优化代码格式和异常处理

- 修复异常处理链,使用from语法保留原始异常
- 格式化代码以符合项目规范
- 优化导入模块的顺序

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
春河晴
2025-03-19 20:27:34 +09:00
parent a829dfdb77
commit fdc098d0db
52 changed files with 3156 additions and 2778 deletions

View File

@@ -3,7 +3,6 @@ import time
from random import random
from nonebot.adapters.onebot.v11 import (
Bot,
GroupMessageEvent,
MessageEvent,
PrivateMessageEvent,
NoticeEvent,
@@ -26,18 +25,19 @@ from .chat_stream import chat_manager
from .message_sender import message_manager # 导入新的消息管理器
from .relationship_manager import relationship_manager
from .storage import MessageStorage
from .utils import calculate_typing_time, is_mentioned_bot_in_message
from .utils import is_mentioned_bot_in_message
from .utils_image import image_path_to_base64
from .utils_user import get_user_nickname, get_user_cardname, get_groupname
from .utils_user import get_user_nickname, get_user_cardname
from ..willing.willing_manager import willing_manager # 导入意愿管理器
from .message_base import UserInfo, GroupInfo, Seg
from src.common.logger import get_module_logger, CHAT_STYLE_CONFIG, LogConfig
# 定义日志配置
chat_config = LogConfig(
# 使用消息发送专用样式
console_format=CHAT_STYLE_CONFIG["console_format"],
file_format=CHAT_STYLE_CONFIG["file_format"]
file_format=CHAT_STYLE_CONFIG["file_format"],
)
# 配置主程序日志格式
@@ -84,23 +84,24 @@ class ChatBot:
# 创建聊天流
chat = await chat_manager.get_or_create_stream(
platform=messageinfo.platform, user_info=userinfo, group_info=groupinfo #我嘞个gourp_info
platform=messageinfo.platform,
user_info=userinfo,
group_info=groupinfo, # 我嘞个gourp_info
)
message.update_chat_stream(chat)
await relationship_manager.update_relationship(
chat_stream=chat,
)
await relationship_manager.update_relationship_value(
chat_stream=chat, relationship_value=0
)
await relationship_manager.update_relationship_value(chat_stream=chat, relationship_value=0)
await message.process()
# 过滤词
for word in global_config.ban_words:
if word in message.processed_plain_text:
logger.info(
f"[{chat.group_info.group_name if chat.group_info else '私聊'}]{userinfo.user_nickname}:{message.processed_plain_text}"
f"[{chat.group_info.group_name if chat.group_info else '私聊'}]"
f"{userinfo.user_nickname}:{message.processed_plain_text}"
)
logger.info(f"[过滤词识别]消息中含有{word}filtered")
return
@@ -109,20 +110,17 @@ class ChatBot:
for pattern in global_config.ban_msgs_regex:
if re.search(pattern, message.raw_message):
logger.info(
f"[{chat.group_info.group_name if chat.group_info else '私聊'}]{userinfo.user_nickname}:{message.raw_message}"
f"[{chat.group_info.group_name if chat.group_info else '私聊'}]"
f"{userinfo.user_nickname}:{message.raw_message}"
)
logger.info(f"[正则表达式过滤]消息匹配到{pattern}filtered")
return
current_time = time.strftime(
"%Y-%m-%d %H:%M:%S", time.localtime(messageinfo.time)
)
current_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(messageinfo.time))
#根据话题计算激活度
# 根据话题计算激活度
topic = ""
interested_rate = (
await hippocampus.memory_activate_value(message.processed_plain_text) / 100
)
interested_rate = await hippocampus.memory_activate_value(message.processed_plain_text) / 100
logger.debug(f"{message.processed_plain_text}的激活度:{interested_rate}")
# logger.info(f"\033[1;32m[主题识别]\033[0m 使用{global_config.topic_extract}主题: {topic}")
@@ -140,7 +138,8 @@ class ChatBot:
current_willing = willing_manager.get_willing(chat_stream=chat)
logger.info(
f"[{current_time}][{chat.group_info.group_name if chat.group_info else '私聊'}]{chat.user_info.user_nickname}:"
f"[{current_time}][{chat.group_info.group_name if chat.group_info else '私聊'}]"
f"{chat.user_info.user_nickname}:"
f"{message.processed_plain_text}[回复意愿:{current_willing:.2f}][概率:{reply_probability * 100:.1f}%]"
)
@@ -152,7 +151,7 @@ class ChatBot:
user_nickname=global_config.BOT_NICKNAME,
platform=messageinfo.platform,
)
#开始思考的时间点
# 开始思考的时间点
thinking_time_point = round(time.time(), 2)
logger.info(f"开始思考的时间点: {thinking_time_point}")
think_id = "mt" + str(thinking_time_point)
@@ -181,10 +180,7 @@ class ChatBot:
# 找到message,删除
# print(f"开始找思考消息")
for msg in container.messages:
if (
isinstance(msg, MessageThinking)
and msg.message_info.message_id == think_id
):
if isinstance(msg, MessageThinking) and msg.message_info.message_id == think_id:
# print(f"找到思考消息: {msg}")
thinking_message = msg
container.messages.remove(msg)
@@ -270,12 +266,12 @@ class ChatBot:
# 获取立场和情感标签,更新关系值
stance, emotion = await self.gpt._get_emotion_tags(raw_content, message.processed_plain_text)
logger.debug(f"'{response}' 立场为:{stance} 获取到的情感标签为:{emotion}")
await relationship_manager.calculate_update_relationship_value(chat_stream=chat, label=emotion, stance=stance)
await relationship_manager.calculate_update_relationship_value(
chat_stream=chat, label=emotion, stance=stance
)
# 使用情绪管理器更新情绪
self.mood_manager.update_mood_from_emotion(
emotion[0], global_config.mood_intensity_factor
)
self.mood_manager.update_mood_from_emotion(emotion[0], global_config.mood_intensity_factor)
# willing_manager.change_reply_willing_after_sent(
# chat_stream=chat
@@ -300,31 +296,21 @@ class ChatBot:
raw_message = f"[戳了戳]{global_config.BOT_NICKNAME}" # 默认类型
if info := event.raw_info:
poke_type = info[2].get(
"txt", "戳了戳"
) # 戳戳类型,例如“拍一拍”、“揉一揉”、“捏一捏”
custom_poke_message = info[4].get(
"txt", ""
) # 自定义戳戳消息,若不存在会为空字符串
raw_message = (
f"[{poke_type}]{global_config.BOT_NICKNAME}{custom_poke_message}"
)
poke_type = info[2].get("txt", "戳了戳") # 戳戳类型,例如“拍一拍”、“揉一揉”、“捏一捏”
custom_poke_message = info[4].get("txt", "") # 自定义戳戳消息,若不存在会为空字符串
raw_message = f"[{poke_type}]{global_config.BOT_NICKNAME}{custom_poke_message}"
raw_message += "(这是一个类似摸摸头的友善行为,而不是恶意行为,请不要作出攻击发言)"
user_info = UserInfo(
user_id=event.user_id,
user_nickname=(
await bot.get_stranger_info(user_id=event.user_id, no_cache=True)
)["nickname"],
user_nickname=(await bot.get_stranger_info(user_id=event.user_id, no_cache=True))["nickname"],
user_cardname=None,
platform="qq",
)
if event.group_id:
group_info = GroupInfo(
group_id=event.group_id, group_name=None, platform="qq"
)
group_info = GroupInfo(group_id=event.group_id, group_name=None, platform="qq")
else:
group_info = None
@@ -338,10 +324,8 @@ class ChatBot:
)
await self.message_process(message_cq)
elif isinstance(event, GroupRecallNoticeEvent) or isinstance(
event, FriendRecallNoticeEvent
):
elif isinstance(event, GroupRecallNoticeEvent) or isinstance(event, FriendRecallNoticeEvent):
user_info = UserInfo(
user_id=event.user_id,
user_nickname=get_user_nickname(event.user_id) or None,
@@ -350,9 +334,7 @@ class ChatBot:
)
if isinstance(event, GroupRecallNoticeEvent):
group_info = GroupInfo(
group_id=event.group_id, group_name=None, platform="qq"
)
group_info = GroupInfo(group_id=event.group_id, group_name=None, platform="qq")
else:
group_info = None
@@ -360,9 +342,7 @@ class ChatBot:
platform=user_info.platform, user_info=user_info, group_info=group_info
)
await self.storage.store_recalled_message(
event.message_id, time.time(), chat
)
await self.storage.store_recalled_message(event.message_id, time.time(), chat)
async def handle_message(self, event: MessageEvent, bot: Bot) -> None:
"""处理收到的消息"""
@@ -379,9 +359,7 @@ class ChatBot:
and hasattr(event.reply.sender, "user_id")
and event.reply.sender.user_id in global_config.ban_user_id
):
logger.debug(
f"跳过处理回复来自被ban用户 {event.reply.sender.user_id} 的消息"
)
logger.debug(f"跳过处理回复来自被ban用户 {event.reply.sender.user_id} 的消息")
return
# 处理私聊消息
if isinstance(event, PrivateMessageEvent):
@@ -391,11 +369,7 @@ class ChatBot:
try:
user_info = UserInfo(
user_id=event.user_id,
user_nickname=(
await bot.get_stranger_info(
user_id=event.user_id, no_cache=True
)
)["nickname"],
user_nickname=(await bot.get_stranger_info(user_id=event.user_id, no_cache=True))["nickname"],
user_cardname=None,
platform="qq",
)
@@ -421,9 +395,7 @@ class ChatBot:
platform="qq",
)
group_info = GroupInfo(
group_id=event.group_id, group_name=None, platform="qq"
)
group_info = GroupInfo(group_id=event.group_id, group_name=None, platform="qq")
# group_info = await bot.get_group_info(group_id=event.group_id)
# sender_info = await bot.get_group_member_info(group_id=event.group_id, user_id=event.user_id, no_cache=True)
@@ -439,5 +411,6 @@ class ChatBot:
await self.message_process(message_cq)
# 创建全局ChatBot实例
chat_bot = ChatBot()