senders.py 40 KB

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