"""通知通道。 设计要点: - 通道可插拔(企业微信 / 飞书),单个通道失败不影响其他通道,也不影响主循环 - 告警(Cookie 失效、登录提示)带冷却,避免每 5 秒往群里刷一条 - 所有 webhook 从配置读取,源码里不再出现密钥 """ from __future__ import annotations import logging import time from typing import Dict, List, Protocol, Tuple import requests from .config import Config log = logging.getLogger("fengxiang.notify") class Channel(Protocol): name: str def send(self, text: str) -> None: # pragma: no cover - 协议声明 ... class WecomChannel: name = "wecom" def __init__(self, webhook: str, timeout: int = 10): self.webhook = webhook self.timeout = timeout def send(self, text: str) -> None: payload = {"msgtype": "text", "text": {"content": text}} resp = requests.post(self.webhook, json=payload, timeout=self.timeout) data = resp.json() if data.get("errcode") != 0: raise RuntimeError(f"企业微信返回错误: {data}") class FeishuChannel: name = "feishu" def __init__(self, webhook: str, timeout: int = 10): self.webhook = webhook self.timeout = timeout def send(self, text: str) -> None: payload = {"msg_type": "text", "content": {"text": text}} resp = requests.post(self.webhook, json=payload, timeout=self.timeout) data = resp.json() # 飞书新老版本返回结构不同,统一取出成功标志 code = data.get("code", data.get("StatusCode")) if code != 0: raise RuntimeError(f"飞书返回错误: {data}") def build_channels(cfg: Config) -> List[Channel]: channels: List[Channel] = [] for name in cfg.notify.channels: if name == "wecom" and cfg.notify.wecom_webhook: channels.append(WecomChannel(cfg.notify.wecom_webhook)) elif name == "feishu" and cfg.notify.feishu_enabled and cfg.notify.feishu_webhook: channels.append(FeishuChannel(cfg.notify.feishu_webhook)) else: log.warning("通道 %s 已配置但缺少 webhook/token,跳过", name) return channels class Dispatcher: def __init__(self, channels: List[Channel], alert_cooldown_sec: int = 1800): self.channels = channels self.alert_cooldown_sec = alert_cooldown_sec self._last_alert: Dict[str, float] = {} def notify(self, text: str) -> Dict[str, bool]: """广播一条消息,返回各通道成功与否。异常不外抛。""" result: Dict[str, bool] = {} for ch in self.channels: try: ch.send(text) result[ch.name] = True log.info("推送成功 [%s] %s", ch.name, text.replace("\n", " ")[:80]) except Exception as exc: # noqa: BLE001 - 推送失败绝不能让监控挂掉 result[ch.name] = False log.error("推送失败 [%s]: %s", ch.name, exc) if not self.channels: log.warning("未配置任何推送通道,消息未发出: %s", text) return result def alert(self, key: str, text: str) -> Tuple[bool, str]: """带冷却的告警。同一 key 在冷却期内不重复发送。""" now = time.time() last = self._last_alert.get(key, 0) if now - last < self.alert_cooldown_sec: log.debug("告警 %s 处于冷却期,跳过", key) return False, "cooldown" self._last_alert[key] = now self.notify(text) return True, "sent"