"""把关键事件推到自建 ntfy(失败绝不拖垮 API)。""" from __future__ import annotations import asyncio import logging from typing import Any import httpx from app.config import settings logger = logging.getLogger(__name__) async def notify( message: str, *, title: str = "Dymini", tags: str | None = None, priority: int = 3, ) -> bool: if not settings.ntfy_enabled: return False base = settings.ntfy_base_url.rstrip("/") topic = settings.ntfy_topic.strip().strip("/") if not base or not topic: return False payload: dict[str, Any] = { "topic": topic, "message": message, "title": title, "priority": max(1, min(5, int(priority))), } if tags: payload["tags"] = [t.strip() for t in tags.split(",") if t.strip()] headers: dict[str, str] = {"Content-Type": "application/json"} token = (settings.ntfy_token or "").strip() if token: headers["Authorization"] = f"Bearer {token}" try: # 短超时:本地无 ntfy 时不能卡住登录/读接口 async with httpx.AsyncClient(timeout=1.5) as client: r = await client.post(base, json=payload, headers=headers) if r.status_code >= 400: logger.warning("ntfy publish failed: %s %s", r.status_code, r.text[:200]) return False return True except Exception as e: logger.warning("ntfy publish error: %s", e) return False def notify_later( message: str, *, title: str = "Dymini", tags: str | None = None, priority: int = 3, ) -> None: """后台推送,不阻塞当前请求。""" if not settings.ntfy_enabled: return try: loop = asyncio.get_running_loop() loop.create_task(notify(message, title=title, tags=tags, priority=priority)) except RuntimeError: pass def summarize_wx_event(root: dict[str, Any]) -> tuple[str, str, str]: """返回 (title, message, tags)。""" event = str(root.get("Event") or root.get("event") or "") msg_type = str(root.get("MsgType") or root.get("msg_type") or "").lower() openid = str(root.get("OpenId") or root.get("FromUserName") or root.get("openid") or "")[-8:] if event == "xpay_goods_deliver_notify" or root.get("GoodsInfo") or root.get("OutTradeNo"): out_trade_no = root.get("OutTradeNo") or root.get("out_trade_no") or "-" product = "" gi = root.get("GoodsInfo") or {} if isinstance(gi, dict): product = str(gi.get("ProductId") or gi.get("product_id") or "") title = "支付发货" msg = f"订单 {out_trade_no}" if product: msg += f" · 道具 {product}" if openid: msg += f" · …{openid}" return title, msg, "moneybag,white_check_mark" if msg_type in {"text", "image", "voice", "video", "miniprogrampage"}: content = str(root.get("Content") or root.get("Recognition") or "")[:180] title = "用户消息" msg = content or f"收到 {msg_type}" if openid: msg = f"…{openid}: {msg}" return title, msg, "speech_balloon" if event: title = "抖音事件" msg = event if openid: msg += f" · …{openid}" return title, msg, "bell" title = "平台推送" msg = str(root)[:180] return title, msg, "incoming_envelope"