perf(methods): 通过移除不必要的 self 参数优化方法签名

在包括 chat、plugin_system、schedule 和 mais4u 在内的多个模块中,消除冗余的实例引用。此次改动将无需访问实例状态的实用函数转换为静态方法,从而提升了内存效率,并使方法依赖关系更加清晰。
This commit is contained in:
雅诺狐
2025-09-20 10:55:06 +08:00
committed by Windpicker-owo
parent aba4f1a947
commit 93542cadef
111 changed files with 705 additions and 465 deletions

View File

@@ -80,7 +80,8 @@ class ChatBot:
# 初始化反注入系统
self._initialize_anti_injector()
def _initialize_anti_injector(self):
@staticmethod
def _initialize_anti_injector():
"""初始化反注入系统"""
try:
initialize_anti_injector()
@@ -100,7 +101,8 @@ class ChatBot:
self._started = True
async def _process_plus_commands(self, message: MessageRecv):
@staticmethod
async def _process_plus_commands(message: MessageRecv):
"""独立处理PlusCommand系统"""
try:
text = message.processed_plain_text
@@ -220,7 +222,8 @@ class ChatBot:
logger.error(f"处理PlusCommand时出错: {e}")
return False, None, True # 出错时继续处理消息
async def _process_commands_with_new_system(self, message: MessageRecv):
@staticmethod
async def _process_commands_with_new_system(message: MessageRecv):
# sourcery skip: use-named-expression
"""使用新插件系统处理命令"""
try:
@@ -310,7 +313,8 @@ class ChatBot:
return False
async def handle_adapter_response(self, message: MessageRecv):
@staticmethod
async def handle_adapter_response(message: MessageRecv):
"""处理适配器命令响应"""
try:
from src.plugin_system.apis.send_api import put_adapter_response

View File

@@ -203,7 +203,8 @@ class ChatManager:
key = "_".join(components)
return hashlib.md5(key.encode()).hexdigest()
def get_stream_id(self, platform: str, id: str, is_group: bool = True) -> str:
@staticmethod
def get_stream_id(platform: str, id: str, is_group: bool = True) -> str:
"""获取聊天流ID"""
components = [platform, id] if is_group else [platform, id, "private"]
key = "_".join(components)

View File

@@ -1,19 +1,18 @@
import time
import urllib3
import base64
from abc import abstractmethod
import time
from abc import abstractmethod, ABCMeta
from dataclasses import dataclass
from rich.traceback import install
from typing import Optional, Any, List
from maim_message import Seg, UserInfo, BaseMessageInfo, MessageBase
from typing import Optional, Any
import urllib3
from maim_message import Seg, UserInfo, BaseMessageInfo, MessageBase
from rich.traceback import install
from src.common.logger import get_logger
from src.chat.utils.utils_image import get_image_manager
from src.chat.utils.utils_voice import get_voice_text
from src.chat.utils.utils_video import get_video_analyzer, is_video_analysis_available
from src.chat.utils.utils_voice import get_voice_text
from src.common.logger import get_logger
from src.config.config import global_config
from .chat_stream import ChatStream
install(extra_lines=3)
@@ -28,7 +27,7 @@ urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
@dataclass
class Message(MessageBase):
class Message(MessageBase, metaclass=ABCMeta):
chat_stream: "ChatStream" = None # type: ignore
reply: Optional["Message"] = None
processed_plain_text: str = ""
@@ -96,12 +95,13 @@ class Message(MessageBase):
class MessageRecv(Message):
"""接收消息类用于处理从MessageCQ序列化的消息"""
def __init__(self, message_dict: dict[str, Any]):
def __init__(self, message_dict: dict[str, Any], message_id: str, chat_stream: "ChatStream", user_info: UserInfo):
"""从MessageCQ的字典初始化
Args:
message_dict: MessageCQ序列化后的字典
"""
super().__init__(message_id, chat_stream, user_info)
self.message_info = BaseMessageInfo.from_dict(message_dict.get("message_info", {}))
self.message_segment = Seg.from_dict(message_dict.get("message_segment", {}))
self.raw_message = message_dict.get("raw_message")

View File

@@ -1,15 +1,15 @@
import re
import json
import traceback
import orjson
from typing import Union
from src.common.database.sqlalchemy_models import Messages, Images
import orjson
from sqlalchemy import select, desc, update
from src.common.database.sqlalchemy_models import Messages, Images, get_db_session
from src.common.logger import get_logger
from .chat_stream import ChatStream
from .message import MessageSending, MessageRecv
from src.common.database.sqlalchemy_database_api import get_db_session
from sqlalchemy import select, update, desc
logger = get_logger("message_storage")
@@ -117,21 +117,13 @@ class MessageStorage:
user_nickname=user_info_dict.get("user_nickname"),
user_cardname=user_info_dict.get("user_cardname"),
processed_plain_text=filtered_processed_plain_text,
display_message=filtered_display_message,
memorized_times=message.memorized_times,
interest_value=interest_value,
priority_mode=priority_mode,
priority_info=priority_info_json,
is_emoji=is_emoji,
is_picid=is_picid,
is_notify=is_notify,
is_command=is_command,
key_words=key_words,
key_words_lite=key_words_lite,
)
async with get_db_session() as session:
session.add(new_message)
await session.commit()
await session.add(new_message)
except Exception:
logger.exception("存储消息失败")
@@ -154,8 +146,7 @@ class MessageStorage:
qq_message_id = message.message_segment.data.get("id")
elif message.message_segment.type == "reply":
qq_message_id = message.message_segment.data.get("id")
if qq_message_id:
logger.debug(f"从reply消息段获取到消息ID: {qq_message_id}")
logger.debug(f"从reply消息段获取到消息ID: {qq_message_id}")
elif message.message_segment.type == "adapter_response":
logger.debug("适配器响应消息不需要更新ID")
return
@@ -198,7 +189,6 @@ class MessageStorage:
f"segment_type={getattr(message.message_segment, 'type', 'N/A')}"
)
@staticmethod
async def replace_image_descriptions(text: str) -> str:
"""将[图片:描述]替换为[picid:image_id]"""
# 先检查文本中是否有图片标记