nomadro/apps/api/services/ebook_svc/services/ntfy.py
eric 3e5b7c2098 Monorepo super-optimize: src layout, workspace scripts, docs.
Collapse portal under src/, unify pnpm workspace/scripts, thin VIP topic re-exports, drop orphan vip scaffolds and one-shot scripts, ignore xhs/release, document root commands.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-01 00:34:04 +08:00

92 lines
2.9 KiB
Python
Raw 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.

"""把关键事件推到自建 ntfy(https://ntfy.nomadro.cn)。"""
from __future__ import annotations
import logging
from typing import Any
import httpx
from ebook_svc.config import settings
logger = logging.getLogger(__name__)
async def notify(
message: str,
*,
title: str = "Nomadmini",
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:
async with httpx.AsyncClient(timeout=8.0) 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:
logger.exception("ntfy publish error")
return False
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"