douyinWEB/backend/app/watch_remind.py
2026-08-15 04:59:15 -05:00

75 lines
2.4 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# -*- coding: utf-8 -*-
"""Anchor watch reminders — notify when high-confidence opens are overdue."""
from __future__ import annotations
import time
from typing import Any
from . import db
from .notify import send_webhook
def _dedupe_key(room_id: str, day_bucket: int) -> str:
return f"watch_remind:{room_id}:{day_bucket}"
async def check_and_notify(*, now: float | None = None) -> dict[str, Any]:
"""Scan upcoming opens; fire webhook once per room per ~3h window when overdue."""
cfg = db.get_settings_map()
if not cfg.get("notify_on_watch_remind", True):
return {"sent": 0, "skipped": "disabled"}
now = float(now or time.time())
window = max(300, int(cfg.get("watch_remind_window_sec") or 1800))
items = db.list_upcoming_opens(limit=40, priority_only=False)
sent = 0
checked = 0
for it in items:
conf = float(it.get("confidence") or 0)
if conf < 0.65 and not it.get("priority"):
continue
eta = float(it.get("eta_ts") or 0)
if eta <= 0:
continue
# Only remind when ETA is due / slightly overdue (within window)
if eta > now + 120:
continue
if now - eta > window:
continue
checked += 1
rid = str(it.get("room_id") or it.get("room_pk") or "")
if not rid:
continue
bucket = int(now // 10800) # 3h dedupe buckets
key = _dedupe_key(rid, bucket)
try:
prev = db.get_kv(key)
if prev:
continue
except Exception:
pass
name = str(it.get("anchor_name") or rid)
msg = (
f"【盯梢】{name} 预计开播窗口已到"
+ (f"(置信 {int(conf*100)}%)" if conf else "")
+ (f" · {it.get('typical_open_hint')}" if it.get("typical_open_hint") else "")
)
await send_webhook(
"watch_remind",
{
"message": msg,
"anchor_name": name,
"room_id": rid,
"room_pk": it.get("room_pk"),
"url": it.get("url"),
"eta_ts": eta,
"confidence": conf,
"priority": bool(it.get("priority")),
},
)
try:
db.set_kv(key, {"ts": now, "anchor": name})
except Exception:
pass
sent += 1
return {"sent": sent, "checked": checked, "candidates": len(items)}