fix:修复表达方式空构建问题

This commit is contained in:
SengokuCola
2025-05-28 23:23:01 +08:00
parent 0087601fb3
commit 2951feadb5
4 changed files with 82 additions and 56 deletions

View File

@@ -204,7 +204,8 @@ class ExpressionLearner:
random_msg: Optional[List[Dict[str, Any]]] = get_raw_msg_by_timestamp_random( random_msg: Optional[List[Dict[str, Any]]] = get_raw_msg_by_timestamp_random(
current_time - 3600 * 24, current_time, limit=num current_time - 3600 * 24, current_time, limit=num
) )
if not random_msg: # print(random_msg)
if not random_msg or random_msg == []:
return None return None
# 转化成str # 转化成str
chat_id: str = random_msg[0]["chat_id"] chat_id: str = random_msg[0]["chat_id"]
@@ -216,7 +217,7 @@ class ExpressionLearner:
chat_str=random_msg_str, chat_str=random_msg_str,
) )
# logger.info(f"学习{type_str}的prompt: {prompt}") logger.info(f"学习{type_str}的prompt: {prompt}")
try: try:
response, _ = await self.express_learn_model.generate_response_async(prompt) response, _ = await self.express_learn_model.generate_response_async(prompt)

View File

@@ -441,6 +441,7 @@ async def build_anonymous_messages(messages: List[Dict[str, Any]]) -> str:
处理 回复<aaa:bbb> 和 @<aaa:bbb> 字段将bbb映射为匿名占位符。 处理 回复<aaa:bbb> 和 @<aaa:bbb> 字段将bbb映射为匿名占位符。
""" """
if not messages: if not messages:
print("111111111111没有消息无法构建匿名消息")
return "" return ""
person_map = {} person_map = {}
@@ -450,7 +451,12 @@ async def build_anonymous_messages(messages: List[Dict[str, Any]]) -> str:
def get_anon_name(platform, user_id): def get_anon_name(platform, user_id):
if user_id == global_config.bot.qq_account: if user_id == global_config.bot.qq_account:
return "SELF" return "SELF"
try:
person_id = person_info_manager.get_person_id(platform, user_id) person_id = person_info_manager.get_person_id(platform, user_id)
except Exception as e:
person_id = None
if not person_id:
return "?"
if person_id not in person_map: if person_id not in person_map:
nonlocal current_char nonlocal current_char
person_map[person_id] = chr(current_char) person_map[person_id] = chr(current_char)
@@ -458,10 +464,15 @@ async def build_anonymous_messages(messages: List[Dict[str, Any]]) -> str:
return person_map[person_id] return person_map[person_id]
for msg in messages: for msg in messages:
user_info = msg.get("user_info", {}) try:
platform = user_info.get("platform") # user_info = msg.get("user_info", {})
user_id = user_info.get("user_id") platform = msg.get("chat_info_platform")
user_id = msg.get("chat_info_user_id")
timestamp = msg.get("time") timestamp = msg.get("time")
# print(f"msg:{msg}")
# print(f"platform:{platform}")
# print(f"user_id:{user_id}")
# print(f"timestamp:{timestamp}")
if msg.get("display_message"): if msg.get("display_message"):
content = msg.get("display_message") content = msg.get("display_message")
else: else:
@@ -472,32 +483,42 @@ async def build_anonymous_messages(messages: List[Dict[str, Any]]) -> str:
if "" in content: if "" in content:
content = content.replace("", "") content = content.replace("", "")
if not all([platform, user_id, timestamp is not None]): # if not all([platform, user_id, timestamp is not None]):
continue # continue
anon_name = get_anon_name(platform, user_id) anon_name = get_anon_name(platform, user_id)
# print(f"anon_name:{anon_name}")
# 处理 回复<aaa:bbb> # 处理 回复<aaa:bbb>
reply_pattern = r"回复<([^:<>]+):([^:<>]+)>" reply_pattern = r"回复<([^:<>]+):([^:<>]+)>"
match = re.search(reply_pattern, content)
def reply_replacer(match, platform=platform): if match:
# aaa = match.group(1) # print(f"发现回复match:{match}")
bbb = match.group(2) bbb = match.group(2)
anon_reply = get_anon_name(platform, bbb) # noqa try:
return f"回复 {anon_reply}" anon_reply = get_anon_name(platform, bbb)
except Exception:
anon_reply = "?"
content = re.sub(reply_pattern, f"回复 {anon_reply}", content, count=1)
content = re.sub(reply_pattern, reply_replacer, content, count=1) # 处理 @<aaa:bbb>无嵌套def
# 处理 @<aaa:bbb>
at_pattern = r"@<([^:<>]+):([^:<>]+)>" at_pattern = r"@<([^:<>]+):([^:<>]+)>"
at_matches = list(re.finditer(at_pattern, content))
def at_replacer(match, platform=platform): if at_matches:
# aaa = match.group(1) # print(f"发现@match:{at_matches}")
bbb = match.group(2) new_content = ""
anon_at = get_anon_name(platform, bbb) # noqa last_end = 0
return f"@{anon_at}" for m in at_matches:
new_content += content[last_end:m.start()]
content = re.sub(at_pattern, at_replacer, content) bbb = m.group(2)
try:
anon_at = get_anon_name(platform, bbb)
except Exception:
anon_at = "?"
new_content += f"@{anon_at}"
last_end = m.end()
new_content += content[last_end:]
content = new_content
header = f"{anon_name}" header = f"{anon_name}"
output_lines.append(header) output_lines.append(header)
@@ -506,7 +527,10 @@ async def build_anonymous_messages(messages: List[Dict[str, Any]]) -> str:
if stripped_line.endswith(""): if stripped_line.endswith(""):
stripped_line = stripped_line[:-1] stripped_line = stripped_line[:-1]
output_lines.append(f"{stripped_line}") output_lines.append(f"{stripped_line}")
# print(f"output_lines:{output_lines}")
output_lines.append("\n") output_lines.append("\n")
except Exception:
continue
formatted_string = "".join(output_lines).strip() formatted_string = "".join(output_lines).strip()
return formatted_string return formatted_string

View File

@@ -162,6 +162,7 @@ class MainSystem:
"""学习并存储表达方式任务""" """学习并存储表达方式任务"""
while True: while True:
await asyncio.sleep(global_config.expression.learning_interval) await asyncio.sleep(global_config.expression.learning_interval)
if global_config.expression.enable_expression_learning:
logger.info("[表达方式学习] 开始学习表达方式...") logger.info("[表达方式学习] 开始学习表达方式...")
await expression_learner.learn_and_store_expression() await expression_learner.learn_and_store_expression()
logger.info("[表达方式学习] 表达方式学习完成") logger.info("[表达方式学习] 表达方式学习完成")

View File

@@ -12,8 +12,8 @@ class MuteAction(PluginAction):
action_name = "mute_action" action_name = "mute_action"
action_description = "如果某人违反了公序良俗,或者别人戳你太多,或者某人刷屏,一定要禁言某人,如果你很生气,可以禁言某人,可以自选禁言时长,视严重程度而定。" action_description = "如果某人违反了公序良俗,或者别人戳你太多,或者某人刷屏,一定要禁言某人,如果你很生气,可以禁言某人,可以自选禁言时长,视严重程度而定。"
action_parameters = { action_parameters = {
"target": "禁言对象,输入你要禁言的对象的名字,必填", "target": "禁言对象,必填,输入你要禁言的对象的名字",
"duration": "禁言时长,输入你要禁言的时长(秒),单位为秒,必填,必须为数字", "duration": "禁言时长,必填,输入你要禁言的时长(秒),单位为秒,必须为数字",
"reason": "禁言理由,可选", "reason": "禁言理由,可选",
} }
action_require = [ action_require = [
@@ -24,8 +24,8 @@ class MuteAction(PluginAction):
"当你想回避某个话题时使用", "当你想回避某个话题时使用",
] ]
default = True # 默认动作,是否手动添加到使用集 default = True # 默认动作,是否手动添加到使用集
# associated_types = ["command", "text"] associated_types = ["command", "text"]
associated_types = ["text"] # associated_types = ["text"]
async def process(self) -> Tuple[bool, str]: async def process(self) -> Tuple[bool, str]:
"""处理群聊禁言动作""" """处理群聊禁言动作"""