refactor of heart_flow

This commit is contained in:
UnCLAS-Prommer
2025-07-13 10:24:23 +08:00
parent 108d883675
commit f93fa88c27

View File

@@ -1,13 +1,6 @@
import asyncio
import time
import traceback
from typing import Optional, List, Dict, Tuple
from rich.traceback import install from rich.traceback import install
from src.common.logger import get_logger from src.common.logger import get_logger
from src.config.config import global_config
from src.chat.message_receive.message import MessageRecv
from src.chat.message_receive.chat_stream import get_chat_manager from src.chat.message_receive.chat_stream import get_chat_manager
from src.chat.focus_chat.heartFC_chat import HeartFChatting from src.chat.focus_chat.heartFC_chat import HeartFChatting
from src.chat.utils.utils import get_chat_type_and_target_info from src.chat.utils.utils import get_chat_type_and_target_info
@@ -39,7 +32,7 @@ class SubHeartflow:
# 随便水群 normal_chat 和 认真水群 focus_chat 实例 # 随便水群 normal_chat 和 认真水群 focus_chat 实例
# CHAT模式激活 随便水群 FOCUS模式激活 认真水群 # CHAT模式激活 随便水群 FOCUS模式激活 认真水群
self.heart_fc_instance: Optional[HeartFChatting] = HeartFChatting( self.heart_fc_instance: HeartFChatting = HeartFChatting(
chat_id=self.subheartflow_id, chat_id=self.subheartflow_id,
) # 该sub_heartflow的HeartFChatting实例 ) # 该sub_heartflow的HeartFChatting实例
@@ -47,88 +40,89 @@ class SubHeartflow:
"""异步初始化方法,创建兴趣流并确定聊天类型""" """异步初始化方法,创建兴趣流并确定聊天类型"""
await self.heart_fc_instance.start() await self.heart_fc_instance.start()
async def _stop_heart_fc_chat(self): # async def _stop_heart_fc_chat(self):
"""停止并清理 HeartFChatting 实例""" # """停止并清理 HeartFChatting 实例"""
if self.heart_fc_instance.running: # if self.heart_fc_instance.running:
logger.info(f"{self.log_prefix} 结束专注聊天...") # logger.info(f"{self.log_prefix} 结束专注聊天...")
try: # try:
await self.heart_fc_instance.shutdown() # await self.heart_fc_instance.shutdown()
except Exception as e: # except Exception as e:
logger.error(f"{self.log_prefix} 关闭 HeartFChatting 实例时出错: {e}") # logger.error(f"{self.log_prefix} 关闭 HeartFChatting 实例时出错: {e}")
logger.error(traceback.format_exc()) # logger.error(traceback.format_exc())
else: # else:
logger.info(f"{self.log_prefix} 没有专注聊天实例,无需停止专注聊天") # logger.info(f"{self.log_prefix} 没有专注聊天实例,无需停止专注聊天")
async def _start_heart_fc_chat(self) -> bool: # async def _start_heart_fc_chat(self) -> bool:
"""启动 HeartFChatting 实例,确保 NormalChat 已停止""" # """启动 HeartFChatting 实例,确保 NormalChat 已停止"""
try: # try:
# 如果任务已完成或不存在,则尝试重新启动 # # 如果任务已完成或不存在,则尝试重新启动
if self.heart_fc_instance._loop_task is None or self.heart_fc_instance._loop_task.done(): # if self.heart_fc_instance._loop_task is None or self.heart_fc_instance._loop_task.done():
logger.info(f"{self.log_prefix} HeartFChatting 实例存在但循环未运行,尝试启动...") # logger.info(f"{self.log_prefix} HeartFChatting 实例存在但循环未运行,尝试启动...")
try: # try:
# 添加超时保护 # # 添加超时保护
await asyncio.wait_for(self.heart_fc_instance.start(), timeout=15.0) # await asyncio.wait_for(self.heart_fc_instance.start(), timeout=15.0)
logger.info(f"{self.log_prefix} HeartFChatting 循环已启动。") # logger.info(f"{self.log_prefix} HeartFChatting 循环已启动。")
return True # return True
except Exception as e: # except Exception as e:
logger.error(f"{self.log_prefix} 尝试启动现有 HeartFChatting 循环时出错: {e}") # logger.error(f"{self.log_prefix} 尝试启动现有 HeartFChatting 循环时出错: {e}")
logger.error(traceback.format_exc()) # logger.error(traceback.format_exc())
# 出错时清理实例,准备重新创建 # # 出错时清理实例,准备重新创建
self.heart_fc_instance = None # self.heart_fc_instance = None # type: ignore
else: # return False
# 任务正在运行 # else:
logger.debug(f"{self.log_prefix} HeartFChatting 已在运行中。") # # 任务正在运行
return True #在运行 # logger.debug(f"{self.log_prefix} HeartFChatting 已在运行中。")
# return True # 已经在运行
except Exception as e: # except Exception as e:
logger.error(f"{self.log_prefix} _start_heart_fc_chat 执行时出错: {e}") # logger.error(f"{self.log_prefix} _start_heart_fc_chat 执行时出错: {e}")
logger.error(traceback.format_exc()) # logger.error(traceback.format_exc())
return False # return False
def is_in_focus_cooldown(self) -> bool: # def is_in_focus_cooldown(self) -> bool:
"""检查是否在focus模式的冷却期内 # """检查是否在focus模式的冷却期内
Returns: # Returns:
bool: 如果在冷却期内返回True否则返回False # bool: 如果在冷却期内返回True否则返回False
""" # """
if self.last_focus_exit_time == 0: # if self.last_focus_exit_time == 0:
return False # return False
# 基础冷却时间10分钟受auto_focus_threshold调控 # # 基础冷却时间10分钟受auto_focus_threshold调控
base_cooldown = 10 * 60 # 10分钟转换为秒 # base_cooldown = 10 * 60 # 10分钟转换为秒
cooldown_duration = base_cooldown / global_config.chat.auto_focus_threshold # cooldown_duration = base_cooldown / global_config.chat.auto_focus_threshold
current_time = time.time() # current_time = time.time()
elapsed_since_exit = current_time - self.last_focus_exit_time # elapsed_since_exit = current_time - self.last_focus_exit_time
is_cooling = elapsed_since_exit < cooldown_duration # is_cooling = elapsed_since_exit < cooldown_duration
if is_cooling: # if is_cooling:
remaining_time = cooldown_duration - elapsed_since_exit # remaining_time = cooldown_duration - elapsed_since_exit
remaining_minutes = remaining_time / 60 # remaining_minutes = remaining_time / 60
logger.debug( # logger.debug(
f"[{self.log_prefix}] focus冷却中剩余时间: {remaining_minutes:.1f}分钟 (阈值: {global_config.chat.auto_focus_threshold})" # f"[{self.log_prefix}] focus冷却中剩余时间: {remaining_minutes:.1f}分钟 (阈值: {global_config.chat.auto_focus_threshold})"
) # )
return is_cooling # return is_cooling
def get_cooldown_progress(self) -> float: # def get_cooldown_progress(self) -> float:
"""获取冷却进度返回0-1之间的值 # """获取冷却进度返回0-1之间的值
Returns: # Returns:
float: 0表示刚开始冷却1表示冷却完成 # float: 0表示刚开始冷却1表示冷却完成
""" # """
if self.last_focus_exit_time == 0: # if self.last_focus_exit_time == 0:
return 1.0 # 没有冷却返回1表示完全恢复 # return 1.0 # 没有冷却返回1表示完全恢复
# 基础冷却时间10分钟受auto_focus_threshold调控 # # 基础冷却时间10分钟受auto_focus_threshold调控
base_cooldown = 10 * 60 # 10分钟转换为秒 # base_cooldown = 10 * 60 # 10分钟转换为秒
cooldown_duration = base_cooldown / global_config.chat.auto_focus_threshold # cooldown_duration = base_cooldown / global_config.chat.auto_focus_threshold
current_time = time.time() # current_time = time.time()
elapsed_since_exit = current_time - self.last_focus_exit_time # elapsed_since_exit = current_time - self.last_focus_exit_time
if elapsed_since_exit >= cooldown_duration: # if elapsed_since_exit >= cooldown_duration:
return 1.0 # 冷却完成 # return 1.0 # 冷却完成
return elapsed_since_exit / cooldown_duration # return elapsed_since_exit / cooldown_duration