# ntfy_utils.py import requests import config def send_ntfy(message, title="数据库同步消息", priority="default", tags=None): """ 向加密的 ntfy 服务器发送消息 """ conf = config.NTFY_CONFIG if not conf.get('enabled', False): return # 确保 URL 正确(末尾不要多余斜杠) server_url = conf['server_url'].rstrip('/') url = f"{server_url}/{conf['topic']}" # 构造请求头 headers = { "Title": title.encode('utf-8'), "Priority": priority, "Tags": ",".join(tags) if tags else "" } # --- 核心:配置秘钥认证 --- token = conf.get('token') if token: # ntfy 使用 Bearer Token 模式 headers["Authorization"] = f"Bearer {token}" try: # 发送请求 response = requests.post( url, data=message.encode('utf-8'), headers=headers, timeout=10 ) # 针对认证失败的处理 if response.status_code == 401: print("ntfy 认证失败:Token 无效") elif response.status_code == 403: print("ntfy 权限不足:该 Token 无权发布消息") response.raise_for_status() except Exception as e: print(f"发送 ntfy 通知失败: {e}") def send_error(msg): """便捷方法:发送错误通知""" send_ntfy( message=str(msg), title="❌ 同步任务错误", priority=config.NTFY_CONFIG['priority']['error'], tags=["warning", "database"] ) def send_critical(msg): """便捷方法:发送严重崩溃通知""" send_ntfy( message=str(msg), title="🔥 同步服务崩溃", priority=config.NTFY_CONFIG['priority']['critical'], tags=["skull", "critical"] )