Commit 915c9c4

benny-dou <60535774+benny-dou@users.noreply.github.com>
2026-01-21 10:23:21
fix(danmu): correct live date matching
Ensure that live dates are accurately matched even when danmu entries are sent after midnight
1 parent 21ecde7
Changed files (2)
src/danmu/entrypoint.py
@@ -74,7 +74,7 @@ async def query_danmu(client: Client, message: Message, **kwargs):
     caption += f"\n👤用户: {user}"
     caption += f"\n🔤关键词: {keyword}"
 
-    status_msg = (await send2tg(client, message, texts=caption, **kwargs))[0]
+    status_msg = (await send2tg(client, message, texts=caption, **kwargs))[0] if kwargs.get("show_progress") else None
     kwargs["progress"] = status_msg
 
     super_chats = defaultdict(Decimal)  # {"currency": amount}
src/danmu/turso.py
@@ -3,7 +3,6 @@
 from collections import defaultdict
 from datetime import datetime, timedelta
 from decimal import Decimal
-from zoneinfo import ZoneInfo
 
 import anyio
 from loguru import logger
@@ -81,8 +80,6 @@ async def parse_from_turso(data: list[dict], user: str, keyword: str, super_chat
     """解析从Turso获取的记录.
 
     日期从新到旧, 数据从旧到新
-    注意, 如果获取到的弹幕的发送时间过了凌晨, 则该弹幕会被当成第二天的数据
-    为了获取该条弹幕实际的开播日期, 需要用前一天的日期去获取真实的开播日期
 
     COLUMNS = {
     "发言": "time TEXT, content TEXT, segmented TEXT",
@@ -93,12 +90,8 @@ async def parse_from_turso(data: list[dict], user: str, keyword: str, super_chat
     # group by dates
     grouped_data = defaultdict(list)  # {date: list[dict]}
     for x in data:
-        time = datetime.strptime(x["time"], "%Y-%m-%d %H:%M:%S").replace(tzinfo=ZoneInfo(TZ))
-        if time.hour < 8:  # 如果发言时间在凌晨, 则认为是第二天的数据, 需要用前一天的日期去获取真实的开播日期  # noqa: SIM108
-            real_date = (time - timedelta(days=1)).strftime("%Y-%m-%d")
-        else:
-            real_date = time.strftime("%Y-%m-%d")
-        grouped_data[real_date].append(x)
+        grouped_data[x["time"][:10]].append(x)
+
     texts = ""
     count = 0
     for date, items in sorted(grouped_data.items(), reverse=True):  # 日期从新到旧
@@ -136,15 +129,29 @@ async def parse_from_turso(data: list[dict], user: str, keyword: str, super_chat
 @cache.memoize(ttl=60)
 async def get_liveinfo() -> dict:
     resp = await turso_exec([{"type": "execute", "stmt": {"sql": "SELECT * FROM liveinfo;"}}], silent=True, **TURSO_KWARGS)
-    logger.warning("Get liveinfo from Turso")
     return {x["liveDate"]: x for x in turso_parse_resp(resp)}
 
 
 async def live_date(date: str) -> str:
+    """Use fuzzy match to get live date.
+
+    有时候过了凌晨的发言, 会被认为是第二天的数据
+    如果匹配不到发言日期, 使用相邻日期进行匹配
+
+    Args:
+        date: The date to match, in the format of "YYYY-MM-DD".
+
+    Returns:
+        str:
+    """
     liveinfo = await get_liveinfo()
-    matched = [v for k, v in liveinfo.items() if k[:10] == date]
-    titles = [x.get("title", "") for x in matched]
-    urls = [x.get("url", "") for x in matched]
-    markdown = [f"[{title}]({url})" for title, url in zip(titles, urls, strict=True)]
-    texts = date + "\n" + "\n".join(markdown)
-    return texts.rstrip()
+    dt = datetime.strptime(date, "%Y-%m-%d")  # noqa: DTZ007
+    possible_dates = [date, (dt - timedelta(days=1)).strftime("%Y-%m-%d"), (dt + timedelta(days=1)).strftime("%Y-%m-%d")]
+    for d in possible_dates:
+        if matched := [v for k, v in liveinfo.items() if k[:10] == d]:
+            titles = [x.get("title", "") for x in matched]
+            urls = [x.get("url", "") for x in matched]
+            markdown = [f"[{title}]({url})" for title, url in zip(titles, urls, strict=True)]
+            texts = d + "\n" + "\n".join(markdown)
+            return texts.rstrip()
+    return date