notice.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  1. import requests
  2. from pydantic import BaseModel, Field
  3. from enum import Enum
  4. class MessageType(Enum):
  5. DEFAULT = 'DEFAULT',
  6. TEXT = 'TEXT',
  7. MARKDOWN = 'MARKDOWN',
  8. EMAIL = 'EMAIL'
  9. class Email(BaseModel):
  10. sender: str = Field(..., description='发件人')
  11. recipient: str = Field(..., description='收件人')
  12. subject: str = Field(..., description='主题')
  13. sendTime: str = Field(..., description='发送时间')
  14. content: str = Field(..., description='内容')
  15. class PushMessage(BaseModel):
  16. title: str = Field(..., description='标题')
  17. content: str = Field(..., description='通知内容')
  18. messageType: MessageType = Field(..., description='消息类型')
  19. text: str = Field(None, description='文本内容')
  20. email: Email = Field(None, description='邮件内容')
  21. def model_dump(self):
  22. # 重写model_dump方法以正确处理枚举类型
  23. data = super().model_dump()
  24. data['messageType'] = self.messageType.value
  25. return data
  26. def from_email(email: dict):
  27. sender_display = email["sender"].replace(' ', '\n').replace('"', '')
  28. recipient_display = email["recipient"].replace(' ', '\n')
  29. return PushMessage(
  30. title="新邮件通知",
  31. content=f'您有一封来自[{email["sender_name"] if email["sender_name"] else email["sender_email"]}]的邮件',
  32. messageType=MessageType.EMAIL,
  33. email=Email(
  34. sender=sender_display,
  35. recipient=recipient_display,
  36. subject=email['subject'],
  37. sendTime=email['date'],
  38. content=email['content'],
  39. )
  40. )
  41. class Push:
  42. def __init__(self, config: dict):
  43. self.config = config
  44. def send_notification(self, data: PushMessage):
  45. pass
  46. class AiYuFeiFei(Push):
  47. def __init__(self, config: dict):
  48. super().__init__(config)
  49. self.url = f'https://iyuu.cn/{config["token"]}.send'
  50. def send_notification(self, data: PushMessage):
  51. data = {
  52. 'text': data.title,
  53. 'desp': data.content
  54. }
  55. response = requests.post(self.url, json=data)
  56. print("爱语飞飞提醒发送结果:", response.json())
  57. class Yo(Push):
  58. def __init__(self, config: dict):
  59. super().__init__(config)
  60. def send_notification(self, data: PushMessage):
  61. headers = {
  62. 'x-api-key': self.config['token']
  63. }
  64. response = requests.post(self.config['url'], json=data.model_dump(), headers=headers)
  65. print("Yo 提醒发送结果:", response.json())
  66. class WeComWebhook(Push):
  67. """
  68. 企业微信 Webhook 推送
  69. """
  70. def __init__(self, config: dict):
  71. super().__init__(config)
  72. self.webhook_url = config.get('webhook_url', '')
  73. def send_notification(self, data: PushMessage):
  74. """
  75. 发送企业微信 webhook 通知
  76. 支持发送者、接收者、发送时间、主题等信息
  77. """
  78. if data.messageType == MessageType.EMAIL and data.email:
  79. # 使用文本格式发送,兼容性更好
  80. content = f"{data.title}\n\n" \
  81. f"发件人:{data.email.sender}\n" \
  82. f"收件人:{data.email.recipient}\n" \
  83. f"发送时间:{data.email.sendTime}\n" \
  84. f"主题:{data.email.subject}"
  85. else:
  86. content = f"{data.title}\n\n{data.content}"
  87. payload = {
  88. "msgtype": "text",
  89. "text": {
  90. "content": content
  91. }
  92. }
  93. try:
  94. response = requests.post(self.webhook_url, json=payload)
  95. result = response.json()
  96. print(f"企业微信 Webhook 推送结果:{result}")
  97. return result
  98. except Exception as e:
  99. print(f"企业微信 Webhook 推送失败:{e}")
  100. raise
  101. class PushFactory:
  102. @staticmethod
  103. def create_push(config: dict) -> Push:
  104. push_type = config.get('type', '')
  105. if push_type == 'WeComWebhook':
  106. return WeComWebhook(config)
  107. elif push_type == 'Yo':
  108. return Yo(config)
  109. elif push_type == 'AiYuFeiFei':
  110. return AiYuFeiFei(config)
  111. else:
  112. raise ValueError(f'不支持的推送类型:{push_type}')
  113. if __name__ == '__main__':
  114. # 测试企业微信 Webhook 推送
  115. webhook_config = {
  116. 'type': 'WeComWebhook',
  117. 'webhook_url': 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=d5b3282e-7531-462f-9b48-e117fb2797f6' # 替换为你的企业微信 webhook 地址
  118. }
  119. # 创建测试邮件消息
  120. test_email = PushMessage(
  121. title="新邮件通知",
  122. content="您有一封来自 [test@example.com] 的邮件",
  123. messageType=MessageType.EMAIL,
  124. email=Email(
  125. sender="张三 <zhangsan@example.com>",
  126. recipient="李四 <lisi@example.com>",
  127. subject="测试邮件主题",
  128. sendTime="2026-03-25 10:30:00",
  129. content="这是一封测试邮件的内容...\n\n请查收!"
  130. )
  131. )
  132. # 测试推送
  133. try:
  134. push = PushFactory.create_push(webhook_config)
  135. print("开始测试企业微信 Webhook 推送...")
  136. result = push.send_notification(test_email)
  137. print(f"测试完成!返回结果:{result}")
  138. except Exception as e:
  139. print(f"测试失败:{e}")