Merge branch 'main-fix' into relationship

This commit is contained in:
meng_xi_pan
2025-03-15 02:37:16 +08:00
5 changed files with 210 additions and 198 deletions

8
run.sh
View File

@@ -97,8 +97,8 @@ check_python() {
# 5/6: 选择分支 # 5/6: 选择分支
choose_branch() { choose_branch() {
BRANCH=$(whiptail --title "🔀 [5/6] 选择 Maimbot 分支" --menu "请选择要安装的 Maimbot 分支:" 15 60 2 \ BRANCH=$(whiptail --title "🔀 [5/6] 选择 Maimbot 分支" --menu "请选择要安装的 Maimbot 分支:" 15 60 2 \
"main" "稳定版本(推荐)" \ "main" "稳定版本(推荐,供下载使用" \
"debug" "开发版本(可能不稳定)" 3>&1 1>&2 2>&3) "main-fix" "生产环境紧急修复" 3>&1 1>&2 2>&3)
if [[ -z "$BRANCH" ]]; then if [[ -z "$BRANCH" ]]; then
BRANCH="main" BRANCH="main"
@@ -201,6 +201,8 @@ install_napcat() {
} }
# 运行安装步骤 # 运行安装步骤
whiptail --title "⚠️ 警告:安装前详阅" --msgbox "项目处于活跃开发阶段,代码可能随时更改\n文档未完善有问题可以提交 Issue 或者 Discussion\nQQ机器人存在被限制风险请自行了解谨慎使用\n由于持续迭代可能存在一些已知或未知的bug\n由于开发中可能消耗较多token\n\n本脚本可能更新不及时如遇到bug请优先尝试手动部署以确定是否为脚本问题" 14 60
check_system check_system
check_mongodb check_mongodb
check_napcat check_napcat
@@ -233,7 +235,7 @@ fi
if [[ "$IS_INSTALL_NAPCAT" == "true" ]]; then if [[ "$IS_INSTALL_NAPCAT" == "true" ]]; then
echo -e "${GREEN}安装 NapCat...${RESET}" echo -e "${GREEN}安装 NapCat...${RESET}"
curl -o napcat.sh https://nclatest.znin.net/NapNeko/NapCat-Installer/main/script/install.sh && bash napcat.sh curl -o napcat.sh https://nclatest.znin.net/NapNeko/NapCat-Installer/main/script/install.sh && bash napcat.sh --cli y --docker n
fi fi
echo -e "${GREEN}创建 Python 虚拟环境...${RESET}" echo -e "${GREEN}创建 Python 虚拟环境...${RESET}"

View File

@@ -55,112 +55,15 @@ class ChatBot:
if not self._started: if not self._started:
self._started = True self._started = True
async def handle_notice(self, event: NoticeEvent, bot: Bot) -> None: async def message_process(self, message_cq: MessageRecvCQ) -> None:
"""处理收到的通知""" """处理转化后的统一格式消息
# 戳一戳通知 1. 过滤消息
if isinstance(event, PokeNotifyEvent): 2. 记忆激活
# 不处理其他人的戳戳 3. 意愿激活
if not event.is_tome(): 4. 生成回复并发送
return 5. 更新关系
6. 更新情绪
# 用户屏蔽,不区分私聊/群聊 """
if event.user_id in global_config.ban_user_id:
return
reply_poke_probability = 1.0 # 回复戳一戳的概率,如果要改可以在这里改,暂不提取到配置文件
if random() < reply_poke_probability:
raw_message = "[戳了戳]你" # 默认类型
if info := event.raw_info:
poke_type = info[2].get("txt", "戳了戳") # 戳戳类型,例如“拍一拍”、“揉一揉”、“捏一捏”
custom_poke_message = info[4].get("txt", "") # 自定义戳戳消息,若不存在会为空字符串
raw_message = f"[{poke_type}]你{custom_poke_message}"
raw_message += "(这是一个类似摸摸头的友善行为,而不是恶意行为,请不要作出攻击发言)"
await self.directly_reply(raw_message, event.user_id, event.group_id)
if 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,
user_cardname=get_user_cardname(event.user_id) or None,
platform="qq",
)
group_info = GroupInfo(group_id=event.group_id, group_name=None, platform="qq")
chat = await chat_manager.get_or_create_stream(
platform=user_info.platform, user_info=user_info, group_info=group_info
)
await self.storage.store_recalled_message(event.message_id, time.time(), chat)
async def handle_message(self, event: MessageEvent, bot: Bot) -> None:
"""处理收到的消息"""
self.bot = bot # 更新 bot 实例
# 用户屏蔽,不区分私聊/群聊
if event.user_id in global_config.ban_user_id:
return
if (
event.reply
and hasattr(event.reply, "sender")
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} 的消息")
return
# 处理私聊消息
if isinstance(event, PrivateMessageEvent):
if not global_config.enable_friend_chat: # 私聊过滤
return
else:
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_cardname=None,
platform="qq",
)
except Exception as e:
logger.error(f"获取陌生人信息失败: {e}")
return
logger.debug(user_info)
# group_info = GroupInfo(group_id=0, group_name="私聊", platform="qq")
group_info = None
# 处理群聊消息
else:
# 白名单设定由nontbot侧完成
if event.group_id:
if event.group_id not in global_config.talk_allowed_groups:
return
user_info = UserInfo(
user_id=event.user_id,
user_nickname=event.sender.nickname,
user_cardname=event.sender.card or 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)
message_cq = MessageRecvCQ(
message_id=event.message_id,
user_info=user_info,
raw_message=str(event.original_message),
group_info=group_info,
reply_message=event.reply,
platform="qq",
)
await message_cq.initialize() await message_cq.initialize()
message_json = message_cq.to_dict() message_json = message_cq.to_dict()
# 哦我嘞个json # 哦我嘞个json
@@ -181,7 +84,9 @@ class ChatBot:
await relationship_manager.update_relationship( await relationship_manager.update_relationship(
chat_stream=chat, chat_stream=chat,
) )
await relationship_manager.update_relationship_value(chat_stream=chat, relationship_value=0.5) await relationship_manager.update_relationship_value(
chat_stream=chat, relationship_value=0.5
)
await message.process() await message.process()
@@ -203,11 +108,15 @@ class ChatBot:
logger.info(f"[正则表达式过滤]消息匹配到{pattern}filtered") logger.info(f"[正则表达式过滤]消息匹配到{pattern}filtered")
return 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 = "" 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.debug(f"{message.processed_plain_text}的激活度:{interested_rate}")
# logger.info(f"\033[1;32m[主题识别]\033[0m 使用{global_config.topic_extract}主题: {topic}") # logger.info(f"\033[1;32m[主题识别]\033[0m 使用{global_config.topic_extract}主题: {topic}")
@@ -216,7 +125,6 @@ class ChatBot:
is_mentioned = is_mentioned_bot_in_message(message) is_mentioned = is_mentioned_bot_in_message(message)
reply_probability = await willing_manager.change_reply_willing_received( reply_probability = await willing_manager.change_reply_willing_received(
chat_stream=chat, chat_stream=chat,
topic=topic[0] if topic else None,
is_mentioned_bot=is_mentioned, is_mentioned_bot=is_mentioned,
config=global_config, config=global_config,
is_emoji=message.is_emoji, is_emoji=message.is_emoji,
@@ -264,7 +172,10 @@ class ChatBot:
# 找到message,删除 # 找到message,删除
# print(f"开始找思考消息") # print(f"开始找思考消息")
for msg in container.messages: 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}") # print(f"找到思考消息: {msg}")
thinking_message = msg thinking_message = msg
container.messages.remove(msg) container.messages.remove(msg)
@@ -349,79 +260,168 @@ class ChatBot:
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( # willing_manager.change_reply_willing_after_sent(
# chat_stream=chat # chat_stream=chat
# ) # )
async def directly_reply(self, raw_message: str, user_id: int, group_id: int): async def handle_notice(self, event: NoticeEvent, bot: Bot) -> None:
""" """处理收到的通知"""
直接回复发来的消息,不经过意愿管理器 if isinstance(event, PokeNotifyEvent):
""" # 戳一戳 通知
# 不处理其他人的戳戳
if not event.is_tome():
return
# 构造用户信息和群组信息 # 用户屏蔽,不区分私聊/群聊
user_info = UserInfo( if event.user_id in global_config.ban_user_id:
user_id=user_id, return
user_nickname=get_user_nickname(user_id) or None,
user_cardname=get_user_cardname(user_id) or None, # 白名单模式
platform="qq", if event.group_id:
) if event.group_id not in global_config.talk_allowed_groups:
group_info = GroupInfo(group_id=group_id, group_name=None, platform="qq") return
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}"
)
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_cardname=None,
platform="qq",
)
if event.group_id:
group_info = GroupInfo(
group_id=event.group_id, group_name=None, platform="qq"
)
else:
group_info = None
message_cq = MessageRecvCQ(
message_id=0,
user_info=user_info,
raw_message=str(raw_message),
group_info=group_info,
reply_message=None,
platform="qq",
)
await self.message_process(message_cq)
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,
user_cardname=get_user_cardname(event.user_id) or None,
platform="qq",
)
group_info = GroupInfo(
group_id=event.group_id, group_name=None, platform="qq"
)
chat = await chat_manager.get_or_create_stream(
platform=user_info.platform, user_info=user_info, group_info=group_info
)
await self.storage.store_recalled_message(
event.message_id, time.time(), chat
)
async def handle_message(self, event: MessageEvent, bot: Bot) -> None:
"""处理收到的消息"""
self.bot = bot # 更新 bot 实例
# 用户屏蔽,不区分私聊/群聊
if event.user_id in global_config.ban_user_id:
return
if (
event.reply
and hasattr(event.reply, "sender")
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} 的消息"
)
return
# 处理私聊消息
if isinstance(event, PrivateMessageEvent):
if not global_config.enable_friend_chat: # 私聊过滤
return
else:
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_cardname=None,
platform="qq",
)
except Exception as e:
logger.error(f"获取陌生人信息失败: {e}")
return
logger.debug(user_info)
# group_info = GroupInfo(group_id=0, group_name="私聊", platform="qq")
group_info = None
# 处理群聊消息
else:
# 白名单设定由nontbot侧完成
if event.group_id:
if event.group_id not in global_config.talk_allowed_groups:
return
user_info = UserInfo(
user_id=event.user_id,
user_nickname=event.sender.nickname,
user_cardname=event.sender.card or 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)
message_cq = MessageRecvCQ( message_cq = MessageRecvCQ(
message_id=None, message_id=event.message_id,
user_info=user_info, user_info=user_info,
raw_message=raw_message, raw_message=str(event.original_message),
group_info=group_info, group_info=group_info,
reply_message=None, reply_message=event.reply,
platform="qq", platform="qq",
) )
await message_cq.initialize()
message_json = message_cq.to_dict()
message = MessageRecv(message_json)
groupinfo = message.message_info.group_info
userinfo = message.message_info.user_info
messageinfo = message.message_info
chat = await chat_manager.get_or_create_stream(
platform=messageinfo.platform, user_info=userinfo, group_info=groupinfo
)
message.update_chat_stream(chat)
await message.process()
bot_user_info = UserInfo(
user_id=global_config.BOT_QQ,
user_nickname=global_config.BOT_NICKNAME,
platform=messageinfo.platform,
)
current_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(messageinfo.time))
logger.info(
f"[{current_time}][{chat.group_info.group_name if chat.group_info else '私聊'}]{chat.user_info.user_nickname}:"
f"{message.processed_plain_text}"
)
# 使用大模型生成回复
response, raw_content = await self.gpt.generate_response(message)
if response:
for msg in response:
message_segment = Seg(type="text", data=msg)
bot_message = MessageSending(
message_id=None,
chat_stream=chat,
bot_user_info=bot_user_info,
sender_info=userinfo,
message_segment=message_segment,
reply=None,
is_head=False,
is_emoji=False,
)
message_manager.add_message(bot_message)
await self.message_process(message_cq)
# 创建全局ChatBot实例 # 创建全局ChatBot实例
chat_bot = ChatBot() chat_bot = ChatBot()

View File

@@ -11,10 +11,9 @@ class WillingManager:
async def _decay_reply_willing(self): async def _decay_reply_willing(self):
"""定期衰减回复意愿""" """定期衰减回复意愿"""
while True: while True:
await asyncio.sleep(3) await asyncio.sleep(1)
for chat_id in self.chat_reply_willing: for chat_id in self.chat_reply_willing:
# 每分钟衰减10%的回复意愿 self.chat_reply_willing[chat_id] = max(0, self.chat_reply_willing[chat_id] * 0.9)
self.chat_reply_willing[chat_id] = max(0, self.chat_reply_willing[chat_id] * 0.6)
def get_willing(self, chat_stream: ChatStream) -> float: def get_willing(self, chat_stream: ChatStream) -> float:
"""获取指定聊天流的回复意愿""" """获取指定聊天流的回复意愿"""
@@ -28,7 +27,6 @@ class WillingManager:
async def change_reply_willing_received(self, async def change_reply_willing_received(self,
chat_stream: ChatStream, chat_stream: ChatStream,
topic: str = None,
is_mentioned_bot: bool = False, is_mentioned_bot: bool = False,
config = None, config = None,
is_emoji: bool = False, is_emoji: bool = False,
@@ -37,14 +35,14 @@ class WillingManager:
"""改变指定聊天流的回复意愿并返回回复概率""" """改变指定聊天流的回复意愿并返回回复概率"""
chat_id = chat_stream.stream_id chat_id = chat_stream.stream_id
current_willing = self.chat_reply_willing.get(chat_id, 0) current_willing = self.chat_reply_willing.get(chat_id, 0)
if topic and current_willing < 1: interested_rate = interested_rate * config.response_interested_rate_amplifier
current_willing += 0.2
elif topic: if interested_rate > 0.5:
current_willing += 0.05 current_willing += (interested_rate - 0.5)
if is_mentioned_bot and current_willing < 1.0: if is_mentioned_bot and current_willing < 1.0:
current_willing += 0.9 current_willing += 1
elif is_mentioned_bot: elif is_mentioned_bot:
current_willing += 0.05 current_willing += 0.05
@@ -53,7 +51,8 @@ class WillingManager:
self.chat_reply_willing[chat_id] = min(current_willing, 3.0) self.chat_reply_willing[chat_id] = min(current_willing, 3.0)
reply_probability = (current_willing - 0.5) * 2
reply_probability = min(max((current_willing - 0.5),0.03)* config.response_willing_amplifier * 2,1)
# 检查群组权限(如果是群聊) # 检查群组权限(如果是群聊)
if chat_stream.group_info and config: if chat_stream.group_info and config:
@@ -63,9 +62,6 @@ class WillingManager:
if chat_stream.group_info.group_id in config.talk_frequency_down_groups: if chat_stream.group_info.group_id in config.talk_frequency_down_groups:
reply_probability = reply_probability / 3.5 reply_probability = reply_probability / 3.5
if is_mentioned_bot and sender_id == "1026294844":
reply_probability = 1
return reply_probability return reply_probability

View File

@@ -20,14 +20,14 @@ alias_names = ["小麦", "阿麦"]
[personality] [personality]
prompt_personality = [ prompt_personality = [
"曾经是一个学习地质的女大学生,现在学习心理学和脑科学,你会刷贴吧", # 贴吧人格 "用一句话或几句话描述性格特点和其他特征",
"是一个女大学生,你有黑色头发,你会刷小红书", # 小红书人格 "用一句话或几句话描述性格特点和其他特征",
"是一个女大学生你会刷b站对ACG文化感兴趣" # b站人格 "例如,是一个热爱国家热爱党的新时代好青年"
] ]
personality_1_probability = 0.6 # 第一种人格出现概率 personality_1_probability = 0.6 # 第一种人格出现概率
personality_2_probability = 0.3 # 第二种人格出现概率 personality_2_probability = 0.3 # 第二种人格出现概率
personality_3_probability = 0.1 # 第三种人格出现概率请确保三个概率相加等于1 personality_3_probability = 0.1 # 第三种人格出现概率请确保三个概率相加等于1
prompt_schedule = "一个曾经学习地质,现在学习心理学和脑科学的女大学生喜欢刷qq贴吧知乎和小红书" prompt_schedule = "用一句话或几句话描述描述性格特点和其他特征"
[message] [message]
min_text_length = 2 # 与麦麦聊天时麦麦只会回答文本大于等于此数的消息 min_text_length = 2 # 与麦麦聊天时麦麦只会回答文本大于等于此数的消息

View File

@@ -165,7 +165,10 @@ def format_list_to_str_alias(lst):
format_list_to_str([1, "two", 3.0]) format_list_to_str([1, "two", 3.0])
'[1, "two", 3.0]' '[1, "two", 3.0]'
""" """
resarr = lst.split(", ") resarr = []
if len(lst) != 0:
resarr = lst.split(", ")
return resarr return resarr
def format_list_to_int(lst): def format_list_to_int(lst):
@@ -208,7 +211,18 @@ def save_trigger(server_address, server_port, final_result_list,t_mongodb_host,t
#============================================== #==============================================
#主要配置文件保存函数 #主要配置文件保存函数
def save_config_to_file(t_config_data): def save_config_to_file(t_config_data):
with open("config/bot_config.toml", "w", encoding="utf-8") as f: filename = "config/bot_config.toml"
backup_filename = f"{filename}.bak"
if not os.path.exists(backup_filename):
if os.path.exists(filename):
logger.info(f"{filename} 已存在,正在备份到 {backup_filename}...")
shutil.copy(filename, backup_filename) # 备份文件
logger.success(f"文件已备份到 {backup_filename}")
else:
logger.warning(f"{filename} 不存在,无法进行备份。")
with open(filename, "w", encoding="utf-8") as f:
toml.dump(t_config_data, f) toml.dump(t_config_data, f)
logger.success("配置已保存到 bot_config.toml 文件中") logger.success("配置已保存到 bot_config.toml 文件中")
def save_bot_config(t_qqbot_qq, t_nickname,t_nickname_final_result): def save_bot_config(t_qqbot_qq, t_nickname,t_nickname_final_result):
@@ -729,24 +743,24 @@ with gr.Blocks(title="MaimBot配置文件编辑") as app:
with gr.Row(): with gr.Row():
ban_msgs_regex_list_display = gr.TextArea( ban_msgs_regex_list_display = gr.TextArea(
value="\n".join(ban_msgs_regex_list), value="\n".join(ban_msgs_regex_list),
label="违禁列表", label="违禁消息正则列表",
interactive=False, interactive=False,
lines=5 lines=5
) )
with gr.Row(): with gr.Row():
with gr.Column(scale=3): with gr.Column(scale=3):
ban_msgs_regex_new_item_input = gr.Textbox(label="添加新违禁") ban_msgs_regex_new_item_input = gr.Textbox(label="添加新违禁消息正则")
ban_msgs_regex_add_btn = gr.Button("添加", scale=1) ban_msgs_regex_add_btn = gr.Button("添加", scale=1)
with gr.Row(): with gr.Row():
with gr.Column(scale=3): with gr.Column(scale=3):
ban_msgs_regex_item_to_delete = gr.Dropdown( ban_msgs_regex_item_to_delete = gr.Dropdown(
choices=ban_msgs_regex_list, choices=ban_msgs_regex_list,
label="选择要删除的违禁" label="选择要删除的违禁消息正则"
) )
ban_msgs_regex_delete_btn = gr.Button("删除", scale=1) ban_msgs_regex_delete_btn = gr.Button("删除", scale=1)
ban_msgs_regex_final_result = gr.Text(label="修改后的违禁") ban_msgs_regex_final_result = gr.Text(label="修改后的违禁消息正则")
ban_msgs_regex_add_btn.click( ban_msgs_regex_add_btn.click(
add_item, add_item,
inputs=[ban_msgs_regex_new_item_input, ban_msgs_regex_list_state], inputs=[ban_msgs_regex_new_item_input, ban_msgs_regex_list_state],