修复了@的bug和日程生成bug,增加了简化输出的配置选项
This commit is contained in:
SengokuCola
2025-03-01 00:32:26 +08:00
parent c3e555fd70
commit 1c977ce2ca
9 changed files with 39 additions and 68 deletions

Binary file not shown.

View File

@@ -68,6 +68,7 @@ async def _(bot: Bot):
async def init_relationships():
"""在 NoneBot2 启动时初始化关系管理器"""
print("\033[1;32m[初始化]\033[0m 正在加载用户关系数据...")
await relationship_manager.load_all_relationships()
asyncio.create_task(relationship_manager._start_relationship_manager())
@group_msg.handle()

View File

@@ -29,6 +29,9 @@ model_r1_probability = 0.8
model_v3_probability = 0.1
model_r1_distill_probability = 0.1
[others]
enable_advance_output = false
[groups]

View File

@@ -6,15 +6,7 @@ import logging
import configparser
import tomli
# 禁用默认的日志输出
# logger.remove()
# # 只禁用 INFO 级别的日志输出到控制台
# logging.getLogger('nonebot').handlers.clear()
# console_handler = logging.StreamHandler()
# console_handler.setLevel(logging.WARNING) # 只输出 WARNING 及以上级别
# logging.getLogger('nonebot').addHandler(console_handler)
# logging.getLogger('nonebot').setLevel(logging.WARNING)
@dataclass
class BotConfig:
@@ -50,6 +42,8 @@ class BotConfig:
MODEL_V3_PROBABILITY: float = 0.1 # V3模型概率
MODEL_R1_DISTILL_PROBABILITY: float = 0.1 # R1蒸馏模型概率
enable_advance_output: bool = False # 是否启用高级输出
@classmethod
def load_config(cls, config_path: str = "bot_config.toml") -> "BotConfig":
"""从TOML配置文件加载配置"""
@@ -105,6 +99,10 @@ class BotConfig:
config.talk_frequency_down_groups = set(groups_config.get("talk_frequency_down", []))
config.ban_user_id = set(groups_config.get("ban_user_id", []))
if "others" in toml_dict:
others_config = toml_dict["others"]
config.enable_advance_output = others_config.get("enable_advance_output", config.enable_advance_output)
print(f"\033[1;32m成功加载配置文件: {config_path}\033[0m")
return config
@@ -130,3 +128,13 @@ llm_config.SILICONFLOW_API_KEY = os.getenv('SILICONFLOW_KEY')
llm_config.SILICONFLOW_BASE_URL = os.getenv('SILICONFLOW_BASE_URL')
llm_config.DEEP_SEEK_API_KEY = os.getenv('DEEP_SEEK_KEY')
llm_config.DEEP_SEEK_BASE_URL = os.getenv('DEEP_SEEK_BASE_URL')
if not global_config.enable_advance_output:
logger.remove()
logging.getLogger('nonebot').handlers.clear()
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.WARNING) # 只输出 WARNING 及以上级别
logging.getLogger('nonebot').addHandler(console_handler)
logging.getLogger('nonebot').setLevel(logging.WARNING)

View File

@@ -39,40 +39,6 @@ class CQCode:
translated_plain_text: Optional[str] = None
reply_message: Dict = None # 存储回复消息
image_base64: Optional[str] = None
@classmethod
def from_cq_code(cls, cq_code: str, reply: Dict = None) -> 'CQCode':
"""
从CQ码字符串创建CQCode对象
例如:[CQ:image,file=1.jpg,url=http://example.com/1.jpg]
"""
if not cq_code.startswith('[CQ:'):
return cls('text', {'text': cq_code}, cq_code, group_id=0, user_id=0)
# 移除前后的[]
content = cq_code[1:-1]
# 分离类型和参数部分
parts = content.split(',')
if not parts:
return cls('text', {'text': cq_code}, cq_code, group_id=0, user_id=0)
# 获取CQ类型
cq_type = parts[0][3:] # 去掉'CQ:'
# 解析参数
params = {}
for part in parts[1:]:
if '=' in part:
key, value = part.split('=', 1)
# 处理转义字符
value = cls.unescape(value)
params[key] = value
# 创建实例
instance = cls(cq_type, params, cq_code, group_id=0, user_id=0, reply_message=reply)
# 根据类型进行相应的翻译处理
instance.translate()
return instance
def translate(self):
"""根据CQ码类型进行相应的翻译处理"""
@@ -88,7 +54,7 @@ class CQCode:
if user_nickname:
self.translated_plain_text = f"[@{user_nickname}]"
else:
self.translated_plain_text = f"[@某人]"
self.translated_plain_text = f"@某人"
elif self.type == 'reply':
self.translated_plain_text = self.translate_reply()
elif self.type == 'face':

View File

@@ -97,7 +97,6 @@ class Message:
trans_list = []
start = 0
print(f"\033[1;34m[调试信息]\033[0m 原始消息: {message}")
while True:
# 查找下一个CQ码的开始位置
cq_start = message.find('[CQ:', start)
@@ -129,7 +128,7 @@ class Message:
# 更新start位置到当前CQ码之后
start = cq_end + 1
print(f"\033[1;34m[调试信息]\033[0m 提取的消息对象:列表: {cq_code_dict_list}")
# print(f"\033[1;34m[调试信息]\033[0m 提取的消息对象:列表: {cq_code_dict_list}")
#判定是否是表情包消息,以及是否含有表情包
if len(cq_code_dict_list) == 1 and cq_code_dict_list[0]['type'] == 'image':

View File

@@ -45,9 +45,7 @@ class Relationship:
class RelationshipManager:
def __init__(self):
self.relationships: dict[int, Relationship] = {} # user_id -> Relationship
# self.id_name_nickname_table: dict[str, list] = {} # name -> [nickname, nickname, ...]
# print("[关系管理] 初始化 id_name_nickname_table") # 调试信息
self.relationships: dict[int, Relationship] = {}
async def update_relationship(self, user_id: int, data=None, **kwargs):
# 检查是否在内存中已存在
@@ -102,8 +100,16 @@ class RelationshipManager:
"""从数据库加载或创建新的关系对象"""
rela = Relationship(user_id=data['user_id'], data=data)
rela.saved = True
self.relationships[rela.user_id] = rela
return rela
async def load_all_relationships(self):
"""加载所有关系对象"""
db = Database.get_instance()
all_relationships = db.db.relationships.find({})
for data in all_relationships:
await self.load_relationship(data)
async def _start_relationship_manager(self):
"""每5分钟自动保存一次关系数据"""
db = Database.get_instance()
@@ -154,27 +160,13 @@ class RelationshipManager:
)
def get_name(self, user_id: int) -> str:
# 确保user_id是整数类型
user_id = int(user_id)
if user_id in self.relationships:
return self.relationships[user_id].nickname
else:
return "[某人]"
def print_all_relationships(self):
"""打印内存中所有的关系记录"""
print("\n\033[1;32m[关系管理]\033[0m 当前内存中的所有关系:")
print("=" * 50)
if not self.relationships:
print("暂无关系记录")
return
for user_id, relationship in self.relationships.items():
print(f"用户ID: {user_id}")
print(f"昵称: {relationship.nickname}")
print(f"好感度: {relationship.relationship_value}")
print("-" * 30)
print("=" * 50)
return "某人"
relationship_manager = RelationshipManager()

View File

@@ -2,6 +2,7 @@ from .relationship_manager import relationship_manager
from .config import global_config
def get_user_nickname(user_id: int) -> str:
if user_id == int(global_config.BOT_QQ):
return global_config.BOT_NICKNAME
if int(user_id) == int(global_config.BOT_QQ):
return global_config.BOT_NICKNAME
# print(user_id)
return relationship_manager.get_name(user_id)

View File

@@ -4,6 +4,7 @@ from typing import List, Dict
from .schedule_llm_module import LLMModel
from dotenv import load_dotenv
from ...common.database import Database # 使用正确的导入语法
from ..chat.config import global_config
# import sys