senders.py 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033
  1. # coding=utf-8
  2. """
  3. 消息发送器模块
  4. 将报告数据发送到各种通知渠道:
  5. - 飞书 (Feishu/Lark)
  6. - 钉钉 (DingTalk)
  7. - 企业微信 (WeCom/WeWork)
  8. - Telegram
  9. - 邮件 (Email)
  10. - ntfy
  11. - Bark
  12. - Slack
  13. 每个发送函数都支持分批发送,并通过参数化配置实现与 CONFIG 的解耦。
  14. """
  15. import smtplib
  16. import time
  17. from datetime import datetime
  18. from email.header import Header
  19. from email.mime.multipart import MIMEMultipart
  20. from email.mime.text import MIMEText
  21. from email.utils import formataddr, formatdate, make_msgid
  22. from pathlib import Path
  23. from typing import Callable, Dict, List, Optional
  24. from urllib.parse import urlparse
  25. import requests
  26. from .batch import add_batch_headers, get_max_batch_header_size
  27. from .formatters import convert_markdown_to_mrkdwn, strip_markdown
  28. # === SMTP 邮件配置 ===
  29. SMTP_CONFIGS = {
  30. # Gmail(使用 STARTTLS)
  31. "gmail.com": {"server": "smtp.gmail.com", "port": 587, "encryption": "TLS"},
  32. # QQ邮箱(使用 SSL,更稳定)
  33. "qq.com": {"server": "smtp.qq.com", "port": 465, "encryption": "SSL"},
  34. # Outlook(使用 STARTTLS)
  35. "outlook.com": {"server": "smtp-mail.outlook.com", "port": 587, "encryption": "TLS"},
  36. "hotmail.com": {"server": "smtp-mail.outlook.com", "port": 587, "encryption": "TLS"},
  37. "live.com": {"server": "smtp-mail.outlook.com", "port": 587, "encryption": "TLS"},
  38. # 网易邮箱(使用 SSL,更稳定)
  39. "163.com": {"server": "smtp.163.com", "port": 465, "encryption": "SSL"},
  40. "126.com": {"server": "smtp.126.com", "port": 465, "encryption": "SSL"},
  41. # 新浪邮箱(使用 SSL)
  42. "sina.com": {"server": "smtp.sina.com", "port": 465, "encryption": "SSL"},
  43. # 搜狐邮箱(使用 SSL)
  44. "sohu.com": {"server": "smtp.sohu.com", "port": 465, "encryption": "SSL"},
  45. # 天翼邮箱(使用 SSL)
  46. "189.cn": {"server": "smtp.189.cn", "port": 465, "encryption": "SSL"},
  47. # 阿里云邮箱(使用 TLS)
  48. "aliyun.com": {"server": "smtp.aliyun.com", "port": 465, "encryption": "TLS"},
  49. }
  50. def send_to_feishu(
  51. webhook_url: str,
  52. report_data: Dict,
  53. report_type: str,
  54. update_info: Optional[Dict] = None,
  55. proxy_url: Optional[str] = None,
  56. mode: str = "daily",
  57. account_label: str = "",
  58. *,
  59. batch_size: int = 29000,
  60. batch_interval: float = 1.0,
  61. split_content_func: Callable = None,
  62. get_time_func: Callable = None,
  63. ) -> bool:
  64. """
  65. 发送到飞书(支持分批发送)
  66. Args:
  67. webhook_url: 飞书 Webhook URL
  68. report_data: 报告数据
  69. report_type: 报告类型
  70. update_info: 更新信息(可选)
  71. proxy_url: 代理 URL(可选)
  72. mode: 报告模式 (daily/current)
  73. account_label: 账号标签(多账号时显示)
  74. batch_size: 批次大小(字节)
  75. batch_interval: 批次发送间隔(秒)
  76. split_content_func: 内容分批函数
  77. get_time_func: 获取当前时间的函数
  78. Returns:
  79. bool: 发送是否成功
  80. """
  81. headers = {"Content-Type": "application/json"}
  82. proxies = None
  83. if proxy_url:
  84. proxies = {"http": proxy_url, "https": proxy_url}
  85. # 日志前缀
  86. log_prefix = f"飞书{account_label}" if account_label else "飞书"
  87. # 预留批次头部空间,避免添加头部后超限
  88. header_reserve = get_max_batch_header_size("feishu")
  89. batches = split_content_func(
  90. report_data,
  91. "feishu",
  92. update_info,
  93. max_bytes=batch_size - header_reserve,
  94. mode=mode,
  95. )
  96. # 统一添加批次头部(已预留空间,不会超限)
  97. batches = add_batch_headers(batches, "feishu", batch_size)
  98. print(f"{log_prefix}消息分为 {len(batches)} 批次发送 [{report_type}]")
  99. # 逐批发送
  100. for i, batch_content in enumerate(batches, 1):
  101. content_size = len(batch_content.encode("utf-8"))
  102. print(
  103. f"发送{log_prefix}第 {i}/{len(batches)} 批次,大小:{content_size} 字节 [{report_type}]"
  104. )
  105. total_titles = sum(
  106. len(stat["titles"]) for stat in report_data["stats"] if stat["count"] > 0
  107. )
  108. now = get_time_func() if get_time_func else datetime.now()
  109. payload = {
  110. "msg_type": "text",
  111. "content": {
  112. "total_titles": total_titles,
  113. "timestamp": now.strftime("%Y-%m-%d %H:%M:%S"),
  114. "report_type": report_type,
  115. "text": batch_content,
  116. },
  117. }
  118. try:
  119. response = requests.post(
  120. webhook_url, headers=headers, json=payload, proxies=proxies, timeout=30
  121. )
  122. if response.status_code == 200:
  123. result = response.json()
  124. # 检查飞书的响应状态
  125. if result.get("StatusCode") == 0 or result.get("code") == 0:
  126. print(f"{log_prefix}第 {i}/{len(batches)} 批次发送成功 [{report_type}]")
  127. # 批次间间隔
  128. if i < len(batches):
  129. time.sleep(batch_interval)
  130. else:
  131. error_msg = result.get("msg") or result.get("StatusMessage", "未知错误")
  132. print(
  133. f"{log_prefix}第 {i}/{len(batches)} 批次发送失败 [{report_type}],错误:{error_msg}"
  134. )
  135. return False
  136. else:
  137. print(
  138. f"{log_prefix}第 {i}/{len(batches)} 批次发送失败 [{report_type}],状态码:{response.status_code}"
  139. )
  140. return False
  141. except Exception as e:
  142. print(f"{log_prefix}第 {i}/{len(batches)} 批次发送出错 [{report_type}]:{e}")
  143. return False
  144. print(f"{log_prefix}所有 {len(batches)} 批次发送完成 [{report_type}]")
  145. return True
  146. def send_to_dingtalk(
  147. webhook_url: str,
  148. report_data: Dict,
  149. report_type: str,
  150. update_info: Optional[Dict] = None,
  151. proxy_url: Optional[str] = None,
  152. mode: str = "daily",
  153. account_label: str = "",
  154. *,
  155. batch_size: int = 20000,
  156. batch_interval: float = 1.0,
  157. split_content_func: Callable = None,
  158. ) -> bool:
  159. """
  160. 发送到钉钉(支持分批发送)
  161. Args:
  162. webhook_url: 钉钉 Webhook URL
  163. report_data: 报告数据
  164. report_type: 报告类型
  165. update_info: 更新信息(可选)
  166. proxy_url: 代理 URL(可选)
  167. mode: 报告模式 (daily/current)
  168. account_label: 账号标签(多账号时显示)
  169. batch_size: 批次大小(字节)
  170. batch_interval: 批次发送间隔(秒)
  171. split_content_func: 内容分批函数
  172. Returns:
  173. bool: 发送是否成功
  174. """
  175. headers = {"Content-Type": "application/json"}
  176. proxies = None
  177. if proxy_url:
  178. proxies = {"http": proxy_url, "https": proxy_url}
  179. # 日志前缀
  180. log_prefix = f"钉钉{account_label}" if account_label else "钉钉"
  181. # 预留批次头部空间,避免添加头部后超限
  182. header_reserve = get_max_batch_header_size("dingtalk")
  183. batches = split_content_func(
  184. report_data,
  185. "dingtalk",
  186. update_info,
  187. max_bytes=batch_size - header_reserve,
  188. mode=mode,
  189. )
  190. # 统一添加批次头部(已预留空间,不会超限)
  191. batches = add_batch_headers(batches, "dingtalk", batch_size)
  192. print(f"{log_prefix}消息分为 {len(batches)} 批次发送 [{report_type}]")
  193. # 逐批发送
  194. for i, batch_content in enumerate(batches, 1):
  195. content_size = len(batch_content.encode("utf-8"))
  196. print(
  197. f"发送{log_prefix}第 {i}/{len(batches)} 批次,大小:{content_size} 字节 [{report_type}]"
  198. )
  199. payload = {
  200. "msgtype": "markdown",
  201. "markdown": {
  202. "title": f"TrendRadar 热点分析报告 - {report_type}",
  203. "text": batch_content,
  204. },
  205. }
  206. try:
  207. response = requests.post(
  208. webhook_url, headers=headers, json=payload, proxies=proxies, timeout=30
  209. )
  210. if response.status_code == 200:
  211. result = response.json()
  212. if result.get("errcode") == 0:
  213. print(f"{log_prefix}第 {i}/{len(batches)} 批次发送成功 [{report_type}]")
  214. # 批次间间隔
  215. if i < len(batches):
  216. time.sleep(batch_interval)
  217. else:
  218. print(
  219. f"{log_prefix}第 {i}/{len(batches)} 批次发送失败 [{report_type}],错误:{result.get('errmsg')}"
  220. )
  221. return False
  222. else:
  223. print(
  224. f"{log_prefix}第 {i}/{len(batches)} 批次发送失败 [{report_type}],状态码:{response.status_code}"
  225. )
  226. return False
  227. except Exception as e:
  228. print(f"{log_prefix}第 {i}/{len(batches)} 批次发送出错 [{report_type}]:{e}")
  229. return False
  230. print(f"{log_prefix}所有 {len(batches)} 批次发送完成 [{report_type}]")
  231. return True
  232. def send_to_wework(
  233. webhook_url: str,
  234. report_data: Dict,
  235. report_type: str,
  236. update_info: Optional[Dict] = None,
  237. proxy_url: Optional[str] = None,
  238. mode: str = "daily",
  239. account_label: str = "",
  240. *,
  241. batch_size: int = 4000,
  242. batch_interval: float = 1.0,
  243. msg_type: str = "markdown",
  244. split_content_func: Callable = None,
  245. ) -> bool:
  246. """
  247. 发送到企业微信(支持分批发送,支持 markdown 和 text 两种格式)
  248. Args:
  249. webhook_url: 企业微信 Webhook URL
  250. report_data: 报告数据
  251. report_type: 报告类型
  252. update_info: 更新信息(可选)
  253. proxy_url: 代理 URL(可选)
  254. mode: 报告模式 (daily/current)
  255. account_label: 账号标签(多账号时显示)
  256. batch_size: 批次大小(字节)
  257. batch_interval: 批次发送间隔(秒)
  258. msg_type: 消息类型 (markdown/text)
  259. split_content_func: 内容分批函数
  260. Returns:
  261. bool: 发送是否成功
  262. """
  263. headers = {"Content-Type": "application/json"}
  264. proxies = None
  265. if proxy_url:
  266. proxies = {"http": proxy_url, "https": proxy_url}
  267. # 日志前缀
  268. log_prefix = f"企业微信{account_label}" if account_label else "企业微信"
  269. # 获取消息类型配置(markdown 或 text)
  270. is_text_mode = msg_type.lower() == "text"
  271. if is_text_mode:
  272. print(f"{log_prefix}使用 text 格式(个人微信模式)[{report_type}]")
  273. else:
  274. print(f"{log_prefix}使用 markdown 格式(群机器人模式)[{report_type}]")
  275. # text 模式使用 wework_text,markdown 模式使用 wework
  276. header_format_type = "wework_text" if is_text_mode else "wework"
  277. # 获取分批内容,预留批次头部空间
  278. header_reserve = get_max_batch_header_size(header_format_type)
  279. batches = split_content_func(
  280. report_data, "wework", update_info, max_bytes=batch_size - header_reserve, mode=mode
  281. )
  282. # 统一添加批次头部(已预留空间,不会超限)
  283. batches = add_batch_headers(batches, header_format_type, batch_size)
  284. print(f"{log_prefix}消息分为 {len(batches)} 批次发送 [{report_type}]")
  285. # 逐批发送
  286. for i, batch_content in enumerate(batches, 1):
  287. # 根据消息类型构建 payload
  288. if is_text_mode:
  289. # text 格式:去除 markdown 语法
  290. plain_content = strip_markdown(batch_content)
  291. payload = {"msgtype": "text", "text": {"content": plain_content}}
  292. content_size = len(plain_content.encode("utf-8"))
  293. else:
  294. # markdown 格式:保持原样
  295. payload = {"msgtype": "markdown", "markdown": {"content": batch_content}}
  296. content_size = len(batch_content.encode("utf-8"))
  297. print(
  298. f"发送{log_prefix}第 {i}/{len(batches)} 批次,大小:{content_size} 字节 [{report_type}]"
  299. )
  300. try:
  301. response = requests.post(
  302. webhook_url, headers=headers, json=payload, proxies=proxies, timeout=30
  303. )
  304. if response.status_code == 200:
  305. result = response.json()
  306. if result.get("errcode") == 0:
  307. print(f"{log_prefix}第 {i}/{len(batches)} 批次发送成功 [{report_type}]")
  308. # 批次间间隔
  309. if i < len(batches):
  310. time.sleep(batch_interval)
  311. else:
  312. print(
  313. f"{log_prefix}第 {i}/{len(batches)} 批次发送失败 [{report_type}],错误:{result.get('errmsg')}"
  314. )
  315. return False
  316. else:
  317. print(
  318. f"{log_prefix}第 {i}/{len(batches)} 批次发送失败 [{report_type}],状态码:{response.status_code}"
  319. )
  320. return False
  321. except Exception as e:
  322. print(f"{log_prefix}第 {i}/{len(batches)} 批次发送出错 [{report_type}]:{e}")
  323. return False
  324. print(f"{log_prefix}所有 {len(batches)} 批次发送完成 [{report_type}]")
  325. return True
  326. def send_to_telegram(
  327. bot_token: str,
  328. chat_id: str,
  329. report_data: Dict,
  330. report_type: str,
  331. update_info: Optional[Dict] = None,
  332. proxy_url: Optional[str] = None,
  333. mode: str = "daily",
  334. account_label: str = "",
  335. *,
  336. batch_size: int = 4000,
  337. batch_interval: float = 1.0,
  338. split_content_func: Callable = None,
  339. ) -> bool:
  340. """
  341. 发送到 Telegram(支持分批发送)
  342. Args:
  343. bot_token: Telegram Bot Token
  344. chat_id: Telegram Chat ID
  345. report_data: 报告数据
  346. report_type: 报告类型
  347. update_info: 更新信息(可选)
  348. proxy_url: 代理 URL(可选)
  349. mode: 报告模式 (daily/current)
  350. account_label: 账号标签(多账号时显示)
  351. batch_size: 批次大小(字节)
  352. batch_interval: 批次发送间隔(秒)
  353. split_content_func: 内容分批函数
  354. Returns:
  355. bool: 发送是否成功
  356. """
  357. headers = {"Content-Type": "application/json"}
  358. url = f"https://api.telegram.org/bot{bot_token}/sendMessage"
  359. proxies = None
  360. if proxy_url:
  361. proxies = {"http": proxy_url, "https": proxy_url}
  362. # 日志前缀
  363. log_prefix = f"Telegram{account_label}" if account_label else "Telegram"
  364. # 获取分批内容,预留批次头部空间
  365. header_reserve = get_max_batch_header_size("telegram")
  366. batches = split_content_func(
  367. report_data, "telegram", update_info, max_bytes=batch_size - header_reserve, mode=mode
  368. )
  369. # 统一添加批次头部(已预留空间,不会超限)
  370. batches = add_batch_headers(batches, "telegram", batch_size)
  371. print(f"{log_prefix}消息分为 {len(batches)} 批次发送 [{report_type}]")
  372. # 逐批发送
  373. for i, batch_content in enumerate(batches, 1):
  374. content_size = len(batch_content.encode("utf-8"))
  375. print(
  376. f"发送{log_prefix}第 {i}/{len(batches)} 批次,大小:{content_size} 字节 [{report_type}]"
  377. )
  378. payload = {
  379. "chat_id": chat_id,
  380. "text": batch_content,
  381. "parse_mode": "HTML",
  382. "disable_web_page_preview": True,
  383. }
  384. try:
  385. response = requests.post(
  386. url, headers=headers, json=payload, proxies=proxies, timeout=30
  387. )
  388. if response.status_code == 200:
  389. result = response.json()
  390. if result.get("ok"):
  391. print(f"{log_prefix}第 {i}/{len(batches)} 批次发送成功 [{report_type}]")
  392. # 批次间间隔
  393. if i < len(batches):
  394. time.sleep(batch_interval)
  395. else:
  396. print(
  397. f"{log_prefix}第 {i}/{len(batches)} 批次发送失败 [{report_type}],错误:{result.get('description')}"
  398. )
  399. return False
  400. else:
  401. print(
  402. f"{log_prefix}第 {i}/{len(batches)} 批次发送失败 [{report_type}],状态码:{response.status_code}"
  403. )
  404. return False
  405. except Exception as e:
  406. print(f"{log_prefix}第 {i}/{len(batches)} 批次发送出错 [{report_type}]:{e}")
  407. return False
  408. print(f"{log_prefix}所有 {len(batches)} 批次发送完成 [{report_type}]")
  409. return True
  410. def send_to_email(
  411. from_email: str,
  412. password: str,
  413. to_email: str,
  414. report_type: str,
  415. html_file_path: str,
  416. custom_smtp_server: Optional[str] = None,
  417. custom_smtp_port: Optional[int] = None,
  418. *,
  419. get_time_func: Callable = None,
  420. ) -> bool:
  421. """
  422. 发送邮件通知
  423. Args:
  424. from_email: 发件人邮箱
  425. password: 邮箱密码/授权码
  426. to_email: 收件人邮箱(多个用逗号分隔)
  427. report_type: 报告类型
  428. html_file_path: HTML 报告文件路径
  429. custom_smtp_server: 自定义 SMTP 服务器(可选)
  430. custom_smtp_port: 自定义 SMTP 端口(可选)
  431. get_time_func: 获取当前时间的函数
  432. Returns:
  433. bool: 发送是否成功
  434. """
  435. try:
  436. if not html_file_path or not Path(html_file_path).exists():
  437. print(f"错误:HTML文件不存在或未提供: {html_file_path}")
  438. return False
  439. print(f"使用HTML文件: {html_file_path}")
  440. with open(html_file_path, "r", encoding="utf-8") as f:
  441. html_content = f.read()
  442. domain = from_email.split("@")[-1].lower()
  443. if custom_smtp_server and custom_smtp_port:
  444. # 使用自定义 SMTP 配置
  445. smtp_server = custom_smtp_server
  446. smtp_port = int(custom_smtp_port)
  447. # 根据端口判断加密方式:465=SSL, 587=TLS
  448. if smtp_port == 465:
  449. use_tls = False # SSL 模式(SMTP_SSL)
  450. elif smtp_port == 587:
  451. use_tls = True # TLS 模式(STARTTLS)
  452. else:
  453. # 其他端口优先尝试 TLS(更安全,更广泛支持)
  454. use_tls = True
  455. elif domain in SMTP_CONFIGS:
  456. # 使用预设配置
  457. config = SMTP_CONFIGS[domain]
  458. smtp_server = config["server"]
  459. smtp_port = config["port"]
  460. use_tls = config["encryption"] == "TLS"
  461. else:
  462. print(f"未识别的邮箱服务商: {domain},使用通用 SMTP 配置")
  463. smtp_server = f"smtp.{domain}"
  464. smtp_port = 587
  465. use_tls = True
  466. msg = MIMEMultipart("alternative")
  467. # 严格按照 RFC 标准设置 From header
  468. sender_name = "TrendRadar"
  469. msg["From"] = formataddr((sender_name, from_email))
  470. # 设置收件人
  471. recipients = [addr.strip() for addr in to_email.split(",")]
  472. if len(recipients) == 1:
  473. msg["To"] = recipients[0]
  474. else:
  475. msg["To"] = ", ".join(recipients)
  476. # 设置邮件主题
  477. now = get_time_func() if get_time_func else datetime.now()
  478. subject = f"TrendRadar 热点分析报告 - {report_type} - {now.strftime('%m月%d日 %H:%M')}"
  479. msg["Subject"] = Header(subject, "utf-8")
  480. # 设置其他标准 header
  481. msg["MIME-Version"] = "1.0"
  482. msg["Date"] = formatdate(localtime=True)
  483. msg["Message-ID"] = make_msgid()
  484. # 添加纯文本部分(作为备选)
  485. text_content = f"""
  486. TrendRadar 热点分析报告
  487. ========================
  488. 报告类型:{report_type}
  489. 生成时间:{now.strftime('%Y-%m-%d %H:%M:%S')}
  490. 请使用支持HTML的邮件客户端查看完整报告内容。
  491. """
  492. text_part = MIMEText(text_content, "plain", "utf-8")
  493. msg.attach(text_part)
  494. html_part = MIMEText(html_content, "html", "utf-8")
  495. msg.attach(html_part)
  496. print(f"正在发送邮件到 {to_email}...")
  497. print(f"SMTP 服务器: {smtp_server}:{smtp_port}")
  498. print(f"发件人: {from_email}")
  499. try:
  500. if use_tls:
  501. # TLS 模式
  502. server = smtplib.SMTP(smtp_server, smtp_port, timeout=30)
  503. server.set_debuglevel(0) # 设为1可以查看详细调试信息
  504. server.ehlo()
  505. server.starttls()
  506. server.ehlo()
  507. else:
  508. # SSL 模式
  509. server = smtplib.SMTP_SSL(smtp_server, smtp_port, timeout=30)
  510. server.set_debuglevel(0)
  511. server.ehlo()
  512. # 登录
  513. server.login(from_email, password)
  514. # 发送邮件
  515. server.send_message(msg)
  516. server.quit()
  517. print(f"邮件发送成功 [{report_type}] -> {to_email}")
  518. return True
  519. except smtplib.SMTPServerDisconnected:
  520. print("邮件发送失败:服务器意外断开连接,请检查网络或稍后重试")
  521. return False
  522. except smtplib.SMTPAuthenticationError as e:
  523. print("邮件发送失败:认证错误,请检查邮箱和密码/授权码")
  524. print(f"详细错误: {str(e)}")
  525. return False
  526. except smtplib.SMTPRecipientsRefused as e:
  527. print(f"邮件发送失败:收件人地址被拒绝 {e}")
  528. return False
  529. except smtplib.SMTPSenderRefused as e:
  530. print(f"邮件发送失败:发件人地址被拒绝 {e}")
  531. return False
  532. except smtplib.SMTPDataError as e:
  533. print(f"邮件发送失败:邮件数据错误 {e}")
  534. return False
  535. except smtplib.SMTPConnectError as e:
  536. print(f"邮件发送失败:无法连接到 SMTP 服务器 {smtp_server}:{smtp_port}")
  537. print(f"详细错误: {str(e)}")
  538. return False
  539. except Exception as e:
  540. print(f"邮件发送失败 [{report_type}]:{e}")
  541. import traceback
  542. traceback.print_exc()
  543. return False
  544. def send_to_ntfy(
  545. server_url: str,
  546. topic: str,
  547. token: Optional[str],
  548. report_data: Dict,
  549. report_type: str,
  550. update_info: Optional[Dict] = None,
  551. proxy_url: Optional[str] = None,
  552. mode: str = "daily",
  553. account_label: str = "",
  554. *,
  555. batch_size: int = 3800,
  556. split_content_func: Callable = None,
  557. ) -> bool:
  558. """
  559. 发送到 ntfy(支持分批发送,严格遵守4KB限制)
  560. Args:
  561. server_url: ntfy 服务器 URL
  562. topic: ntfy 主题
  563. token: ntfy 访问令牌(可选)
  564. report_data: 报告数据
  565. report_type: 报告类型
  566. update_info: 更新信息(可选)
  567. proxy_url: 代理 URL(可选)
  568. mode: 报告模式 (daily/current)
  569. account_label: 账号标签(多账号时显示)
  570. batch_size: 批次大小(字节)
  571. split_content_func: 内容分批函数
  572. Returns:
  573. bool: 发送是否成功
  574. """
  575. # 日志前缀
  576. log_prefix = f"ntfy{account_label}" if account_label else "ntfy"
  577. # 避免 HTTP header 编码问题
  578. report_type_en_map = {
  579. "当日汇总": "Daily Summary",
  580. "当前榜单汇总": "Current Ranking",
  581. "增量更新": "Incremental Update",
  582. "实时增量": "Realtime Incremental",
  583. "实时当前榜单": "Realtime Current Ranking",
  584. }
  585. report_type_en = report_type_en_map.get(report_type, "News Report")
  586. headers = {
  587. "Content-Type": "text/plain; charset=utf-8",
  588. "Markdown": "yes",
  589. "Title": report_type_en,
  590. "Priority": "default",
  591. "Tags": "news",
  592. }
  593. if token:
  594. headers["Authorization"] = f"Bearer {token}"
  595. # 构建完整URL,确保格式正确
  596. base_url = server_url.rstrip("/")
  597. if not base_url.startswith(("http://", "https://")):
  598. base_url = f"https://{base_url}"
  599. url = f"{base_url}/{topic}"
  600. proxies = None
  601. if proxy_url:
  602. proxies = {"http": proxy_url, "https": proxy_url}
  603. # 获取分批内容,预留批次头部空间
  604. header_reserve = get_max_batch_header_size("ntfy")
  605. batches = split_content_func(
  606. report_data, "ntfy", update_info, max_bytes=batch_size - header_reserve, mode=mode
  607. )
  608. # 统一添加批次头部(已预留空间,不会超限)
  609. batches = add_batch_headers(batches, "ntfy", batch_size)
  610. total_batches = len(batches)
  611. print(f"{log_prefix}消息分为 {total_batches} 批次发送 [{report_type}]")
  612. # 反转批次顺序,使得在ntfy客户端显示时顺序正确
  613. # ntfy显示最新消息在上面,所以我们从最后一批开始推送
  614. reversed_batches = list(reversed(batches))
  615. print(f"{log_prefix}将按反向顺序推送(最后批次先推送),确保客户端显示顺序正确")
  616. # 逐批发送(反向顺序)
  617. success_count = 0
  618. for idx, batch_content in enumerate(reversed_batches, 1):
  619. # 计算正确的批次编号(用户视角的编号)
  620. actual_batch_num = total_batches - idx + 1
  621. content_size = len(batch_content.encode("utf-8"))
  622. print(
  623. f"发送{log_prefix}第 {actual_batch_num}/{total_batches} 批次(推送顺序: {idx}/{total_batches}),大小:{content_size} 字节 [{report_type}]"
  624. )
  625. # 检查消息大小,确保不超过4KB
  626. if content_size > 4096:
  627. print(f"警告:{log_prefix}第 {actual_batch_num} 批次消息过大({content_size} 字节),可能被拒绝")
  628. # 更新 headers 的批次标识
  629. current_headers = headers.copy()
  630. if total_batches > 1:
  631. current_headers["Title"] = f"{report_type_en} ({actual_batch_num}/{total_batches})"
  632. try:
  633. response = requests.post(
  634. url,
  635. headers=current_headers,
  636. data=batch_content.encode("utf-8"),
  637. proxies=proxies,
  638. timeout=30,
  639. )
  640. if response.status_code == 200:
  641. print(f"{log_prefix}第 {actual_batch_num}/{total_batches} 批次发送成功 [{report_type}]")
  642. success_count += 1
  643. if idx < total_batches:
  644. # 公共服务器建议 2-3 秒,自托管可以更短
  645. interval = 2 if "ntfy.sh" in server_url else 1
  646. time.sleep(interval)
  647. elif response.status_code == 429:
  648. print(
  649. f"{log_prefix}第 {actual_batch_num}/{total_batches} 批次速率限制 [{report_type}],等待后重试"
  650. )
  651. time.sleep(10) # 等待10秒后重试
  652. # 重试一次
  653. retry_response = requests.post(
  654. url,
  655. headers=current_headers,
  656. data=batch_content.encode("utf-8"),
  657. proxies=proxies,
  658. timeout=30,
  659. )
  660. if retry_response.status_code == 200:
  661. print(f"{log_prefix}第 {actual_batch_num}/{total_batches} 批次重试成功 [{report_type}]")
  662. success_count += 1
  663. else:
  664. print(
  665. f"{log_prefix}第 {actual_batch_num}/{total_batches} 批次重试失败,状态码:{retry_response.status_code}"
  666. )
  667. elif response.status_code == 413:
  668. print(
  669. f"{log_prefix}第 {actual_batch_num}/{total_batches} 批次消息过大被拒绝 [{report_type}],消息大小:{content_size} 字节"
  670. )
  671. else:
  672. print(
  673. f"{log_prefix}第 {actual_batch_num}/{total_batches} 批次发送失败 [{report_type}],状态码:{response.status_code}"
  674. )
  675. try:
  676. print(f"错误详情:{response.text}")
  677. except:
  678. pass
  679. except requests.exceptions.ConnectTimeout:
  680. print(f"{log_prefix}第 {actual_batch_num}/{total_batches} 批次连接超时 [{report_type}]")
  681. except requests.exceptions.ReadTimeout:
  682. print(f"{log_prefix}第 {actual_batch_num}/{total_batches} 批次读取超时 [{report_type}]")
  683. except requests.exceptions.ConnectionError as e:
  684. print(f"{log_prefix}第 {actual_batch_num}/{total_batches} 批次连接错误 [{report_type}]:{e}")
  685. except Exception as e:
  686. print(f"{log_prefix}第 {actual_batch_num}/{total_batches} 批次发送异常 [{report_type}]:{e}")
  687. # 判断整体发送是否成功
  688. if success_count == total_batches:
  689. print(f"{log_prefix}所有 {total_batches} 批次发送完成 [{report_type}]")
  690. return True
  691. elif success_count > 0:
  692. print(f"{log_prefix}部分发送成功:{success_count}/{total_batches} 批次 [{report_type}]")
  693. return True # 部分成功也视为成功
  694. else:
  695. print(f"{log_prefix}发送完全失败 [{report_type}]")
  696. return False
  697. def send_to_bark(
  698. bark_url: str,
  699. report_data: Dict,
  700. report_type: str,
  701. update_info: Optional[Dict] = None,
  702. proxy_url: Optional[str] = None,
  703. mode: str = "daily",
  704. account_label: str = "",
  705. *,
  706. batch_size: int = 3600,
  707. batch_interval: float = 1.0,
  708. split_content_func: Callable = None,
  709. ) -> bool:
  710. """
  711. 发送到 Bark(支持分批发送,使用 markdown 格式)
  712. Args:
  713. bark_url: Bark URL(包含 device_key)
  714. report_data: 报告数据
  715. report_type: 报告类型
  716. update_info: 更新信息(可选)
  717. proxy_url: 代理 URL(可选)
  718. mode: 报告模式 (daily/current)
  719. account_label: 账号标签(多账号时显示)
  720. batch_size: 批次大小(字节)
  721. batch_interval: 批次发送间隔(秒)
  722. split_content_func: 内容分批函数
  723. Returns:
  724. bool: 发送是否成功
  725. """
  726. # 日志前缀
  727. log_prefix = f"Bark{account_label}" if account_label else "Bark"
  728. proxies = None
  729. if proxy_url:
  730. proxies = {"http": proxy_url, "https": proxy_url}
  731. # 解析 Bark URL,提取 device_key 和 API 端点
  732. # Bark URL 格式: https://api.day.app/device_key 或 https://bark.day.app/device_key
  733. parsed_url = urlparse(bark_url)
  734. device_key = parsed_url.path.strip('/').split('/')[0] if parsed_url.path else None
  735. if not device_key:
  736. print(f"{log_prefix} URL 格式错误,无法提取 device_key: {bark_url}")
  737. return False
  738. # 构建正确的 API 端点
  739. api_endpoint = f"{parsed_url.scheme}://{parsed_url.netloc}/push"
  740. # 获取分批内容,预留批次头部空间
  741. header_reserve = get_max_batch_header_size("bark")
  742. batches = split_content_func(
  743. report_data, "bark", update_info, max_bytes=batch_size - header_reserve, mode=mode
  744. )
  745. # 统一添加批次头部(已预留空间,不会超限)
  746. batches = add_batch_headers(batches, "bark", batch_size)
  747. total_batches = len(batches)
  748. print(f"{log_prefix}消息分为 {total_batches} 批次发送 [{report_type}]")
  749. # 反转批次顺序,使得在Bark客户端显示时顺序正确
  750. # Bark显示最新消息在上面,所以我们从最后一批开始推送
  751. reversed_batches = list(reversed(batches))
  752. print(f"{log_prefix}将按反向顺序推送(最后批次先推送),确保客户端显示顺序正确")
  753. # 逐批发送(反向顺序)
  754. success_count = 0
  755. for idx, batch_content in enumerate(reversed_batches, 1):
  756. # 计算正确的批次编号(用户视角的编号)
  757. actual_batch_num = total_batches - idx + 1
  758. content_size = len(batch_content.encode("utf-8"))
  759. print(
  760. f"发送{log_prefix}第 {actual_batch_num}/{total_batches} 批次(推送顺序: {idx}/{total_batches}),大小:{content_size} 字节 [{report_type}]"
  761. )
  762. # 检查消息大小(Bark使用APNs,限制4KB)
  763. if content_size > 4096:
  764. print(
  765. f"警告:{log_prefix}第 {actual_batch_num}/{total_batches} 批次消息过大({content_size} 字节),可能被拒绝"
  766. )
  767. # 构建JSON payload
  768. payload = {
  769. "title": report_type,
  770. "markdown": batch_content,
  771. "device_key": device_key,
  772. "sound": "default",
  773. "group": "TrendRadar",
  774. "action": "none", # 点击推送跳到 APP 不弹出弹框,方便阅读
  775. }
  776. try:
  777. response = requests.post(
  778. api_endpoint,
  779. json=payload,
  780. proxies=proxies,
  781. timeout=30,
  782. )
  783. if response.status_code == 200:
  784. result = response.json()
  785. if result.get("code") == 200:
  786. print(f"{log_prefix}第 {actual_batch_num}/{total_batches} 批次发送成功 [{report_type}]")
  787. success_count += 1
  788. # 批次间间隔
  789. if idx < total_batches:
  790. time.sleep(batch_interval)
  791. else:
  792. print(
  793. f"{log_prefix}第 {actual_batch_num}/{total_batches} 批次发送失败 [{report_type}],错误:{result.get('message', '未知错误')}"
  794. )
  795. else:
  796. print(
  797. f"{log_prefix}第 {actual_batch_num}/{total_batches} 批次发送失败 [{report_type}],状态码:{response.status_code}"
  798. )
  799. try:
  800. print(f"错误详情:{response.text}")
  801. except:
  802. pass
  803. except requests.exceptions.ConnectTimeout:
  804. print(f"{log_prefix}第 {actual_batch_num}/{total_batches} 批次连接超时 [{report_type}]")
  805. except requests.exceptions.ReadTimeout:
  806. print(f"{log_prefix}第 {actual_batch_num}/{total_batches} 批次读取超时 [{report_type}]")
  807. except requests.exceptions.ConnectionError as e:
  808. print(f"{log_prefix}第 {actual_batch_num}/{total_batches} 批次连接错误 [{report_type}]:{e}")
  809. except Exception as e:
  810. print(f"{log_prefix}第 {actual_batch_num}/{total_batches} 批次发送异常 [{report_type}]:{e}")
  811. # 判断整体发送是否成功
  812. if success_count == total_batches:
  813. print(f"{log_prefix}所有 {total_batches} 批次发送完成 [{report_type}]")
  814. return True
  815. elif success_count > 0:
  816. print(f"{log_prefix}部分发送成功:{success_count}/{total_batches} 批次 [{report_type}]")
  817. return True # 部分成功也视为成功
  818. else:
  819. print(f"{log_prefix}发送完全失败 [{report_type}]")
  820. return False
  821. def send_to_slack(
  822. webhook_url: str,
  823. report_data: Dict,
  824. report_type: str,
  825. update_info: Optional[Dict] = None,
  826. proxy_url: Optional[str] = None,
  827. mode: str = "daily",
  828. account_label: str = "",
  829. *,
  830. batch_size: int = 4000,
  831. batch_interval: float = 1.0,
  832. split_content_func: Callable = None,
  833. ) -> bool:
  834. """
  835. 发送到 Slack(支持分批发送,使用 mrkdwn 格式)
  836. Args:
  837. webhook_url: Slack Webhook URL
  838. report_data: 报告数据
  839. report_type: 报告类型
  840. update_info: 更新信息(可选)
  841. proxy_url: 代理 URL(可选)
  842. mode: 报告模式 (daily/current)
  843. account_label: 账号标签(多账号时显示)
  844. batch_size: 批次大小(字节)
  845. batch_interval: 批次发送间隔(秒)
  846. split_content_func: 内容分批函数
  847. Returns:
  848. bool: 发送是否成功
  849. """
  850. headers = {"Content-Type": "application/json"}
  851. proxies = None
  852. if proxy_url:
  853. proxies = {"http": proxy_url, "https": proxy_url}
  854. # 日志前缀
  855. log_prefix = f"Slack{account_label}" if account_label else "Slack"
  856. # 获取分批内容,预留批次头部空间
  857. header_reserve = get_max_batch_header_size("slack")
  858. batches = split_content_func(
  859. report_data, "slack", update_info, max_bytes=batch_size - header_reserve, mode=mode
  860. )
  861. # 统一添加批次头部(已预留空间,不会超限)
  862. batches = add_batch_headers(batches, "slack", batch_size)
  863. print(f"{log_prefix}消息分为 {len(batches)} 批次发送 [{report_type}]")
  864. # 逐批发送
  865. for i, batch_content in enumerate(batches, 1):
  866. # 转换 Markdown 到 mrkdwn 格式
  867. mrkdwn_content = convert_markdown_to_mrkdwn(batch_content)
  868. content_size = len(mrkdwn_content.encode("utf-8"))
  869. print(
  870. f"发送{log_prefix}第 {i}/{len(batches)} 批次,大小:{content_size} 字节 [{report_type}]"
  871. )
  872. # 构建 Slack payload(使用简单的 text 字段,支持 mrkdwn)
  873. payload = {"text": mrkdwn_content}
  874. try:
  875. response = requests.post(
  876. webhook_url, headers=headers, json=payload, proxies=proxies, timeout=30
  877. )
  878. # Slack Incoming Webhooks 成功时返回 "ok" 文本
  879. if response.status_code == 200 and response.text == "ok":
  880. print(f"{log_prefix}第 {i}/{len(batches)} 批次发送成功 [{report_type}]")
  881. # 批次间间隔
  882. if i < len(batches):
  883. time.sleep(batch_interval)
  884. else:
  885. error_msg = response.text if response.text else f"状态码:{response.status_code}"
  886. print(
  887. f"{log_prefix}第 {i}/{len(batches)} 批次发送失败 [{report_type}],错误:{error_msg}"
  888. )
  889. return False
  890. except Exception as e:
  891. print(f"{log_prefix}第 {i}/{len(batches)} 批次发送出错 [{report_type}]:{e}")
  892. return False
  893. print(f"{log_prefix}所有 {len(batches)} 批次发送完成 [{report_type}]")
  894. return True