Skip to content

Commit 01fc208

Browse files
author
sineom
committed
优化指定用户的总结
1 parent f6fd9d3 commit 01fc208

File tree

2 files changed

+25
-60
lines changed

2 files changed

+25
-60
lines changed

db.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -103,7 +103,7 @@ def get_summary_time(self, session_id):
103103
return None
104104
return row[0]
105105

106-
def get_records(self, session_id, start_timestamp:int = None, limit:int = None, username: list=None) -> list:
106+
def get_records(self, session_id, start_timestamp:int = None, limit:int = None, username: list[str]=None) -> list:
107107
c = self.conn.cursor()
108108

109109
# 构建基础SQL查询

main.py

Lines changed: 24 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -140,11 +140,10 @@ def find_json(json_string):
140140
json_string = ""
141141
return json_string
142142

143-
144143
@plugins.register(name="summary",
145144
desire_priority=0,
146145
desc="A simple plugin to summary messages",
147-
version="0.0.7",
146+
version="0.0.8",
148147
author="sineom")
149148
class Summary(Plugin):
150149
# 类级别常量
@@ -154,8 +153,8 @@ class Summary(Plugin):
154153

155154
def __init__(self):
156155
super().__init__()
157-
self._init_config()
158156
self._init_components()
157+
self._init_config()
159158
self._init_handlers()
160159

161160
def _init_config(self):
@@ -195,7 +194,7 @@ def _get_username(self, context, msg: ChatMessage) -> str:
195194
return msg.actual_user_nickname or msg.actual_user_id
196195
return msg.from_user_nickname or msg.from_user_id
197196

198-
async def _handle_command(self, e_context: EventContext) -> Optional[Reply]:
197+
def _handle_command(self, e_context: EventContext) -> Optional[Reply]:
199198
"""处理命令"""
200199
content = e_context['context'].content
201200
msg = e_context['context']['msg']
@@ -206,10 +205,10 @@ async def _handle_command(self, e_context: EventContext) -> Optional[Reply]:
206205
return command
207206

208207
# 总结命令处理
209-
if "总结" not in content:
208+
if self.TRIGGER_PREFIX + "总结" not in content:
210209
return None
211210

212-
return await self._handle_summary_command(content, session_id)
211+
return self._handle_summary_command(content, session_id, e_context)
213212

214213
def _handle_admin_command(self, content: str, session_id: str, e_context: EventContext) -> Optional[Reply]:
215214
"""处理管理员命令"""
@@ -226,14 +225,8 @@ def _handle_admin_command(self, content: str, session_id: str, e_context: EventC
226225

227226
return None
228227

229-
def _handle_summary_command(self, content: str, session_id: str) -> Reply:
230-
"""处理总结命令
231-
Args:
232-
content: 命令内容
233-
session_id: 会话ID
234-
Returns:
235-
Reply: 回复内容
236-
"""
228+
def _handle_summary_command(self, content: str, session_id: str, e_context: EventContext) -> Reply:
229+
"""处理总结命令"""
237230
# 检查锁
238231
if not self._acquire_summary_lock(session_id):
239232
return self._get_in_progress_reply(session_id, content)
@@ -243,30 +236,15 @@ def _handle_summary_command(self, content: str, session_id: str) -> Reply:
243236
if error_reply := self._check_summary_limits(session_id):
244237
return error_reply
245238

239+
# 添加回复
240+
e_context['reply'] = Reply(ReplyType.TEXT, "正在加速生成总结,请稍等")
241+
e_context.action = EventAction.BREAK_PASS
246242
# 解析命令参数
247243
limit, duration, username = self._parse_summary_args(content)
248244

249-
250-
# 若存在用户名,则使用用户名查询+条件筛选
251-
if username:
252-
return self._generate_summary(session_id, 0, 0, username)
253-
254-
# 如果解析失败,检查是否是用户名查询
255-
if limit is None and duration is None:
256-
# 移除命令前缀,获取可能的用户名
257-
possible_username = content.split(self.TRIGGER_PREFIX + "总结", 1)[1].strip()
258-
if possible_username: # 只有当有实际内容时才按用户名查询
259-
logger.debug(f"[Summary] Treating '{possible_username}' as username query")
260-
return self._generate_summary(session_id, 0, 0, possible_username)
261-
else:
262-
# 如果没有任何参数,使用默认值
263-
return Reply(ReplyType.TEXT, "请@具体用户名")
264-
265-
266-
267245
# 生成总结
268246
start_time = int(time.time()) - duration if duration > 0 else 0
269-
return self._generate_summary(session_id, start_time, limit or self.DEFAULT_LIMIT)
247+
return self._generate_summary(session_id,start_time= start_time,limit= limit ,username=username)
270248

271249
except Exception as e:
272250
logger.error(f"[Summary] Error handling summary command: {e}")
@@ -294,12 +272,11 @@ def _parse_summary_args(self, content: str) -> Tuple[int, int, str]:
294272
content: 用户输入的命令内容,例如"@妮可 @欧尼 3小时内的前99条消息"
295273
296274
Returns:
297-
Tuple[int, int, str]: 返回(消息数量限制, 时间范围(秒), 用户名列表)的元组
275+
Tuple[int, int, str]: 返回(消息数量限制, 时间范围(秒), 用户名列表)的���组
298276
如果解析失败返回(None, None, None)
299277
"""
300278
try:
301279
# 先提取所有@用户名
302-
username = None
303280
usernames = []
304281
parts = content.split()
305282
cleaned_content = []
@@ -310,11 +287,8 @@ def _parse_summary_args(self, content: str) -> Tuple[int, int, str]:
310287
else:
311288
cleaned_content.append(part)
312289

313-
if usernames:
314-
username = ' '.join([f'@{name}' for name in usernames])
315-
# 重组不含用户名的内容
316-
content = ''.join(cleaned_content)
317-
290+
content = ''.join(cleaned_content)
291+
print(f"[Summary] username: {len(usernames)}")
318292
# 将中文内容转换为标准命令格式
319293
command_json = find_json(self._translate_text_to_commands(content))
320294
command = json.loads(command_json)
@@ -332,8 +306,8 @@ def _parse_summary_args(self, content: str) -> Tuple[int, int, str]:
332306
duration = int(float(duration))
333307
duration = max(int(duration), 0) or self.DEFAULT_DURATION
334308

335-
logger.debug(f"[Summary] Parsed args: limit={limit}, duration={duration}, users={username}")
336-
return limit, duration, username
309+
logger.debug(f"[Summary] Parsed args: limit={limit}, duration={duration}, users={usernames}")
310+
return limit, duration, usernames
337311

338312
except Exception as e:
339313
logger.error(f"[Summary] Failed to parse command: {e}")
@@ -394,7 +368,7 @@ def on_receive_message(self, e_context: EventContext):
394368
username = cmsg.actual_user_nickname
395369
if username is None:
396370
username = cmsg.actual_user_id
397-
else:
371+
else:
398372
username = cmsg.from_user_nickname
399373
if username is None:
400374
username = cmsg.from_user_id
@@ -434,18 +408,10 @@ def _release_summary_lock(self, session_id: str):
434408
with self._locks_lock:
435409
self._summary_locks.pop(session_id, None)
436410

437-
def _generate_summary(self, session_id: str, limit: int = None, start_time: int = None, username: list = None) -> Reply:
438-
"""生成聊天记录总结
439-
Args:
440-
session_id: 会话ID
441-
start_time: 开始时间,仅在 username 为 None 时使用
442-
limit: 记录数量限制,仅在 username 为 None 时使用
443-
username: 可选的用户名过滤,如果提供则忽略 start_time 和 limit
444-
Returns:
445-
Reply: 总结回复
446-
"""
411+
def _generate_summary(self, session_id: str, start_time: int = None, limit: int = None, username: list = None) -> Reply:
412+
"""生成聊天记录总结"""
447413
try:
448-
records = self.db.get_records(session_id, start_time, limit, username)
414+
records = self.db.get_records(session_id, start_timestamp=start_time, limit=limit, username=username)
449415

450416
# 检查记录数量
451417
if not records:
@@ -456,8 +422,7 @@ def _generate_summary(self, session_id: str, limit: int = None, start_time: int
456422
# 构建聊天记录文本
457423
chat_logs = []
458424
for record in records:
459-
timestamp = time.strftime("%H:%M:%S", time.localtime(record[7])) if record[7] else ""
460-
chat_logs.append(f"{record[2]}({timestamp}): {record[3]}")
425+
chat_logs.append(f"{record[2]}({record[7]}): {record[3]}")
461426
chat_text = "\n".join(chat_logs)
462427

463428
logger.debug("[Summary] Processing %d chat records for summary", len(records))
@@ -495,7 +460,7 @@ def _generate_summary(self, session_id: str, limit: int = None, start_time: int
495460
logger.error("[Summary] Error generating summary: %s", str(e))
496461
return Reply(ReplyType.TEXT, "生成总结时发生错误,请稍后重试")
497462

498-
async def on_handle_context(self, e_context: EventContext):
463+
def on_handle_context(self, e_context: EventContext):
499464
"""处理上下文事件"""
500465
if e_context['context'].type != ContextType.TEXT:
501466
return
@@ -509,7 +474,7 @@ async def on_handle_context(self, e_context: EventContext):
509474
return
510475

511476
# 处理命令
512-
reply = await self._handle_command(e_context)
477+
reply = self._handle_command(e_context)
513478
if reply:
514479
e_context['reply'] = reply
515480
e_context.action = EventAction.BREAK_PASS
@@ -546,7 +511,7 @@ def convert_text_to_image(self, text):
546511
converter.close()
547512
return image_path
548513

549-
async def _get_in_progress_reply(self, session_id: str, content: str) -> Reply:
514+
def _get_in_progress_reply(self, session_id: str, content: str) -> Reply:
550515
"""获取正在处理中的回复"""
551516
try:
552517
session = self.bot.sessions.build_session(session_id, SUMMARY_IN_PROGRESS_PROMPT)

0 commit comments

Comments
 (0)