autool-dispatcher/notify_manager.py
2026-06-17 19:50:39 +08:00

63 lines
2.4 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.

import requests
import logging
import time
logger = logging.getLogger(__name__)
class Notifier:
def __init__(self, wechat_tokens, wecom_tokens=None):
self.wechat_tokens = wechat_tokens
self.wecom_tokens = wecom_tokens or {}
# Dispatcher 端不需要获取本机 IP告警信息中通常包含 Worker ID
# self.ip = self._get_ip_address()
def send_wechat_alert(self, worker_id, message):
"""发送微信告警
Args:
worker_id: 发生告警的 Worker ID
message: 告警内容
"""
title = f"设备告警:{worker_id}"
if not self.wechat_tokens:
logger.warning("未配置微信推送 Token跳过发送。")
return
for name, token in self.wechat_tokens.items():
url = f'https://wx.xtuis.cn/{token}.send'
try:
requests.post(url, data={'text': title, 'desp': f"设备 {worker_id} {message}"}, timeout=10)
logger.info(f"告警已发送给: {name}")
time.sleep(3) # 避免发送太快导致失败
except Exception as e:
logger.warning(f"发送告警失败: {e}")
def send_weCom_alert(self, worker_id, message):
"""发送企业微信告警
Args:
worker_id: 发生告警的 Worker ID
message: 告警内容
"""
title = f"{time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())}, {worker_id}"
content = f"{title}\n\n{message}"
if not self.wecom_tokens:
logger.warning("未配置企业微信 Webhook Key跳过发送。")
return
for name, key in self.wecom_tokens.items():
url = f'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key={key}'
payload = {
"msgtype": "text",
"text": {
"content": content
}
}
try:
response = requests.post(url, json=payload, timeout=10)
if response.status_code == 200:
logger.info(f"企业微信告警已发送给: {name}")
else:
logger.warning(f"发送企业微信告警到 {name} 失败: HTTP {response.status_code}, {response.text}")
except Exception as e:
logger.warning(f"发送企业微信告警到 {name} 失败: {e}")