perf(methods): 通过移除不必要的 self 参数优化方法签名
在包括 chat、plugin_system、schedule 和 mais4u 在内的多个模块中,消除冗余的实例引用。此次改动将无需访问实例状态的实用函数转换为静态方法,从而提升了内存效率,并使方法依赖关系更加清晰。
This commit is contained in:
@@ -118,7 +118,7 @@ class ChatAction:
|
||||
self.regression_count = 0
|
||||
|
||||
message_time: float = message.message_info.time # type: ignore
|
||||
message_list_before_now = get_raw_msg_by_timestamp_with_chat_inclusive(
|
||||
message_list_before_now = await get_raw_msg_by_timestamp_with_chat_inclusive(
|
||||
chat_id=self.chat_id,
|
||||
timestamp_start=self.last_change_time,
|
||||
timestamp_end=message_time,
|
||||
@@ -182,7 +182,7 @@ class ChatAction:
|
||||
|
||||
async def regress_action(self):
|
||||
message_time = time.time()
|
||||
message_list_before_now = get_raw_msg_by_timestamp_with_chat_inclusive(
|
||||
message_list_before_now = await get_raw_msg_by_timestamp_with_chat_inclusive(
|
||||
chat_id=self.chat_id,
|
||||
timestamp_start=self.last_change_time,
|
||||
timestamp_end=message_time,
|
||||
|
||||
@@ -58,7 +58,8 @@ class MessageSenderContainer:
|
||||
"""恢复发送。"""
|
||||
self._paused_event.set()
|
||||
|
||||
def _calculate_typing_delay(self, text: str) -> float:
|
||||
@staticmethod
|
||||
def _calculate_typing_delay(text: str) -> float:
|
||||
"""根据文本长度计算模拟打字延迟。"""
|
||||
chars_per_second = s4u_config.chars_per_second
|
||||
min_delay = s4u_config.min_typing_delay
|
||||
@@ -150,6 +151,10 @@ class MessageSenderContainer:
|
||||
if self._task:
|
||||
await self._task
|
||||
|
||||
@property
|
||||
def task(self):
|
||||
return self._task
|
||||
|
||||
|
||||
class S4UChatManager:
|
||||
def __init__(self):
|
||||
@@ -177,6 +182,7 @@ class S4UChat:
|
||||
def __init__(self, chat_stream: ChatStream):
|
||||
"""初始化 S4UChat 实例。"""
|
||||
|
||||
self.last_msg_id = self.msg_id
|
||||
self.chat_stream = chat_stream
|
||||
self.stream_id = chat_stream.stream_id
|
||||
self.stream_name = get_chat_manager().get_stream_name(self.stream_id) or self.stream_id
|
||||
@@ -206,7 +212,8 @@ class S4UChat:
|
||||
|
||||
logger.info(f"[{self.stream_name}] S4UChat with two-queue system initialized.")
|
||||
|
||||
def _get_priority_info(self, message: MessageRecv) -> dict:
|
||||
@staticmethod
|
||||
def _get_priority_info(message: MessageRecv) -> dict:
|
||||
"""安全地从消息中提取和解析 priority_info"""
|
||||
priority_info_raw = message.priority_info
|
||||
priority_info = {}
|
||||
@@ -219,7 +226,8 @@ class S4UChat:
|
||||
priority_info = priority_info_raw
|
||||
return priority_info
|
||||
|
||||
def _is_vip(self, priority_info: dict) -> bool:
|
||||
@staticmethod
|
||||
def _is_vip(priority_info: dict) -> bool:
|
||||
"""检查消息是否来自VIP用户。"""
|
||||
return priority_info.get("message_type") == "vip"
|
||||
|
||||
@@ -468,7 +476,6 @@ class S4UChat:
|
||||
await asyncio.sleep(1)
|
||||
|
||||
def get_processing_message_id(self):
|
||||
self.last_msg_id = self.msg_id
|
||||
self.msg_id = f"{time.time()}_{random.randint(1000, 9999)}"
|
||||
|
||||
async def _generate_and_send(self, message: MessageRecv):
|
||||
@@ -565,7 +572,7 @@ class S4UChat:
|
||||
|
||||
# 确保发送器被妥善关闭(即使已关闭,再次调用也是安全的)
|
||||
sender_container.resume()
|
||||
if not sender_container._task.done():
|
||||
if not sender_container.task.done():
|
||||
await sender_container.close()
|
||||
await sender_container.join()
|
||||
logger.info(f"[{self.stream_name}] _generate_and_send 任务结束,资源已清理。")
|
||||
@@ -586,3 +593,7 @@ class S4UChat:
|
||||
await self._processing_task
|
||||
except asyncio.CancelledError:
|
||||
logger.info(f"处理任务已成功取消: {self.stream_name}")
|
||||
|
||||
@property
|
||||
def new_message_event(self):
|
||||
return self._new_message_event
|
||||
|
||||
@@ -124,7 +124,8 @@ class ChatMood:
|
||||
# 发送初始情绪状态到ws端
|
||||
asyncio.create_task(self.send_emotion_update(self.mood_values))
|
||||
|
||||
def _parse_numerical_mood(self, response: str) -> dict[str, int] | None:
|
||||
@staticmethod
|
||||
def _parse_numerical_mood(response: str) -> dict[str, int] | None:
|
||||
try:
|
||||
# The LLM might output markdown with json inside
|
||||
if "```json" in response:
|
||||
|
||||
@@ -161,7 +161,8 @@ class S4UMessageProcessor:
|
||||
else:
|
||||
logger.info(f"[S4U]{userinfo.user_nickname}:{message.processed_plain_text}")
|
||||
|
||||
async def handle_internal_message(self, message: MessageRecvS4U):
|
||||
@staticmethod
|
||||
async def handle_internal_message(message: MessageRecvS4U):
|
||||
if message.is_internal:
|
||||
group_info = GroupInfo(platform="amaidesu_default", group_id=660154, group_name="内心")
|
||||
|
||||
@@ -173,7 +174,7 @@ class S4UMessageProcessor:
|
||||
message.message_info.platform = s4u_chat.chat_stream.platform
|
||||
|
||||
s4u_chat.internal_message.append(message)
|
||||
s4u_chat._new_message_event.set()
|
||||
s4u_chat.new_message_event.set()
|
||||
|
||||
logger.info(
|
||||
f"[{s4u_chat.stream_name}] 添加内部消息-------------------------------------------------------: {message.processed_plain_text}"
|
||||
@@ -182,20 +183,23 @@ class S4UMessageProcessor:
|
||||
return True
|
||||
return False
|
||||
|
||||
async def handle_screen_message(self, message: MessageRecvS4U):
|
||||
@staticmethod
|
||||
async def handle_screen_message(message: MessageRecvS4U):
|
||||
if message.is_screen:
|
||||
screen_manager.set_screen(message.screen_info)
|
||||
return True
|
||||
return False
|
||||
|
||||
async def hadle_if_voice_done(self, message: MessageRecvS4U):
|
||||
@staticmethod
|
||||
async def hadle_if_voice_done(message: MessageRecvS4U):
|
||||
if message.voice_done:
|
||||
s4u_chat = get_s4u_chat_manager().get_or_create_chat(message.chat_stream)
|
||||
s4u_chat.voice_done = message.voice_done
|
||||
return True
|
||||
return False
|
||||
|
||||
async def check_if_fake_gift(self, message: MessageRecvS4U) -> bool:
|
||||
@staticmethod
|
||||
async def check_if_fake_gift(message: MessageRecvS4U) -> bool:
|
||||
"""检查消息是否为假礼物"""
|
||||
if message.is_gift:
|
||||
return False
|
||||
@@ -227,7 +231,8 @@ class S4UMessageProcessor:
|
||||
|
||||
return True # 非礼物消息,继续正常处理
|
||||
|
||||
async def _handle_context_web_update(self, chat_id: str, message: MessageRecv):
|
||||
@staticmethod
|
||||
async def _handle_context_web_update(chat_id: str, message: MessageRecv):
|
||||
"""处理上下文网页更新的独立task
|
||||
|
||||
Args:
|
||||
|
||||
@@ -98,7 +98,8 @@ class PromptBuilder:
|
||||
self.prompt_built = ""
|
||||
self.activate_messages = ""
|
||||
|
||||
async def build_expression_habits(self, chat_stream: ChatStream, chat_history, target):
|
||||
@staticmethod
|
||||
async def build_expression_habits(chat_stream: ChatStream, chat_history, target):
|
||||
style_habits = []
|
||||
grammar_habits = []
|
||||
|
||||
@@ -133,7 +134,8 @@ class PromptBuilder:
|
||||
|
||||
return expression_habits_block
|
||||
|
||||
async def build_relation_info(self, chat_stream) -> str:
|
||||
@staticmethod
|
||||
async def build_relation_info(chat_stream) -> str:
|
||||
is_group_chat = bool(chat_stream.group_info)
|
||||
who_chat_in_group = []
|
||||
if is_group_chat:
|
||||
@@ -167,7 +169,8 @@ class PromptBuilder:
|
||||
)
|
||||
return relation_prompt
|
||||
|
||||
async def build_memory_block(self, text: str) -> str:
|
||||
@staticmethod
|
||||
async def build_memory_block(text: str) -> str:
|
||||
related_memory = await hippocampus_manager.get_memory_from_text(
|
||||
text=text, max_memory_num=2, max_memory_length=2, max_depth=3, fast_retrieval=False
|
||||
)
|
||||
@@ -179,7 +182,8 @@ class PromptBuilder:
|
||||
return await global_prompt_manager.format_prompt("memory_prompt", memory_info=related_memory_info)
|
||||
return ""
|
||||
|
||||
def build_chat_history_prompts(self, chat_stream: ChatStream, message: MessageRecvS4U):
|
||||
@staticmethod
|
||||
def build_chat_history_prompts(chat_stream: ChatStream, message: MessageRecvS4U):
|
||||
message_list_before_now = get_raw_msg_before_timestamp_with_chat(
|
||||
chat_id=chat_stream.stream_id,
|
||||
timestamp=time.time(),
|
||||
@@ -270,7 +274,8 @@ class PromptBuilder:
|
||||
|
||||
return core_msg_str, background_dialogue_prompt, all_dialogue_prompt_str
|
||||
|
||||
def build_gift_info(self, message: MessageRecvS4U):
|
||||
@staticmethod
|
||||
def build_gift_info(message: MessageRecvS4U):
|
||||
if message.is_gift:
|
||||
return f"这是一条礼物信息,{message.gift_name} x{message.gift_count},请注意这位用户"
|
||||
else:
|
||||
@@ -279,7 +284,8 @@ class PromptBuilder:
|
||||
|
||||
return ""
|
||||
|
||||
def build_sc_info(self, message: MessageRecvS4U):
|
||||
@staticmethod
|
||||
def build_sc_info(message: MessageRecvS4U):
|
||||
super_chat_manager = get_super_chat_manager()
|
||||
return super_chat_manager.build_superchat_summary_string(message.chat_stream.stream_id)
|
||||
|
||||
|
||||
@@ -49,7 +49,8 @@ class S4UStreamGenerator:
|
||||
|
||||
self.chat_stream = None
|
||||
|
||||
async def build_last_internal_message(self, message: MessageRecvS4U, previous_reply_context: str = ""):
|
||||
@staticmethod
|
||||
async def build_last_internal_message(message: MessageRecvS4U, previous_reply_context: str = ""):
|
||||
# person_id = PersonInfoManager.get_person_id(
|
||||
# message.chat_stream.user_info.platform, message.chat_stream.user_info.user_id
|
||||
# )
|
||||
|
||||
@@ -105,7 +105,8 @@ class SuperChatManager:
|
||||
logger.error(f"清理过期SuperChat时出错: {e}", exc_info=True)
|
||||
await asyncio.sleep(60) # 出错时等待更长时间
|
||||
|
||||
def _calculate_expire_time(self, price: float) -> float:
|
||||
@staticmethod
|
||||
def _calculate_expire_time(price: float) -> float:
|
||||
"""根据SuperChat金额计算过期时间"""
|
||||
current_time = time.time()
|
||||
|
||||
|
||||
Reference in New Issue
Block a user