102 lines
2.5 KiB
Python
102 lines
2.5 KiB
Python
"""信息发送管理模块"""
|
|
import requests
|
|
from logger import get_logger
|
|
|
|
logger = get_logger(__name__)
|
|
|
|
|
|
class NotificationManager:
|
|
"""通知管理器"""
|
|
|
|
def __init__(self, token: str = "", provider: str = "iyuu"):
|
|
"""
|
|
初始化通知管理器
|
|
|
|
Args:
|
|
token: 通知token
|
|
provider: 通知服务提供商 (iyuu, wechat, dingtalk等)
|
|
"""
|
|
self.token = token
|
|
self.provider = provider
|
|
self.api_url = f"https://iyuu.cn/{token}.send" if provider == "iyuu" else ""
|
|
|
|
def send(self, title: str, content: str) -> bool:
|
|
"""
|
|
发送通知
|
|
|
|
Args:
|
|
title: 通知标题
|
|
content: 通知内容
|
|
|
|
Returns:
|
|
是否发送成功
|
|
"""
|
|
if not self.token:
|
|
logger.warning("未配置通知token,跳过发送")
|
|
return False
|
|
|
|
if self.provider == "iyuu":
|
|
return self._send_iyuu(title, content)
|
|
else:
|
|
logger.warning(f"不支持的通知提供商: {self.provider}")
|
|
return False
|
|
|
|
def _send_iyuu(self, title: str, content: str) -> bool:
|
|
"""
|
|
通过爱语飞飞发送通知
|
|
|
|
Args:
|
|
title: 通知标题
|
|
content: 通知内容
|
|
|
|
Returns:
|
|
是否发送成功
|
|
"""
|
|
try:
|
|
logger.info(f"发送通知: {title}")
|
|
|
|
response = requests.post(
|
|
self.api_url,
|
|
json={
|
|
'text': title,
|
|
'desp': content
|
|
},
|
|
timeout=10
|
|
)
|
|
|
|
response.raise_for_status()
|
|
result = response.json()
|
|
|
|
if result.get('errcode') == 0:
|
|
logger.info("通知发送成功")
|
|
return True
|
|
else:
|
|
logger.error(f"通知发送失败: {result.get('errmsg')}")
|
|
return False
|
|
|
|
except requests.RequestException as e:
|
|
logger.error(f"通知请求失败: {e}")
|
|
return False
|
|
except Exception as e:
|
|
logger.error(f"通知发送异常: {e}")
|
|
return False
|
|
|
|
|
|
def create_notification_manager(config: dict) -> NotificationManager:
|
|
"""
|
|
根据配置创建通知管理器
|
|
|
|
Args:
|
|
config: 通知配置字典
|
|
|
|
Returns:
|
|
通知管理器实例
|
|
"""
|
|
token = config.get('iyuu_token', '')
|
|
provider = config.get('provider', 'iyuu')
|
|
|
|
if token:
|
|
return NotificationManager(token=token, provider=provider)
|
|
|
|
return None
|