38 lines
1.5 KiB
Python
38 lines
1.5 KiB
Python
import requests
|
|
|
|
class LarkNotifier:
|
|
"""飞书消息发送工具类"""
|
|
|
|
def __init__(self, bot_name="weibo", receive_id="on_f972f5f8c4de6ac967574b97dc8c1d82"):
|
|
# 将基础配置放在初始化中,方便后续修改或通过环境变量传入
|
|
self.url = "https://zhiyinzhe.xyz/sendMsg/api/send"
|
|
self.bot_name = bot_name
|
|
self.receive_id = receive_id
|
|
|
|
# 使用 Session 可以复用底层 TCP 连接,提升发送效率
|
|
self.session = requests.Session()
|
|
|
|
def send_alert(self, title: str, content: str):
|
|
"""
|
|
发送通用文本告警
|
|
:param title: 告警标题 (如 "⚠️ 市场获取失败")
|
|
:param content: 告警具体内容 (如 "Slug: xxx \n 原因: xxx")
|
|
"""
|
|
payload = {
|
|
"bot_name": self.bot_name,
|
|
"receive_id": self.receive_id,
|
|
"receive_id_type": "union_id",
|
|
"content": f"{title}\n{content}"
|
|
}
|
|
|
|
try:
|
|
# 使用 data=payload 发送 Form Data
|
|
response = self.session.post(self.url, data=payload, timeout=5)
|
|
response.raise_for_status()
|
|
print(f"告警发送成功: {title}")
|
|
except Exception as e:
|
|
# 告警系统自身的错误只记录日志,绝不抛出异常影响主程序
|
|
print(f"发送飞书告警失败: {e}")
|
|
|
|
# 实例化一个全局单例供其他模块直接导入使用
|
|
lark_notifier = LarkNotifier() |