baodan/api/insurance/utils/notify.py

63 lines
1.9 KiB
Python
Raw Normal View History

"""企微 Webhook 通知服务同步失败告警、Token 超限通知等。"""
import requests
from flask import current_app
def send_wecom_webhook(title: str, content: str):
"""通过企微群机器人 Webhook 发送通知。
Args:
title: 消息标题
content: 消息内容支持 Markdown
"""
webhook_url = current_app.config.get("WECOM_WEBHOOK_URL", "")
if not webhook_url:
current_app.logger.warning("WECOM_WEBHOOK_URL 未配置,跳过通知")
return
payload = {
"msgtype": "markdown",
"markdown": {
"content": f"## {title}\n\n{content}",
},
}
try:
resp = requests.post(webhook_url, json=payload, timeout=10)
result = resp.json()
if result.get("errcode") != 0:
current_app.logger.error(f"企微 Webhook 发送失败: {result}")
except Exception as e:
current_app.logger.error(f"企微 Webhook 请求异常: {e}")
def notify_sync_failure(datasource_name: str, error_msg: str):
"""数据源同步失败通知。"""
send_wecom_webhook(
"⚠️ 数据源同步失败",
f"**数据源**: {datasource_name}\n"
f"**错误**: {error_msg}\n"
f"**时间**: 请检查数据源配置并重试",
)
def notify_token_limit_reached(username: str, token_usage: int, limit: int):
"""Token 超限通知。"""
send_wecom_webhook(
"⚠️ Token 消耗超限",
f"**用户**: {username}\n"
f"**已用**: {token_usage:,} tokens\n"
f"**限额**: {limit:,} tokens\n"
f"**建议**: 联系管理员调整配额",
)
def notify_proposal_generated(username: str, customer_name: str):
"""方案生成完成通知。"""
send_wecom_webhook(
"✅ 推荐方案已生成",
f"**操作人**: {username}\n"
f"**客户**: {customer_name}\n"
f"**状态**: 方案已就绪,请查看",
)