Commit fa11ddd

benny-dou <60535774+benny-dou@users.noreply.github.com>
2025-07-02 08:11:18
style(history): improve query chat history
1 parent 5c1709e
Changed files (1)
src
history
src/history/query.py
@@ -103,6 +103,7 @@ async def query_chat_history(client: Client, message: Message, **kwargs):
 
     results = await query_turso(client, chatinfo, match_time, user, keyword)
     texts = results.get("texts", "")
+
     count = results.get("count", 0)
 
     if not texts:
@@ -113,6 +114,7 @@ async def query_chat_history(client: Client, message: Message, **kwargs):
         await modify_progress(message=status_msg, text=blockquote(texts), force_update=True, **kwargs)
         return
 
+    texts = results.get("full_texts", "")  # use full texts
     caption += f"\n#️⃣消息数: {count}"
     # less than 100,000, add instant view
     if len(texts) < 1000000 and (telegraph_url := await publish_telegraph(title=f"【{chat_title}】{user}{match_time} {keyword}", html=convert_html(texts), author=user or chat_title)):
@@ -204,12 +206,23 @@ async def query_turso(client: Client, cinfo: dict[str, str], match_time: str, us
     sql += " ORDER BY T.mid DESC"
     logger.info(sql)
     resp = await turso_exec([{"type": "execute", "stmt": {"sql": sql}}], silent=True, retry=2, **TURSO_KWARGS)
-    texts = ""
+    full_texts = ""
+    texts = ""  # long message will be trimmed
     count = 0
     for row in turso_parse_resp(resp):
         url = f"https://t.me/{cinfo['chandle']}/{row['mid']}" if cinfo["chandle"] else f"https://t.me/c/{cinfo['cid']}/{row['mid']}"
-        username = row["fullname"] or "匿名"
+        username = row["fullname"] or "消息链接"
         emoji = MTYPE_EMOJI[row["mtype"]] if row["mtype"] != "text" else ""
-        texts += f"👤[{username}]({url}) {row['time']}{emoji}:\n{row['content']}\n"
+        full_texts += f"\n👤[{username}]({url}) {row['time']}{emoji}:\n{row['content']}\n"
+        # trim long message
+        content: str = row["content"]
+        if len(row["content"]) > 100:
+            idx = content.find(keyword)  # -1 if not found
+            begin = max(0, idx - 45)
+            begin_prefix = "..." if begin > 0 else ""
+            end = min(len(content), idx + len(keyword) + 45)
+            end_suffix = "..." if end != len(content) else ""
+            content = f"{begin_prefix}{row['content'][begin:end]}{end_suffix}"
+        texts += f"\n👤[{username}]({url}) {row['time']}{emoji}:\n{content}\n"
         count += 1
-    return {"texts": texts.strip(), "count": count}
+    return {"texts": texts.strip(), "full_texts": full_texts.strip(), "count": count}