Commit f0392bd

benny-dou <60535774+benny-dou@users.noreply.github.com>
2025-03-14 13:09:59
feat(summary): custom summary prefix message
1 parent 572652d
Changed files (1)
src
src/llm/summary.py
@@ -53,12 +53,13 @@ HELP = f"""🤖**GPT总结历史消息** (最多{MAX_MESSAGE_SUMMARY}条)
 """
 
 
-async def ai_summary(client: Client, message: Message, **kwargs):
+async def ai_summary(client: Client, message: Message, summary_prefix: str | None = None, **kwargs):
     """GPT summary of the message history.
 
     Args:
         client (Client): The Pyrogram client.
         message (Message): The trigger message object.
+        summary_prefix (str | None): Prefix string of the response message.
     """
     # send docs if message == "/summary"
     if equal_prefix(message.text, prefix=[PREFIX.AI_SUMMARY]):
@@ -78,13 +79,13 @@ async def ai_summary(client: Client, message: Message, **kwargs):
         reply_info = parse_msg(message.reply_to_message)
         end_time = reply_info["datetime"]
 
-    # 3️⃣ /summay #YYYYMMDDHHMMSS @user
-    # 4️⃣ /summay #YYYYMMDDHHMMSS-YYYYMMDDHHMMSS @user
+    # 3️⃣ /summary #YYYYMMDDHHMMSS @user
+    # 4️⃣ /summary #YYYYMMDDHHMMSS-YYYYMMDDHHMMSS @user
     if matched := re.match(r"^" + PREFIX.AI_SUMMARY + r"\s+#(\d{14})-?(\d{14})?(\s+)?(@\w+)?", info["text"]):
         begin_time = datetime.strptime(matched.group(1), "%Y%m%d%H%M%S").replace(tzinfo=ZoneInfo(TZ))
         end_time = datetime.strptime(matched.group(2) or end_time.strftime("%Y%m%d%H%M%S"), "%Y%m%d%H%M%S").replace(tzinfo=ZoneInfo(TZ))
         filter_user = matched.group(4) or ""
-    # 2️⃣ /summay #interval @user  (/summay #4h @user)
+    # 2️⃣ /summary #interval @user  (/summary #4h @user)
     elif matched := re.match(r"^" + PREFIX.AI_SUMMARY + r"\s+#(\d+)([mMhHdD])(\s+)?(@\w+)?", info["text"]):
         interval = int(matched.group(1))
         unit = matched.group(2).lower()
@@ -95,13 +96,12 @@ async def ai_summary(client: Client, message: Message, **kwargs):
             begin_time = end_time - timedelta(hours=interval)
         elif unit == "d":
             begin_time = end_time - timedelta(days=interval)
-    # 1️⃣ /summay #N @user
+    # 1️⃣ /summary #N @user
     elif matched := re.match(r"^" + PREFIX.AI_SUMMARY + r"\s+#(\d+)(\s+)?(@\w+)?", info["text"]):
         num_history = min(int(matched.group(1)), MAX_MESSAGE_SUMMARY)
         filter_user = matched.group(3) or ""
     else:
         return
-
     # set custom chat_id and message_id (useful for debug)
     if matched := re.search(r"cid=(-?\w+)", info["text"], re.IGNORECASE):
         info["cid"] = to_int(matched.group(1))
@@ -110,7 +110,6 @@ async def ai_summary(client: Client, message: Message, **kwargs):
     if kwargs.get("show_progress") and "progress" not in kwargs:
         res = await send2tg(client, message, texts=f"📝正在获取历史消息...\n⏩开始时间: {begin_time:%m-%d %H:%M:%S}\n⏯️结束时间: {end_time:%m-%d %H:%M:%S}", **kwargs)
         kwargs["progress"] = res[0]
-
     history = await get_parsed_chat_history(client, info["cid"], offset_id, num_history, begin_time, end_time, filter_user.removeprefix("@"))
 
     # parse the history contexts
@@ -148,9 +147,9 @@ async def ai_summary(client: Client, message: Message, **kwargs):
     response = await send_to_gpt(config, **kwargs)
     if texts := response.get("content"):
         texts = texts.strip("`")
-        if reasoning := response.get("reasoning"):
-            texts = f"{reasoning}\n{texts}"
-        await send2tg(client, message, texts=f"🤖**{response['model']}**:\n{texts}", **kwargs)
+        if summary_prefix is None:
+            summary_prefix = f"🤖**{response['model']}**:\n"
+        await send2tg(client, message, texts=f"{summary_prefix}⏩开始时间: {begin_time:%m-%d %H:%M:%S}\n⏯️结束时间: {end_time:%m-%d %H:%M:%S}\n{texts}", **kwargs)
         await modify_progress(del_status=True, **kwargs)
 
 
@@ -169,10 +168,11 @@ async def get_contexts(history: list[dict]) -> dict:
 每一条消息的格式如下:
 {
     "id": 消息ID, 按顺序递增,
+    "type": 消息类型,
     "time": 消息发送时间,
     "url": 消息链接,
     "username": 消息发送者,
-    "content": 本条消息内容,
+    "message": 本条消息内容,
     "reply_to_message": 回复消息的原始内容, 如果本消息并不回复其他消息, 则不存在该字段
 }
 
@@ -205,6 +205,8 @@ async def get_contexts(history: list[dict]) -> dict:
 
         if info["text"].startswith("👤"):  # social media
             continue
+        if info["is_bot"]:  # bots
+            continue
 
         if info["text"]:  # currently, we only include texts
             if len(user_context) == 0:
@@ -212,10 +214,11 @@ async def get_contexts(history: list[dict]) -> dict:
             end_time = info["datetime"]
             content = {
                 "id": info["mid"],
+                "type": info["mtype"],
                 "time": f"{info['datetime']:%H:%M:%S}",
                 "url": info["message_url"],
                 "username": info["full_name"],
-                "content": info["text"],
+                "message": info["text"],
             }
             if reply_msg_content := get_message_by_id(history, info.get("reply_to_message_id")):
                 content["reply_to_message"] = reply_msg_content
@@ -235,8 +238,9 @@ def get_message_by_id(history: list[dict], message_id: int | None = None) -> dic
 
     return {
         "id": info["mid"],
+        "type": info["mtype"],
         "time": f"{info['datetime']:%H:%M:%S}",
         "url": info["message_url"],
         "username": info["full_name"],
-        "content": info["text"],
+        "message": info["text"] or info["mtype"],
     }