This commit is contained in:
Charlie Wang
2025-03-20 22:36:54 +08:00
62 changed files with 3623 additions and 3881 deletions

View File

@@ -4,16 +4,15 @@ import asyncio
from random import random
from nonebot.adapters.onebot.v11 import (
Bot,
GroupMessageEvent,
MessageEvent,
PrivateMessageEvent,
GroupMessageEvent,
NoticeEvent,
PokeNotifyEvent,
GroupRecallNoticeEvent,
FriendRecallNoticeEvent,
)
from src.common.logger import get_module_logger
from ..memory_system.memory import hippocampus
from ..moods.moods import MoodManager # 导入情绪管理器
from .config import global_config
@@ -28,13 +27,23 @@ 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
logger = get_module_logger("chat_bot")
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"],
)
# 配置主程序日志格式
logger = get_module_logger("chat_bot", config=chat_config)
class ChatBot:
@@ -79,15 +88,15 @@ 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()
@@ -109,7 +118,8 @@ class ChatBot:
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
@@ -118,20 +128,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}")
@@ -157,7 +164,8 @@ class ChatBot:
current_willing = willing_manager.get_willing(chat_stream=chat)
actual_prob = random()
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}%]"
)
reply_probability = 1 if is_mentioned else reply_probability
@@ -181,7 +189,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)
@@ -212,10 +220,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)
@@ -301,12 +306,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
@@ -331,31 +336,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
@@ -369,10 +364,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,
@@ -381,9 +374,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
@@ -391,9 +382,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:
"""处理收到的消息"""
@@ -410,9 +399,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):
@@ -422,11 +409,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",
)
@@ -452,9 +435,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)
@@ -470,5 +451,69 @@ class ChatBot:
await self.message_process(message_cq)
async def handle_forward_message(self, event: MessageEvent, bot: Bot) -> None:
"""专用于处理合并转发的消息处理器"""
# 获取合并转发消息的详细信息
forward_info = await bot.get_forward_msg(message_id=event.message_id)
messages = forward_info["messages"]
# 构建合并转发消息的文本表示
processed_messages = []
for node in messages:
# 提取发送者昵称
nickname = node["sender"].get("nickname", "未知用户")
# 处理消息内容
message_content = []
for seg in node["message"]:
if seg["type"] == "text":
message_content.append(seg["data"]["text"])
elif seg["type"] == "image":
message_content.append("[图片]")
elif seg["type"] =="face":
message_content.append("[表情]")
elif seg["type"] == "at":
message_content.append(f"@{seg['data'].get('qq', '未知用户')}")
else:
message_content.append(f"[{seg['type']}]")
# 拼接为【昵称】+ 内容
processed_messages.append(f"{nickname}{''.join(message_content)}")
# 组合所有消息
combined_message = "\n".join(processed_messages)
combined_message = f"合并转发消息内容:\n{combined_message}"
# 构建用户信息(使用转发消息的发送者)
user_info = UserInfo(
user_id=event.user_id,
user_nickname=event.sender.nickname,
user_cardname=event.sender.card if hasattr(event.sender, "card") else None,
platform="qq",
)
# 构建群聊信息(如果是群聊)
group_info = None
if isinstance(event, GroupMessageEvent):
group_info = GroupInfo(
group_id=event.group_id,
group_name= None,
platform="qq"
)
# 创建消息对象
message_cq = MessageRecvCQ(
message_id=event.message_id,
user_info=user_info,
raw_message=combined_message,
group_info=group_info,
reply_message=event.reply,
platform="qq",
)
# 进入标准消息处理流程
await self.message_process(message_cq)
# 创建全局ChatBot实例
chat_bot = ChatBot()