Merge branch 'main-fix' of github.com:SengokuCola/MaiMBot into main-fix-friendtalk

This commit is contained in:
Oct-autumn
2025-03-15 03:06:50 +08:00
17 changed files with 1662 additions and 242 deletions

Binary file not shown.

4
run-WebUI.bat Normal file
View File

@@ -0,0 +1,4 @@
CHCP 65001
@echo off
python webui.py
pause

8
run.sh
View File

@@ -97,8 +97,8 @@ check_python() {
# 5/6: 选择分支
choose_branch() {
BRANCH=$(whiptail --title "🔀 [5/6] 选择 Maimbot 分支" --menu "请选择要安装的 Maimbot 分支:" 15 60 2 \
"main" "稳定版本(推荐)" \
"debug" "开发版本(可能不稳定)" 3>&1 1>&2 2>&3)
"main" "稳定版本(推荐,供下载使用" \
"main-fix" "生产环境紧急修复" 3>&1 1>&2 2>&3)
if [[ -z "$BRANCH" ]]; then
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_mongodb
check_napcat
@@ -233,7 +235,7 @@ fi
if [[ "$IS_INSTALL_NAPCAT" == "true" ]]; then
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
echo -e "${GREEN}创建 Python 虚拟环境...${RESET}"

View File

@@ -15,7 +15,7 @@ from .bot import chat_bot
from .config import global_config
from .emoji_manager import emoji_manager
from .relationship_manager import relationship_manager
from .willing_manager import willing_manager
from ..willing.willing_manager import willing_manager
from .chat_stream import chat_manager
from ..memory_system.memory import hippocampus, memory_graph
from .bot import ChatBot

View File

@@ -29,7 +29,7 @@ from .storage import MessageStorage
from .utils import calculate_typing_time, 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 .willing_manager import willing_manager # 导入意愿管理器
from ..willing.willing_manager import willing_manager # 导入意愿管理器
from .message_base import UserInfo, GroupInfo, Seg
from ..utils.logger_config import LogClassification, LogModule
@@ -55,117 +55,18 @@ class ChatBot:
if not self._started:
self._started = True
async def handle_notice(self, event: NoticeEvent, bot: Bot) -> None:
"""处理收到的通知"""
# 戳一戳通知
if isinstance(event, PokeNotifyEvent):
# 不处理其他人的戳戳
if not event.is_tome():
return
# 用户屏蔽,不区分私聊/群聊
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",
)
if isinstance(event, GroupRecallNoticeEvent):
group_info = GroupInfo(
group_id=event.group_id, group_name=None, platform="qq"
)
else:
group_info = None
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",
)
async def message_process(self, message_cq: MessageRecvCQ) -> None:
"""处理转化后的统一格式消息
1. 过滤消息
2. 记忆激活
3. 意愿激活
4. 生成回复并发送
5. 更新关系
6. 更新情绪
"""
await message_cq.initialize()
message_json = message_cq.to_dict()
# 哦我嘞个json
# 进入maimbot
message = MessageRecv(message_json)
@@ -175,16 +76,20 @@ class ChatBot:
# 消息过滤涉及到config有待更新
# 创建聊天流
chat = await chat_manager.get_or_create_stream(
platform=messageinfo.platform, user_info=userinfo, group_info=groupinfo
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.5)
await relationship_manager.update_relationship_value(
chat_stream=chat, relationship_value=0.5
)
await message.process()
# 过滤词
for word in global_config.ban_words:
if word in message.processed_plain_text:
@@ -203,12 +108,15 @@ class ChatBot:
logger.info(f"[正则表达式过滤]消息匹配到{pattern}filtered")
return
current_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(messageinfo.time))
# topic=await topic_identifier.identify_topic_llm(message.processed_plain_text)
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}")
@@ -217,7 +125,6 @@ class ChatBot:
is_mentioned = is_mentioned_bot_in_message(message)
reply_probability = await willing_manager.change_reply_willing_received(
chat_stream=chat,
topic=topic[0] if topic else None,
is_mentioned_bot=is_mentioned,
config=global_config,
is_emoji=message.is_emoji,
@@ -265,7 +172,10 @@ 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)
@@ -359,79 +269,171 @@ class ChatBot:
chat_stream=chat, relationship_value=valuedict[emotion[0]]
)
# 使用情绪管理器更新情绪
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
# )
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(
user_id=user_id,
user_nickname=get_user_nickname(user_id) or None,
user_cardname=get_user_cardname(user_id) or None,
platform="qq",
)
group_info = GroupInfo(group_id=group_id, group_name=None, platform="qq")
# 用户屏蔽,不区分私聊/群聊
if event.user_id in global_config.ban_user_id:
return
# 白名单模式
if event.group_id:
if event.group_id not in global_config.talk_allowed_groups:
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",
)
if isinstance(event, GroupRecallNoticeEvent):
group_info = GroupInfo(
group_id=event.group_id, group_name=None, platform="qq"
)
else:
group_info = None
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=None,
message_id=event.message_id,
user_info=user_info,
raw_message=raw_message,
raw_message=str(event.original_message),
group_info=group_info,
reply_message=None,
reply_message=event.reply,
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实例
chat_bot = ChatBot()

View File

@@ -73,6 +73,8 @@ class BotConfig:
mood_update_interval: float = 1.0 # 情绪更新间隔 单位秒
mood_decay_rate: float = 0.95 # 情绪衰减率
mood_intensity_factor: float = 0.7 # 情绪强度因子
willing_mode: str = "classical" # 意愿模式
keywords_reaction_rules = [] # 关键词回复规则
@@ -212,6 +214,10 @@ class BotConfig:
"model_r1_distill_probability", config.MODEL_R1_DISTILL_PROBABILITY
)
config.max_response_length = response_config.get("max_response_length", config.max_response_length)
def willing(parent: dict):
willing_config = parent["willing"]
config.willing_mode = willing_config.get("willing_mode", config.willing_mode)
def model(parent: dict):
# 加载模型配置
@@ -353,6 +359,7 @@ class BotConfig:
"cq_code": {"func": cq_code, "support": ">=0.0.0"},
"bot": {"func": bot, "support": ">=0.0.0"},
"response": {"func": response, "support": ">=0.0.0"},
"willing": {"func": willing, "support": ">=0.0.9", "necessary": False},
"model": {"func": model, "support": ">=0.0.0"},
"message": {"func": message, "support": ">=0.0.0"},
"memory": {"func": memory, "support": ">=0.0.0", "necessary": False},

View File

@@ -1,7 +1,6 @@
import random
import time
from typing import Optional
from loguru import logger
from ...common.database import db
from ..memory_system.memory import hippocampus, memory_graph
@@ -11,6 +10,13 @@ from .config import global_config
from .utils import get_embedding, get_recent_group_detailed_plain_text
from .chat_stream import chat_manager
from ..utils.logger_config import LogClassification, LogModule
log_module = LogModule()
logger = log_module.setup_logger(LogClassification.PBUILDER)
logger.info("初始化Prompt系统")
class PromptBuilder:
def __init__(self):
@@ -163,7 +169,7 @@ class PromptBuilder:
prompt_ger += "你喜欢用文言文"
# 额外信息要求
extra_info = """但是记得回复平淡一些,简短一些,尤其注意在没明确提到时不要过多提及自身的背景, 不要直接回复别人发的表情包,记住不要输出多余内容(包括前后缀,冒号和引号,括号,表情等),只需要输出回复内容就好,不要输出其他任何内容"""
extra_info = """但是记得回复平淡一些,简短一些,尤其注意在没明确提到时不要过多提及自身的背景, 不要直接回复别人发的表情包,记住不要输出多余内容(包括前后缀,冒号和引号,括号,表情,@,等),只需要输出回复内容就好,不要输出其他任何内容"""
# 合并prompt
prompt = ""
@@ -239,7 +245,7 @@ class PromptBuilder:
return prompt_for_check, memory
def _build_initiative_prompt(self, selected_node, prompt_regular, memory):
prompt_for_initiative = f"{prompt_regular}你现在想在群里发言,回忆了一下,想到一个话题,是{selected_node['concept']},关于这个话题的记忆有\n{memory}\n,请在把握群里的聊天内容的基础上,综合群内的氛围,以日常且口语化的口吻,简短且随意一点进行发言,不要说的太有条理,可以有个性。记住不要输出多余内容(包括前后缀,冒号和引号,括号,表情等)"
prompt_for_initiative = f"{prompt_regular}你现在想在群里发言,回忆了一下,想到一个话题,是{selected_node['concept']},关于这个话题的记忆有\n{memory}\n,请在把握群里的聊天内容的基础上,综合群内的氛围,以日常且口语化的口吻,简短且随意一点进行发言,不要说的太有条理,可以有个性。记住不要输出多余内容(包括前后缀,冒号和引号,括号,表情,@等)"
return prompt_for_initiative
async def get_prompt_info(self, message: str, threshold: float):

View File

@@ -1,14 +0,0 @@
#Broca's Area
# 功能:语言产生、语法处理和言语运动控制。
# 损伤后果:布洛卡失语症(表达困难,但理解保留)。
import time
class Thinking_Idea:
def __init__(self, message_id: str):
self.messages = [] # 消息列表集合
self.current_thoughts = [] # 当前思考内容列表
self.time = time.time() # 创建时间
self.id = str(int(time.time() * 1000)) # 使用时间戳生成唯一标识ID

View File

@@ -1,4 +1,5 @@
import asyncio
from .remote import main
asyncio.run(main())
# 启动心跳线程
heartbeat_thread = main()

View File

@@ -4,13 +4,12 @@ import uuid
import platform
import os
import json
import threading
from loguru import logger
import asyncio
# UUID文件路径
UUID_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "client_uuid.json")
# 生成或获取客户端唯一ID
def get_unique_id():
# 检查是否已经有保存的UUID
@@ -37,7 +36,6 @@ def get_unique_id():
return client_id
# 生成客户端唯一ID
def generate_unique_id():
# 结合主机名、系统信息和随机UUID生成唯一ID
@@ -45,7 +43,6 @@ def generate_unique_id():
unique_id = f"{system_info}-{uuid.uuid4()}"
return unique_id
def send_heartbeat(server_url, client_id):
"""向服务器发送心跳"""
sys = platform.system()
@@ -66,31 +63,40 @@ def send_heartbeat(server_url, client_id):
logger.debug(f"发送心跳时出错: {e}")
return False
async def main():
# 配置
SERVER_URL = "http://hyybuth.xyz:10058" # 更改为你的服务器地址
HEARTBEAT_INTERVAL = 300 # 5分钟
# 获取或生成客户端ID
client_id = get_unique_id()
logger.debug(f"客户端已启动ID: {client_id}")
# 主心跳循环
try:
while True:
if send_heartbeat(SERVER_URL, client_id):
print(f"{HEARTBEAT_INTERVAL}秒后发送下一次心跳...")
class HeartbeatThread(threading.Thread):
"""心跳线程类"""
def __init__(self, server_url, interval):
super().__init__(daemon=True) # 设置为守护线程,主程序结束时自动结束
self.server_url = server_url
self.interval = interval
self.client_id = get_unique_id()
self.running = True
def run(self):
"""线程运行函数"""
logger.debug(f"心跳线程已启动客户端ID: {self.client_id}")
while self.running:
if send_heartbeat(self.server_url, self.client_id):
logger.info(f"{self.interval}秒后发送下一次心跳...")
else:
print(f"{HEARTBEAT_INTERVAL}秒后重试...")
logger.info(f"{self.interval}秒后重试...")
time.sleep(self.interval) # 使用同步的睡眠
def stop(self):
"""停止线程"""
self.running = False
await asyncio.sleep(HEARTBEAT_INTERVAL)
except KeyboardInterrupt:
print("用户已停止客户端")
except Exception as e:
print(f"发生意外错误: {e}")
if __name__ == "__main__":
asyncio.run(main())
def main():
"""主函数,启动心跳线程"""
# 配置
SERVER_URL = "http://hyybuth.xyz:10058"
HEARTBEAT_INTERVAL = 300 # 5分钟
# 创建并启动心跳线程
heartbeat_thread = HeartbeatThread(SERVER_URL, HEARTBEAT_INTERVAL)
heartbeat_thread.start()
return heartbeat_thread # 返回线程对象,便于外部控制

View File

@@ -7,6 +7,7 @@ class LogClassification(Enum):
MEMORY = "memory"
EMOJI = "emoji"
CHAT = "chat"
PBUILDER = "promptbuilder"
class LogModule:
logger = loguru.logger.opt()
@@ -32,6 +33,10 @@ class LogModule:
# 表情包系统日志格式
emoji_format = "<green>{time:HH:mm}</green> | <level>{level: <8}</level> | <yellow>表情包</yellow> | <cyan>{function}</cyan>:<cyan>{line}</cyan> - <level>{message}</level>"
promptbuilder_format = "<green>{time:HH:mm}</green> | <level>{level: <8}</level> | <yellow>Prompt</yellow> | <cyan>{function}</cyan>:<cyan>{line}</cyan> - <level>{message}</level>"
# 根据日志类型选择日志格式和输出
if log_type == LogClassification.CHAT:
self.logger.add(
@@ -39,6 +44,12 @@ class LogModule:
format=chat_format,
# level="INFO"
)
elif log_type == LogClassification.PBUILDER:
self.logger.add(
sys.stderr,
format=promptbuilder_format,
# level="INFO"
)
elif log_type == LogClassification.MEMORY:
# 同时输出到控制台和文件

View File

@@ -0,0 +1,98 @@
import asyncio
from typing import Dict
from ..chat.chat_stream import ChatStream
class WillingManager:
def __init__(self):
self.chat_reply_willing: Dict[str, float] = {} # 存储每个聊天流的回复意愿
self._decay_task = None
self._started = False
async def _decay_reply_willing(self):
"""定期衰减回复意愿"""
while True:
await asyncio.sleep(1)
for chat_id in self.chat_reply_willing:
self.chat_reply_willing[chat_id] = max(0, self.chat_reply_willing[chat_id] * 0.9)
def get_willing(self, chat_stream: ChatStream) -> float:
"""获取指定聊天流的回复意愿"""
if chat_stream:
return self.chat_reply_willing.get(chat_stream.stream_id, 0)
return 0
def set_willing(self, chat_id: str, willing: float):
"""设置指定聊天流的回复意愿"""
self.chat_reply_willing[chat_id] = willing
async def change_reply_willing_received(self,
chat_stream: ChatStream,
is_mentioned_bot: bool = False,
config = None,
is_emoji: bool = False,
interested_rate: float = 0,
sender_id: str = None) -> float:
"""改变指定聊天流的回复意愿并返回回复概率"""
chat_id = chat_stream.stream_id
current_willing = self.chat_reply_willing.get(chat_id, 0)
interested_rate = interested_rate * config.response_interested_rate_amplifier
if interested_rate > 0.5:
current_willing += (interested_rate - 0.5)
if is_mentioned_bot and current_willing < 1.0:
current_willing += 1
elif is_mentioned_bot:
current_willing += 0.05
if is_emoji:
current_willing *= 0.2
self.chat_reply_willing[chat_id] = min(current_willing, 3.0)
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.group_id not in config.talk_allowed_groups:
current_willing = 0
reply_probability = 0
if chat_stream.group_info.group_id in config.talk_frequency_down_groups:
reply_probability = reply_probability / 3.5
return reply_probability
def change_reply_willing_sent(self, chat_stream: ChatStream):
"""发送消息后降低聊天流的回复意愿"""
if chat_stream:
chat_id = chat_stream.stream_id
current_willing = self.chat_reply_willing.get(chat_id, 0)
self.chat_reply_willing[chat_id] = max(0, current_willing - 1.8)
def change_reply_willing_not_sent(self, chat_stream: ChatStream):
"""未发送消息后降低聊天流的回复意愿"""
if chat_stream:
chat_id = chat_stream.stream_id
current_willing = self.chat_reply_willing.get(chat_id, 0)
self.chat_reply_willing[chat_id] = max(0, current_willing - 0)
def change_reply_willing_after_sent(self, chat_stream: ChatStream):
"""发送消息后提高聊天流的回复意愿"""
if chat_stream:
chat_id = chat_stream.stream_id
current_willing = self.chat_reply_willing.get(chat_id, 0)
if current_willing < 1:
self.chat_reply_willing[chat_id] = min(1, current_willing + 0.4)
async def ensure_started(self):
"""确保衰减任务已启动"""
if not self._started:
if self._decay_task is None:
self._decay_task = asyncio.create_task(self._decay_reply_willing())
self._started = True
# 创建全局实例
willing_manager = WillingManager()

View File

@@ -0,0 +1,102 @@
import asyncio
from typing import Dict
from ..chat.chat_stream import ChatStream
class WillingManager:
def __init__(self):
self.chat_reply_willing: Dict[str, float] = {} # 存储每个聊天流的回复意愿
self._decay_task = None
self._started = False
async def _decay_reply_willing(self):
"""定期衰减回复意愿"""
while True:
await asyncio.sleep(3)
for chat_id in self.chat_reply_willing:
# 每分钟衰减10%的回复意愿
self.chat_reply_willing[chat_id] = max(0, self.chat_reply_willing[chat_id] * 0.6)
def get_willing(self, chat_stream: ChatStream) -> float:
"""获取指定聊天流的回复意愿"""
if chat_stream:
return self.chat_reply_willing.get(chat_stream.stream_id, 0)
return 0
def set_willing(self, chat_id: str, willing: float):
"""设置指定聊天流的回复意愿"""
self.chat_reply_willing[chat_id] = willing
async def change_reply_willing_received(self,
chat_stream: ChatStream,
topic: str = None,
is_mentioned_bot: bool = False,
config = None,
is_emoji: bool = False,
interested_rate: float = 0,
sender_id: str = None) -> float:
"""改变指定聊天流的回复意愿并返回回复概率"""
chat_id = chat_stream.stream_id
current_willing = self.chat_reply_willing.get(chat_id, 0)
if topic and current_willing < 1:
current_willing += 0.2
elif topic:
current_willing += 0.05
if is_mentioned_bot and current_willing < 1.0:
current_willing += 0.9
elif is_mentioned_bot:
current_willing += 0.05
if is_emoji:
current_willing *= 0.2
self.chat_reply_willing[chat_id] = min(current_willing, 3.0)
reply_probability = (current_willing - 0.5) * 2
# 检查群组权限(如果是群聊)
if chat_stream.group_info and config:
if chat_stream.group_info.group_id not in config.talk_allowed_groups:
current_willing = 0
reply_probability = 0
if chat_stream.group_info.group_id in config.talk_frequency_down_groups:
reply_probability = reply_probability / 3.5
if is_mentioned_bot and sender_id == "1026294844":
reply_probability = 1
return reply_probability
def change_reply_willing_sent(self, chat_stream: ChatStream):
"""发送消息后降低聊天流的回复意愿"""
if chat_stream:
chat_id = chat_stream.stream_id
current_willing = self.chat_reply_willing.get(chat_id, 0)
self.chat_reply_willing[chat_id] = max(0, current_willing - 1.8)
def change_reply_willing_not_sent(self, chat_stream: ChatStream):
"""未发送消息后降低聊天流的回复意愿"""
if chat_stream:
chat_id = chat_stream.stream_id
current_willing = self.chat_reply_willing.get(chat_id, 0)
self.chat_reply_willing[chat_id] = max(0, current_willing - 0)
def change_reply_willing_after_sent(self, chat_stream: ChatStream):
"""发送消息后提高聊天流的回复意愿"""
if chat_stream:
chat_id = chat_stream.stream_id
current_willing = self.chat_reply_willing.get(chat_id, 0)
if current_willing < 1:
self.chat_reply_willing[chat_id] = min(1, current_willing + 0.4)
async def ensure_started(self):
"""确保衰减任务已启动"""
if not self._started:
if self._decay_task is None:
self._decay_task = asyncio.create_task(self._decay_reply_willing())
self._started = True
# 创建全局实例
willing_manager = WillingManager()

View File

@@ -5,9 +5,8 @@ from typing import Dict
from loguru import logger
from .config import global_config
from .chat_stream import ChatStream
from ..chat.config import global_config
from ..chat.chat_stream import ChatStream
class WillingManager:
def __init__(self):

View File

@@ -0,0 +1,32 @@
from typing import Optional
from loguru import logger
from ..chat.config import global_config
from .mode_classical import WillingManager as ClassicalWillingManager
from .mode_dynamic import WillingManager as DynamicWillingManager
from .mode_custom import WillingManager as CustomWillingManager
def init_willing_manager() -> Optional[object]:
"""
根据配置初始化并返回对应的WillingManager实例
Returns:
对应mode的WillingManager实例
"""
mode = global_config.willing_mode.lower()
if mode == "classical":
logger.info("使用经典回复意愿管理器")
return ClassicalWillingManager()
elif mode == "dynamic":
logger.info("使用动态回复意愿管理器")
return DynamicWillingManager()
elif mode == "custom":
logger.warning(f"自定义的回复意愿管理器模式: {mode}")
return CustomWillingManager()
else:
logger.warning(f"未知的回复意愿管理器模式: {mode}, 将使用经典模式")
return ClassicalWillingManager()
# 全局willing_manager对象
willing_manager = init_willing_manager()

View File

@@ -1,6 +1,7 @@
[inner]
version = "0.0.8"
version = "0.0.9"
#以下是给开发人员阅读的,一般用户不需要阅读
#如果你想要修改配置文件请在修改后将version的值进行变更
#如果新增项目请在BotConfig类下新增相应的变量
#1.如果你修改的是[]层级项目,例如你新增了 [memory],那么请在config.py的 load_config函数中的include_configs字典中新增"内容":{
@@ -19,14 +20,14 @@ alias_names = ["小麦", "阿麦"]
[personality]
prompt_personality = [
"曾经是一个学习地质的女大学生,现在学习心理学和脑科学,你会刷贴吧", # 贴吧人格
"是一个女大学生,你有黑色头发,你会刷小红书", # 小红书人格
"是一个女大学生你会刷b站对ACG文化感兴趣" # b站人格
"用一句话或几句话描述性格特点和其他特征",
"用一句话或几句话描述性格特点和其他特征",
"例如,是一个热爱国家热爱党的新时代好青年"
]
personality_1_probability = 0.6 # 第一种人格出现概率
personality_2_probability = 0.3 # 第二种人格出现概率
personality_3_probability = 0.1 # 第三种人格出现概率请确保三个概率相加等于1
prompt_schedule = "一个曾经学习地质,现在学习心理学和脑科学的女大学生喜欢刷qq贴吧知乎和小红书"
prompt_schedule = "用一句话或几句话描述描述性格特点和其他特征"
[message]
min_text_length = 2 # 与麦麦聊天时麦麦只会回答文本大于等于此数的消息
@@ -64,11 +65,16 @@ model_v3_probability = 0.1 # 麦麦回答时选择次要回复模型2 模型的
model_r1_distill_probability = 0.1 # 麦麦回答时选择次要回复模型3 模型的概率
max_response_length = 1024 # 麦麦回答的最大token数
[willing]
willing_mode = "classical"
# willing_mode = "dynamic"
# willing_mode = "custom"
[memory]
build_memory_interval = 600 # 记忆构建间隔 单位秒 间隔越低,麦麦学习越多,但是冗余信息也会增多
build_memory_interval = 2000 # 记忆构建间隔 单位秒 间隔越低,麦麦学习越多,但是冗余信息也会增多
memory_compress_rate = 0.1 # 记忆压缩率 控制记忆精简程度 建议保持默认,调高可以获得更多信息,但是冗余信息也会增多
forget_memory_interval = 600 # 记忆遗忘间隔 单位秒 间隔越低,麦麦遗忘越频繁,记忆更精简,但更难学习
forget_memory_interval = 1000 # 记忆遗忘间隔 单位秒 间隔越低,麦麦遗忘越频繁,记忆更精简,但更难学习
memory_forget_time = 24 #多长时间后的记忆会被遗忘 单位小时
memory_forget_percentage = 0.01 # 记忆遗忘比例 控制记忆遗忘程度 越大遗忘越多 建议保持默认
@@ -116,6 +122,9 @@ talk_allowed = [
talk_frequency_down = [] #降低回复频率的群
ban_user_id = [] #禁止回复消息的QQ号
[remote] #测试功能,发送统计信息,主要是看全球有多少只麦麦
enable = false #默认关闭
#V3
#name = "deepseek-chat"
@@ -178,8 +187,6 @@ pri_out = 0
name = "Pro/Qwen/Qwen2-VL-7B-Instruct"
provider = "SILICONFLOW"
#嵌入模型
[model.embedding] #嵌入

1157
webui.py Normal file

File diff suppressed because it is too large Load Diff