senders.py 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390
  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. import json
  18. from datetime import datetime
  19. from email.header import Header
  20. from email.mime.multipart import MIMEMultipart
  21. from email.mime.text import MIMEText
  22. from email.utils import formataddr, formatdate, make_msgid
  23. from pathlib import Path
  24. from typing import Any, Callable, Dict, Optional
  25. from urllib.parse import urlparse
  26. import requests
  27. from .batch import add_batch_headers, get_max_batch_header_size
  28. from .formatters import convert_markdown_to_mrkdwn, strip_markdown
  29. def _render_ai_analysis(ai_analysis: Any, channel: str) -> str:
  30. """渲染 AI 分析内容为指定渠道格式"""
  31. if not ai_analysis:
  32. return ""
  33. try:
  34. from trendradar.ai.formatter import get_ai_analysis_renderer
  35. renderer = get_ai_analysis_renderer(channel)
  36. return renderer(ai_analysis)
  37. except ImportError:
  38. return ""
  39. # === SMTP 邮件配置 ===
  40. SMTP_CONFIGS = {
  41. # Gmail(使用 STARTTLS)
  42. "gmail.com": {"server": "smtp.gmail.com", "port": 587, "encryption": "TLS"},
  43. # QQ邮箱(使用 SSL,更稳定)
  44. "qq.com": {"server": "smtp.qq.com", "port": 465, "encryption": "SSL"},
  45. # Outlook(使用 STARTTLS)
  46. "outlook.com": {"server": "smtp-mail.outlook.com", "port": 587, "encryption": "TLS"},
  47. "hotmail.com": {"server": "smtp-mail.outlook.com", "port": 587, "encryption": "TLS"},
  48. "live.com": {"server": "smtp-mail.outlook.com", "port": 587, "encryption": "TLS"},
  49. # 网易邮箱(使用 SSL,更稳定)
  50. "163.com": {"server": "smtp.163.com", "port": 465, "encryption": "SSL"},
  51. "126.com": {"server": "smtp.126.com", "port": 465, "encryption": "SSL"},
  52. # 新浪邮箱(使用 SSL)
  53. "sina.com": {"server": "smtp.sina.com", "port": 465, "encryption": "SSL"},
  54. # 搜狐邮箱(使用 SSL)
  55. "sohu.com": {"server": "smtp.sohu.com", "port": 465, "encryption": "SSL"},
  56. # 天翼邮箱(使用 SSL)
  57. "189.cn": {"server": "smtp.189.cn", "port": 465, "encryption": "SSL"},
  58. # 阿里云邮箱(使用 TLS)
  59. "aliyun.com": {"server": "smtp.aliyun.com", "port": 465, "encryption": "TLS"},
  60. # Yandex邮箱(使用 TLS)
  61. "yandex.com": {"server": "smtp.yandex.com", "port": 465, "encryption": "TLS"},
  62. # iCloud邮箱(使用 SSL)
  63. "icloud.com": {"server": "smtp.mail.me.com", "port": 587, "encryption": "SSL"},
  64. }
  65. def send_to_feishu(
  66. webhook_url: str,
  67. report_data: Dict,
  68. report_type: str,
  69. update_info: Optional[Dict] = None,
  70. proxy_url: Optional[str] = None,
  71. mode: str = "daily",
  72. account_label: str = "",
  73. *,
  74. batch_size: int = 29000,
  75. batch_interval: float = 1.0,
  76. split_content_func: Callable = None,
  77. get_time_func: Callable = None,
  78. rss_items: Optional[list] = None,
  79. rss_new_items: Optional[list] = None,
  80. ai_analysis: Any = None,
  81. display_regions: Optional[Dict] = None,
  82. standalone_data: Optional[Dict] = None,
  83. ) -> bool:
  84. """
  85. 发送到飞书(支持分批发送,支持热榜+RSS合并+独立展示区)
  86. Args:
  87. webhook_url: 飞书 Webhook URL
  88. report_data: 报告数据
  89. report_type: 报告类型
  90. update_info: 更新信息(可选)
  91. proxy_url: 代理 URL(可选)
  92. mode: 报告模式 (daily/current)
  93. account_label: 账号标签(多账号时显示)
  94. batch_size: 批次大小(字节)
  95. batch_interval: 批次发送间隔(秒)
  96. split_content_func: 内容分批函数
  97. get_time_func: 获取当前时间的函数
  98. rss_items: RSS 统计条目列表(可选,用于合并推送)
  99. rss_new_items: RSS 新增条目列表(可选,用于新增区块)
  100. Returns:
  101. bool: 发送是否成功
  102. """
  103. headers = {"Content-Type": "application/json"}
  104. proxies = None
  105. if proxy_url:
  106. proxies = {"http": proxy_url, "https": proxy_url}
  107. # 日志前缀
  108. log_prefix = f"飞书{account_label}" if account_label else "飞书"
  109. # 渲染 AI 分析内容(如果有)
  110. ai_content = None
  111. ai_stats = None
  112. if ai_analysis:
  113. ai_content = _render_ai_analysis(ai_analysis, "feishu")
  114. # 提取 AI 分析统计数据(只要 AI 分析成功就显示)
  115. if getattr(ai_analysis, "success", False):
  116. ai_stats = {
  117. "total_news": getattr(ai_analysis, "total_news", 0),
  118. "analyzed_news": getattr(ai_analysis, "analyzed_news", 0),
  119. "max_news_limit": getattr(ai_analysis, "max_news_limit", 0),
  120. "hotlist_count": getattr(ai_analysis, "hotlist_count", 0),
  121. "rss_count": getattr(ai_analysis, "rss_count", 0),
  122. "ai_mode": getattr(ai_analysis, "ai_mode", ""),
  123. }
  124. # 预留批次头部空间,避免添加头部后超限
  125. header_reserve = get_max_batch_header_size("feishu")
  126. batches = split_content_func(
  127. report_data,
  128. "feishu",
  129. update_info,
  130. max_bytes=batch_size - header_reserve,
  131. mode=mode,
  132. rss_items=rss_items,
  133. rss_new_items=rss_new_items,
  134. ai_content=ai_content,
  135. standalone_data=standalone_data,
  136. ai_stats=ai_stats,
  137. report_type=report_type,
  138. )
  139. # 统一添加批次头部(已预留空间,不会超限)
  140. batches = add_batch_headers(batches, "feishu", batch_size)
  141. print(f"{log_prefix}消息分为 {len(batches)} 批次发送 [{report_type}]")
  142. # 逐批发送
  143. for i, batch_content in enumerate(batches, 1):
  144. content_size = len(batch_content.encode("utf-8"))
  145. print(
  146. f"发送{log_prefix}第 {i}/{len(batches)} 批次,大小:{content_size} 字节 [{report_type}]"
  147. )
  148. # 飞书 webhook 只显示 content.text,所有信息都整合到 text 中
  149. payload = {
  150. "msg_type": "interactive",
  151. "content": {
  152. "text": batch_content,
  153. },
  154. }
  155. try:
  156. response = requests.post(
  157. webhook_url, headers=headers, json=payload, proxies=proxies, timeout=30
  158. )
  159. if response.status_code == 200:
  160. result = response.json()
  161. # 检查飞书的响应状态
  162. if result.get("StatusCode") == 0 or result.get("code") == 0:
  163. print(f"{log_prefix}第 {i}/{len(batches)} 批次发送成功 [{report_type}]")
  164. # 批次间间隔
  165. if i < len(batches):
  166. time.sleep(batch_interval)
  167. else:
  168. error_msg = result.get("msg") or result.get("StatusMessage", "未知错误")
  169. print(
  170. f"{log_prefix}第 {i}/{len(batches)} 批次发送失败 [{report_type}],错误:{error_msg}"
  171. )
  172. return False
  173. else:
  174. print(
  175. f"{log_prefix}第 {i}/{len(batches)} 批次发送失败 [{report_type}],状态码:{response.status_code}"
  176. )
  177. return False
  178. except Exception as e:
  179. print(f"{log_prefix}第 {i}/{len(batches)} 批次发送出错 [{report_type}]:{e}")
  180. return False
  181. print(f"{log_prefix}所有 {len(batches)} 批次发送完成 [{report_type}]")
  182. return True
  183. def send_to_dingtalk(
  184. webhook_url: str,
  185. report_data: Dict,
  186. report_type: str,
  187. update_info: Optional[Dict] = None,
  188. proxy_url: Optional[str] = None,
  189. mode: str = "daily",
  190. account_label: str = "",
  191. *,
  192. batch_size: int = 20000,
  193. batch_interval: float = 1.0,
  194. split_content_func: Callable = None,
  195. rss_items: Optional[list] = None,
  196. rss_new_items: Optional[list] = None,
  197. ai_analysis: Any = None,
  198. display_regions: Optional[Dict] = None,
  199. standalone_data: Optional[Dict] = None,
  200. ) -> bool:
  201. """
  202. 发送到钉钉(支持分批发送,支持热榜+RSS合并+独立展示区)
  203. Args:
  204. webhook_url: 钉钉 Webhook URL
  205. report_data: 报告数据
  206. report_type: 报告类型
  207. update_info: 更新信息(可选)
  208. proxy_url: 代理 URL(可选)
  209. mode: 报告模式 (daily/current)
  210. account_label: 账号标签(多账号时显示)
  211. batch_size: 批次大小(字节)
  212. batch_interval: 批次发送间隔(秒)
  213. split_content_func: 内容分批函数
  214. rss_items: RSS 统计条目列表(可选,用于合并推送)
  215. rss_new_items: RSS 新增条目列表(可选,用于新增区块)
  216. Returns:
  217. bool: 发送是否成功
  218. """
  219. headers = {"Content-Type": "application/json"}
  220. proxies = None
  221. if proxy_url:
  222. proxies = {"http": proxy_url, "https": proxy_url}
  223. # 日志前缀
  224. log_prefix = f"钉钉{account_label}" if account_label else "钉钉"
  225. # 渲染 AI 分析内容(如果有)
  226. ai_content = None
  227. ai_stats = None
  228. if ai_analysis:
  229. ai_content = _render_ai_analysis(ai_analysis, "dingtalk")
  230. # 提取 AI 分析统计数据(只要 AI 分析成功就显示)
  231. if getattr(ai_analysis, "success", False):
  232. ai_stats = {
  233. "total_news": getattr(ai_analysis, "total_news", 0),
  234. "analyzed_news": getattr(ai_analysis, "analyzed_news", 0),
  235. "max_news_limit": getattr(ai_analysis, "max_news_limit", 0),
  236. "hotlist_count": getattr(ai_analysis, "hotlist_count", 0),
  237. "rss_count": getattr(ai_analysis, "rss_count", 0),
  238. "ai_mode": getattr(ai_analysis, "ai_mode", ""),
  239. }
  240. # 预留批次头部空间,避免添加头部后超限
  241. header_reserve = get_max_batch_header_size("dingtalk")
  242. batches = split_content_func(
  243. report_data,
  244. "dingtalk",
  245. update_info,
  246. max_bytes=batch_size - header_reserve,
  247. mode=mode,
  248. rss_items=rss_items,
  249. rss_new_items=rss_new_items,
  250. ai_content=ai_content,
  251. standalone_data=standalone_data,
  252. ai_stats=ai_stats,
  253. report_type=report_type,
  254. )
  255. # 统一添加批次头部(已预留空间,不会超限)
  256. batches = add_batch_headers(batches, "dingtalk", batch_size)
  257. print(f"{log_prefix}消息分为 {len(batches)} 批次发送 [{report_type}]")
  258. # 逐批发送
  259. for i, batch_content in enumerate(batches, 1):
  260. content_size = len(batch_content.encode("utf-8"))
  261. print(
  262. f"发送{log_prefix}第 {i}/{len(batches)} 批次,大小:{content_size} 字节 [{report_type}]"
  263. )
  264. payload = {
  265. "msgtype": "markdown",
  266. "markdown": {
  267. "title": f"TrendRadar 热点分析报告 - {report_type}",
  268. "text": batch_content,
  269. },
  270. }
  271. try:
  272. response = requests.post(
  273. webhook_url, headers=headers, json=payload, proxies=proxies, timeout=30
  274. )
  275. if response.status_code == 200:
  276. result = response.json()
  277. if result.get("errcode") == 0:
  278. print(f"{log_prefix}第 {i}/{len(batches)} 批次发送成功 [{report_type}]")
  279. # 批次间间隔
  280. if i < len(batches):
  281. time.sleep(batch_interval)
  282. else:
  283. print(
  284. f"{log_prefix}第 {i}/{len(batches)} 批次发送失败 [{report_type}],错误:{result.get('errmsg')}"
  285. )
  286. return False
  287. else:
  288. print(
  289. f"{log_prefix}第 {i}/{len(batches)} 批次发送失败 [{report_type}],状态码:{response.status_code}"
  290. )
  291. return False
  292. except Exception as e:
  293. print(f"{log_prefix}第 {i}/{len(batches)} 批次发送出错 [{report_type}]:{e}")
  294. return False
  295. print(f"{log_prefix}所有 {len(batches)} 批次发送完成 [{report_type}]")
  296. return True
  297. def send_to_wework(
  298. webhook_url: str,
  299. report_data: Dict,
  300. report_type: str,
  301. update_info: Optional[Dict] = None,
  302. proxy_url: Optional[str] = None,
  303. mode: str = "daily",
  304. account_label: str = "",
  305. *,
  306. batch_size: int = 4000,
  307. batch_interval: float = 1.0,
  308. msg_type: str = "markdown",
  309. split_content_func: Callable = None,
  310. rss_items: Optional[list] = None,
  311. rss_new_items: Optional[list] = None,
  312. ai_analysis: Any = None,
  313. display_regions: Optional[Dict] = None,
  314. standalone_data: Optional[Dict] = None,
  315. ) -> bool:
  316. """
  317. 发送到企业微信(支持分批发送,支持 markdown 和 text 两种格式,支持热榜+RSS合并+独立展示区)
  318. Args:
  319. webhook_url: 企业微信 Webhook URL
  320. report_data: 报告数据
  321. report_type: 报告类型
  322. update_info: 更新信息(可选)
  323. proxy_url: 代理 URL(可选)
  324. mode: 报告模式 (daily/current)
  325. account_label: 账号标签(多账号时显示)
  326. batch_size: 批次大小(字节)
  327. batch_interval: 批次发送间隔(秒)
  328. msg_type: 消息类型 (markdown/text)
  329. split_content_func: 内容分批函数
  330. rss_items: RSS 统计条目列表(可选,用于合并推送)
  331. rss_new_items: RSS 新增条目列表(可选,用于新增区块)
  332. Returns:
  333. bool: 发送是否成功
  334. """
  335. headers = {"Content-Type": "application/json"}
  336. proxies = None
  337. if proxy_url:
  338. proxies = {"http": proxy_url, "https": proxy_url}
  339. # 日志前缀
  340. log_prefix = f"企业微信{account_label}" if account_label else "企业微信"
  341. # 获取消息类型配置(markdown 或 text)
  342. is_text_mode = msg_type.lower() == "text"
  343. if is_text_mode:
  344. print(f"{log_prefix}使用 text 格式(个人微信模式)[{report_type}]")
  345. else:
  346. print(f"{log_prefix}使用 markdown 格式(群机器人模式)[{report_type}]")
  347. # text 模式使用 wework_text,markdown 模式使用 wework
  348. header_format_type = "wework_text" if is_text_mode else "wework"
  349. # 渲染 AI 分析内容(如果有)
  350. ai_content = None
  351. ai_stats = None
  352. if ai_analysis:
  353. ai_content = _render_ai_analysis(ai_analysis, "wework")
  354. # 提取 AI 分析统计数据(只要 AI 分析成功就显示)
  355. if getattr(ai_analysis, "success", False):
  356. ai_stats = {
  357. "total_news": getattr(ai_analysis, "total_news", 0),
  358. "analyzed_news": getattr(ai_analysis, "analyzed_news", 0),
  359. "max_news_limit": getattr(ai_analysis, "max_news_limit", 0),
  360. "hotlist_count": getattr(ai_analysis, "hotlist_count", 0),
  361. "rss_count": getattr(ai_analysis, "rss_count", 0),
  362. "ai_mode": getattr(ai_analysis, "ai_mode", ""),
  363. }
  364. # 获取分批内容,预留批次头部空间
  365. header_reserve = get_max_batch_header_size(header_format_type)
  366. batches = split_content_func(
  367. report_data, "wework", update_info, max_bytes=batch_size - header_reserve, mode=mode,
  368. rss_items=rss_items,
  369. rss_new_items=rss_new_items,
  370. ai_content=ai_content,
  371. standalone_data=standalone_data,
  372. ai_stats=ai_stats,
  373. report_type=report_type,
  374. )
  375. # 统一添加批次头部(已预留空间,不会超限)
  376. batches = add_batch_headers(batches, header_format_type, batch_size)
  377. print(f"{log_prefix}消息分为 {len(batches)} 批次发送 [{report_type}]")
  378. # 逐批发送
  379. for i, batch_content in enumerate(batches, 1):
  380. # 根据消息类型构建 payload
  381. if is_text_mode:
  382. # text 格式:去除 markdown 语法
  383. plain_content = strip_markdown(batch_content)
  384. payload = {"msgtype": "text", "text": {"content": plain_content}}
  385. content_size = len(plain_content.encode("utf-8"))
  386. else:
  387. # markdown 格式:保持原样
  388. payload = {"msgtype": "markdown", "markdown": {"content": batch_content}}
  389. content_size = len(batch_content.encode("utf-8"))
  390. print(
  391. f"发送{log_prefix}第 {i}/{len(batches)} 批次,大小:{content_size} 字节 [{report_type}]"
  392. )
  393. try:
  394. response = requests.post(
  395. webhook_url, headers=headers, json=payload, proxies=proxies, timeout=30
  396. )
  397. if response.status_code == 200:
  398. result = response.json()
  399. if result.get("errcode") == 0:
  400. print(f"{log_prefix}第 {i}/{len(batches)} 批次发送成功 [{report_type}]")
  401. # 批次间间隔
  402. if i < len(batches):
  403. time.sleep(batch_interval)
  404. else:
  405. print(
  406. f"{log_prefix}第 {i}/{len(batches)} 批次发送失败 [{report_type}],错误:{result.get('errmsg')}"
  407. )
  408. return False
  409. else:
  410. print(
  411. f"{log_prefix}第 {i}/{len(batches)} 批次发送失败 [{report_type}],状态码:{response.status_code}"
  412. )
  413. return False
  414. except Exception as e:
  415. print(f"{log_prefix}第 {i}/{len(batches)} 批次发送出错 [{report_type}]:{e}")
  416. return False
  417. print(f"{log_prefix}所有 {len(batches)} 批次发送完成 [{report_type}]")
  418. return True
  419. def send_to_telegram(
  420. bot_token: str,
  421. chat_id: str,
  422. report_data: Dict,
  423. report_type: str,
  424. update_info: Optional[Dict] = None,
  425. proxy_url: Optional[str] = None,
  426. mode: str = "daily",
  427. account_label: str = "",
  428. *,
  429. batch_size: int = 4000,
  430. batch_interval: float = 1.0,
  431. split_content_func: Callable = None,
  432. rss_items: Optional[list] = None,
  433. rss_new_items: Optional[list] = None,
  434. ai_analysis: Any = None,
  435. display_regions: Optional[Dict] = None,
  436. standalone_data: Optional[Dict] = None,
  437. ) -> bool:
  438. """
  439. 发送到 Telegram(支持分批发送,支持热榜+RSS合并+独立展示区)
  440. Args:
  441. bot_token: Telegram Bot Token
  442. chat_id: Telegram Chat ID
  443. report_data: 报告数据
  444. report_type: 报告类型
  445. update_info: 更新信息(可选)
  446. proxy_url: 代理 URL(可选)
  447. mode: 报告模式 (daily/current)
  448. account_label: 账号标签(多账号时显示)
  449. batch_size: 批次大小(字节)
  450. batch_interval: 批次发送间隔(秒)
  451. split_content_func: 内容分批函数
  452. rss_items: RSS 统计条目列表(可选,用于合并推送)
  453. rss_new_items: RSS 新增条目列表(可选,用于新增区块)
  454. Returns:
  455. bool: 发送是否成功
  456. """
  457. headers = {"Content-Type": "application/json"}
  458. url = f"https://api.telegram.org/bot{bot_token}/sendMessage"
  459. proxies = None
  460. if proxy_url:
  461. proxies = {"http": proxy_url, "https": proxy_url}
  462. # 日志前缀
  463. log_prefix = f"Telegram{account_label}" if account_label else "Telegram"
  464. # 渲染 AI 分析内容(如果有)
  465. ai_content = None
  466. ai_stats = None
  467. if ai_analysis:
  468. ai_content = _render_ai_analysis(ai_analysis, "telegram")
  469. # 提取 AI 分析统计数据(只要 AI 分析成功就显示)
  470. if getattr(ai_analysis, "success", False):
  471. ai_stats = {
  472. "total_news": getattr(ai_analysis, "total_news", 0),
  473. "analyzed_news": getattr(ai_analysis, "analyzed_news", 0),
  474. "max_news_limit": getattr(ai_analysis, "max_news_limit", 0),
  475. "hotlist_count": getattr(ai_analysis, "hotlist_count", 0),
  476. "rss_count": getattr(ai_analysis, "rss_count", 0),
  477. "ai_mode": getattr(ai_analysis, "ai_mode", ""),
  478. }
  479. # 获取分批内容,预留批次头部空间
  480. header_reserve = get_max_batch_header_size("telegram")
  481. batches = split_content_func(
  482. report_data, "telegram", update_info, max_bytes=batch_size - header_reserve, mode=mode,
  483. rss_items=rss_items,
  484. rss_new_items=rss_new_items,
  485. ai_content=ai_content,
  486. standalone_data=standalone_data,
  487. ai_stats=ai_stats,
  488. report_type=report_type,
  489. )
  490. # 统一添加批次头部(已预留空间,不会超限)
  491. batches = add_batch_headers(batches, "telegram", batch_size)
  492. print(f"{log_prefix}消息分为 {len(batches)} 批次发送 [{report_type}]")
  493. # 逐批发送
  494. for i, batch_content in enumerate(batches, 1):
  495. content_size = len(batch_content.encode("utf-8"))
  496. print(
  497. f"发送{log_prefix}第 {i}/{len(batches)} 批次,大小:{content_size} 字节 [{report_type}]"
  498. )
  499. payload = {
  500. "chat_id": chat_id,
  501. "text": batch_content,
  502. "parse_mode": "HTML",
  503. "disable_web_page_preview": True,
  504. }
  505. try:
  506. response = requests.post(
  507. url, headers=headers, json=payload, proxies=proxies, timeout=30
  508. )
  509. if response.status_code == 200:
  510. result = response.json()
  511. if result.get("ok"):
  512. print(f"{log_prefix}第 {i}/{len(batches)} 批次发送成功 [{report_type}]")
  513. # 批次间间隔
  514. if i < len(batches):
  515. time.sleep(batch_interval)
  516. else:
  517. print(
  518. f"{log_prefix}第 {i}/{len(batches)} 批次发送失败 [{report_type}],错误:{result.get('description')}"
  519. )
  520. return False
  521. else:
  522. print(
  523. f"{log_prefix}第 {i}/{len(batches)} 批次发送失败 [{report_type}],状态码:{response.status_code}"
  524. )
  525. return False
  526. except Exception as e:
  527. print(f"{log_prefix}第 {i}/{len(batches)} 批次发送出错 [{report_type}]:{e}")
  528. return False
  529. print(f"{log_prefix}所有 {len(batches)} 批次发送完成 [{report_type}]")
  530. return True
  531. def send_to_email(
  532. from_email: str,
  533. password: str,
  534. to_email: str,
  535. report_type: str,
  536. html_file_path: str,
  537. custom_smtp_server: Optional[str] = None,
  538. custom_smtp_port: Optional[int] = None,
  539. *,
  540. get_time_func: Callable = None,
  541. ) -> bool:
  542. """
  543. 发送邮件通知
  544. Args:
  545. from_email: 发件人邮箱
  546. password: 邮箱密码/授权码
  547. to_email: 收件人邮箱(多个用逗号分隔)
  548. report_type: 报告类型
  549. html_file_path: HTML 报告文件路径
  550. custom_smtp_server: 自定义 SMTP 服务器(可选)
  551. custom_smtp_port: 自定义 SMTP 端口(可选)
  552. get_time_func: 获取当前时间的函数
  553. Returns:
  554. bool: 发送是否成功
  555. Note:
  556. AI 分析内容已在 HTML 生成时嵌入,无需再追加
  557. """
  558. try:
  559. if not html_file_path or not Path(html_file_path).exists():
  560. print(f"错误:HTML文件不存在或未提供: {html_file_path}")
  561. return False
  562. print(f"使用HTML文件: {html_file_path}")
  563. with open(html_file_path, "r", encoding="utf-8") as f:
  564. html_content = f.read()
  565. domain = from_email.split("@")[-1].lower()
  566. if custom_smtp_server and custom_smtp_port:
  567. # 使用自定义 SMTP 配置
  568. smtp_server = custom_smtp_server
  569. smtp_port = int(custom_smtp_port)
  570. # 根据端口判断加密方式:465=SSL, 587=TLS
  571. if smtp_port == 465:
  572. use_tls = False # SSL 模式(SMTP_SSL)
  573. elif smtp_port == 587:
  574. use_tls = True # TLS 模式(STARTTLS)
  575. else:
  576. # 其他端口优先尝试 TLS(更安全,更广泛支持)
  577. use_tls = True
  578. elif domain in SMTP_CONFIGS:
  579. # 使用预设配置
  580. config = SMTP_CONFIGS[domain]
  581. smtp_server = config["server"]
  582. smtp_port = config["port"]
  583. use_tls = config["encryption"] == "TLS"
  584. else:
  585. print(f"未识别的邮箱服务商: {domain},使用通用 SMTP 配置")
  586. smtp_server = f"smtp.{domain}"
  587. smtp_port = 587
  588. use_tls = True
  589. msg = MIMEMultipart("alternative")
  590. # 严格按照 RFC 标准设置 From header
  591. sender_name = "TrendRadar"
  592. msg["From"] = formataddr((sender_name, from_email))
  593. # 设置收件人
  594. recipients = [addr.strip() for addr in to_email.split(",")]
  595. if len(recipients) == 1:
  596. msg["To"] = recipients[0]
  597. else:
  598. msg["To"] = ", ".join(recipients)
  599. # 设置邮件主题
  600. now = get_time_func() if get_time_func else datetime.now()
  601. subject = f"TrendRadar 热点分析报告 - {report_type} - {now.strftime('%m月%d日 %H:%M')}"
  602. msg["Subject"] = Header(subject, "utf-8")
  603. # 设置其他标准 header
  604. msg["MIME-Version"] = "1.0"
  605. msg["Date"] = formatdate(localtime=True)
  606. msg["Message-ID"] = make_msgid()
  607. # 添加纯文本部分(作为备选)
  608. text_content = f"""
  609. TrendRadar 热点分析报告
  610. ========================
  611. 报告类型:{report_type}
  612. 生成时间:{now.strftime('%Y-%m-%d %H:%M:%S')}
  613. 请使用支持HTML的邮件客户端查看完整报告内容。
  614. """
  615. text_part = MIMEText(text_content, "plain", "utf-8")
  616. msg.attach(text_part)
  617. html_part = MIMEText(html_content, "html", "utf-8")
  618. msg.attach(html_part)
  619. print(f"正在发送邮件到 {to_email}...")
  620. print(f"SMTP 服务器: {smtp_server}:{smtp_port}")
  621. print(f"发件人: {from_email}")
  622. try:
  623. if use_tls:
  624. # TLS 模式
  625. server = smtplib.SMTP(smtp_server, smtp_port, timeout=30)
  626. server.set_debuglevel(0) # 设为1可以查看详细调试信息
  627. server.ehlo()
  628. server.starttls()
  629. server.ehlo()
  630. else:
  631. # SSL 模式
  632. server = smtplib.SMTP_SSL(smtp_server, smtp_port, timeout=30)
  633. server.set_debuglevel(0)
  634. server.ehlo()
  635. # 登录
  636. server.login(from_email, password)
  637. # 发送邮件
  638. server.send_message(msg)
  639. server.quit()
  640. print(f"邮件发送成功 [{report_type}] -> {to_email}")
  641. return True
  642. except smtplib.SMTPServerDisconnected:
  643. print("邮件发送失败:服务器意外断开连接,请检查网络或稍后重试")
  644. return False
  645. except smtplib.SMTPAuthenticationError as e:
  646. print("邮件发送失败:认证错误,请检查邮箱和密码/授权码")
  647. print(f"详细错误: {str(e)}")
  648. return False
  649. except smtplib.SMTPRecipientsRefused as e:
  650. print(f"邮件发送失败:收件人地址被拒绝 {e}")
  651. return False
  652. except smtplib.SMTPSenderRefused as e:
  653. print(f"邮件发送失败:发件人地址被拒绝 {e}")
  654. return False
  655. except smtplib.SMTPDataError as e:
  656. print(f"邮件发送失败:邮件数据错误 {e}")
  657. return False
  658. except smtplib.SMTPConnectError as e:
  659. print(f"邮件发送失败:无法连接到 SMTP 服务器 {smtp_server}:{smtp_port}")
  660. print(f"详细错误: {str(e)}")
  661. return False
  662. except Exception as e:
  663. print(f"邮件发送失败 [{report_type}]:{e}")
  664. import traceback
  665. traceback.print_exc()
  666. return False
  667. def send_to_ntfy(
  668. server_url: str,
  669. topic: str,
  670. token: Optional[str],
  671. report_data: Dict,
  672. report_type: str,
  673. update_info: Optional[Dict] = None,
  674. proxy_url: Optional[str] = None,
  675. mode: str = "daily",
  676. account_label: str = "",
  677. *,
  678. batch_size: int = 3800,
  679. split_content_func: Callable = None,
  680. rss_items: Optional[list] = None,
  681. rss_new_items: Optional[list] = None,
  682. ai_analysis: Any = None,
  683. display_regions: Optional[Dict] = None,
  684. standalone_data: Optional[Dict] = None,
  685. ) -> bool:
  686. """
  687. 发送到 ntfy(支持分批发送,严格遵守4KB限制,支持热榜+RSS合并+独立展示区)
  688. Args:
  689. server_url: ntfy 服务器 URL
  690. topic: ntfy 主题
  691. token: ntfy 访问令牌(可选)
  692. report_data: 报告数据
  693. report_type: 报告类型
  694. update_info: 更新信息(可选)
  695. proxy_url: 代理 URL(可选)
  696. mode: 报告模式 (daily/current)
  697. account_label: 账号标签(多账号时显示)
  698. batch_size: 批次大小(字节)
  699. split_content_func: 内容分批函数
  700. rss_items: RSS 统计条目列表(可选,用于合并推送)
  701. rss_new_items: RSS 新增条目列表(可选,用于新增区块)
  702. Returns:
  703. bool: 发送是否成功
  704. """
  705. # 日志前缀
  706. log_prefix = f"ntfy{account_label}" if account_label else "ntfy"
  707. # 避免 HTTP header 编码问题
  708. report_type_en_map = {
  709. "全天汇总": "Daily Summary",
  710. "当前榜单": "Current Ranking",
  711. "增量分析": "Incremental Update",
  712. "通知连通性测试": "Notification Test",
  713. }
  714. report_type_en = report_type_en_map.get(report_type, "News Report")
  715. headers = {
  716. "Content-Type": "text/plain; charset=utf-8",
  717. "Markdown": "yes",
  718. "Title": report_type_en,
  719. "Priority": "default",
  720. "Tags": "news",
  721. }
  722. if token:
  723. headers["Authorization"] = f"Bearer {token}"
  724. # 构建完整URL,确保格式正确
  725. base_url = server_url.rstrip("/")
  726. if not base_url.startswith(("http://", "https://")):
  727. base_url = f"https://{base_url}"
  728. url = f"{base_url}/{topic}"
  729. proxies = None
  730. if proxy_url:
  731. proxies = {"http": proxy_url, "https": proxy_url}
  732. # 渲染 AI 分析内容(如果有),合并到主内容中
  733. ai_content = None
  734. ai_stats = None
  735. if ai_analysis:
  736. ai_content = _render_ai_analysis(ai_analysis, "ntfy")
  737. # 提取 AI 分析统计数据(只要 AI 分析成功就显示)
  738. if getattr(ai_analysis, "success", False):
  739. ai_stats = {
  740. "total_news": getattr(ai_analysis, "total_news", 0),
  741. "analyzed_news": getattr(ai_analysis, "analyzed_news", 0),
  742. "max_news_limit": getattr(ai_analysis, "max_news_limit", 0),
  743. "hotlist_count": getattr(ai_analysis, "hotlist_count", 0),
  744. "rss_count": getattr(ai_analysis, "rss_count", 0),
  745. "ai_mode": getattr(ai_analysis, "ai_mode", ""),
  746. }
  747. # 获取分批内容,预留批次头部空间
  748. header_reserve = get_max_batch_header_size("ntfy")
  749. batches = split_content_func(
  750. report_data, "ntfy", update_info, max_bytes=batch_size - header_reserve, mode=mode,
  751. rss_items=rss_items,
  752. rss_new_items=rss_new_items,
  753. ai_content=ai_content,
  754. standalone_data=standalone_data,
  755. ai_stats=ai_stats,
  756. report_type=report_type,
  757. )
  758. # 统一添加批次头部(已预留空间,不会超限)
  759. batches = add_batch_headers(batches, "ntfy", batch_size)
  760. total_batches = len(batches)
  761. print(f"{log_prefix}消息分为 {total_batches} 批次发送 [{report_type}]")
  762. # 反转批次顺序,使得在ntfy客户端显示时顺序正确
  763. # ntfy显示最新消息在上面,所以我们从最后一批开始推送
  764. reversed_batches = list(reversed(batches))
  765. print(f"{log_prefix}将按反向顺序推送(最后批次先推送),确保客户端显示顺序正确")
  766. # 逐批发送(反向顺序)
  767. success_count = 0
  768. for idx, batch_content in enumerate(reversed_batches, 1):
  769. # 计算正确的批次编号(用户视角的编号)
  770. actual_batch_num = total_batches - idx + 1
  771. content_size = len(batch_content.encode("utf-8"))
  772. print(
  773. f"发送{log_prefix}第 {actual_batch_num}/{total_batches} 批次(推送顺序: {idx}/{total_batches}),大小:{content_size} 字节 [{report_type}]"
  774. )
  775. # 检查消息大小,确保不超过4KB
  776. if content_size > 4096:
  777. print(f"警告:{log_prefix}第 {actual_batch_num} 批次消息过大({content_size} 字节),可能被拒绝")
  778. # 更新 headers 的批次标识
  779. current_headers = headers.copy()
  780. if total_batches > 1:
  781. current_headers["Title"] = f"{report_type_en} ({actual_batch_num}/{total_batches})"
  782. try:
  783. response = requests.post(
  784. url,
  785. headers=current_headers,
  786. data=batch_content.encode("utf-8"),
  787. proxies=proxies,
  788. timeout=30,
  789. )
  790. if response.status_code == 200:
  791. print(f"{log_prefix}第 {actual_batch_num}/{total_batches} 批次发送成功 [{report_type}]")
  792. success_count += 1
  793. if idx < total_batches:
  794. # 公共服务器建议 2-3 秒,自托管可以更短
  795. interval = 2 if "ntfy.sh" in server_url else 1
  796. time.sleep(interval)
  797. elif response.status_code == 429:
  798. print(
  799. f"{log_prefix}第 {actual_batch_num}/{total_batches} 批次速率限制 [{report_type}],等待后重试"
  800. )
  801. time.sleep(10) # 等待10秒后重试
  802. # 重试一次
  803. retry_response = requests.post(
  804. url,
  805. headers=current_headers,
  806. data=batch_content.encode("utf-8"),
  807. proxies=proxies,
  808. timeout=30,
  809. )
  810. if retry_response.status_code == 200:
  811. print(f"{log_prefix}第 {actual_batch_num}/{total_batches} 批次重试成功 [{report_type}]")
  812. success_count += 1
  813. else:
  814. print(
  815. f"{log_prefix}第 {actual_batch_num}/{total_batches} 批次重试失败,状态码:{retry_response.status_code}"
  816. )
  817. elif response.status_code == 413:
  818. print(
  819. f"{log_prefix}第 {actual_batch_num}/{total_batches} 批次消息过大被拒绝 [{report_type}],消息大小:{content_size} 字节"
  820. )
  821. else:
  822. print(
  823. f"{log_prefix}第 {actual_batch_num}/{total_batches} 批次发送失败 [{report_type}],状态码:{response.status_code}"
  824. )
  825. try:
  826. print(f"错误详情:{response.text}")
  827. except:
  828. pass
  829. except requests.exceptions.ConnectTimeout:
  830. print(f"{log_prefix}第 {actual_batch_num}/{total_batches} 批次连接超时 [{report_type}]")
  831. except requests.exceptions.ReadTimeout:
  832. print(f"{log_prefix}第 {actual_batch_num}/{total_batches} 批次读取超时 [{report_type}]")
  833. except requests.exceptions.ConnectionError as e:
  834. print(f"{log_prefix}第 {actual_batch_num}/{total_batches} 批次连接错误 [{report_type}]:{e}")
  835. except Exception as e:
  836. print(f"{log_prefix}第 {actual_batch_num}/{total_batches} 批次发送异常 [{report_type}]:{e}")
  837. # 判断整体发送是否成功
  838. if success_count == total_batches:
  839. print(f"{log_prefix}所有 {total_batches} 批次发送完成 [{report_type}]")
  840. elif success_count > 0:
  841. print(f"{log_prefix}部分发送成功:{success_count}/{total_batches} 批次 [{report_type}]")
  842. else:
  843. print(f"{log_prefix}发送完全失败 [{report_type}]")
  844. return False
  845. return True
  846. def send_to_bark(
  847. bark_url: str,
  848. report_data: Dict,
  849. report_type: str,
  850. update_info: Optional[Dict] = None,
  851. proxy_url: Optional[str] = None,
  852. mode: str = "daily",
  853. account_label: str = "",
  854. *,
  855. batch_size: int = 3600,
  856. batch_interval: float = 1.0,
  857. split_content_func: Callable = None,
  858. rss_items: Optional[list] = None,
  859. rss_new_items: Optional[list] = None,
  860. ai_analysis: Any = None,
  861. display_regions: Optional[Dict] = None,
  862. standalone_data: Optional[Dict] = None,
  863. ) -> bool:
  864. """
  865. 发送到 Bark(支持分批发送,使用 markdown 格式,支持热榜+RSS合并+独立展示区)
  866. Args:
  867. bark_url: Bark URL(包含 device_key)
  868. report_data: 报告数据
  869. report_type: 报告类型
  870. update_info: 更新信息(可选)
  871. proxy_url: 代理 URL(可选)
  872. mode: 报告模式 (daily/current)
  873. account_label: 账号标签(多账号时显示)
  874. batch_size: 批次大小(字节)
  875. batch_interval: 批次发送间隔(秒)
  876. split_content_func: 内容分批函数
  877. rss_items: RSS 统计条目列表(可选,用于合并推送)
  878. rss_new_items: RSS 新增条目列表(可选,用于新增区块)
  879. Returns:
  880. bool: 发送是否成功
  881. """
  882. # 日志前缀
  883. log_prefix = f"Bark{account_label}" if account_label else "Bark"
  884. proxies = None
  885. if proxy_url:
  886. proxies = {"http": proxy_url, "https": proxy_url}
  887. # 解析 Bark URL,提取 device_key 和 API 端点
  888. # Bark URL 格式: https://api.day.app/device_key 或 https://bark.day.app/device_key
  889. parsed_url = urlparse(bark_url)
  890. device_key = parsed_url.path.strip('/').split('/')[0] if parsed_url.path else None
  891. if not device_key:
  892. print(f"{log_prefix} URL 格式错误,无法提取 device_key: {bark_url}")
  893. return False
  894. # 构建正确的 API 端点
  895. api_endpoint = f"{parsed_url.scheme}://{parsed_url.netloc}/push"
  896. # 渲染 AI 分析内容(如果有),合并到主内容中
  897. ai_content = None
  898. ai_stats = None
  899. if ai_analysis:
  900. ai_content = _render_ai_analysis(ai_analysis, "bark")
  901. # 提取 AI 分析统计数据(只要 AI 分析成功就显示)
  902. if getattr(ai_analysis, "success", False):
  903. ai_stats = {
  904. "total_news": getattr(ai_analysis, "total_news", 0),
  905. "analyzed_news": getattr(ai_analysis, "analyzed_news", 0),
  906. "max_news_limit": getattr(ai_analysis, "max_news_limit", 0),
  907. "hotlist_count": getattr(ai_analysis, "hotlist_count", 0),
  908. "rss_count": getattr(ai_analysis, "rss_count", 0),
  909. "ai_mode": getattr(ai_analysis, "ai_mode", ""),
  910. }
  911. # 获取分批内容,预留批次头部空间
  912. header_reserve = get_max_batch_header_size("bark")
  913. batches = split_content_func(
  914. report_data, "bark", update_info, max_bytes=batch_size - header_reserve, mode=mode,
  915. rss_items=rss_items,
  916. rss_new_items=rss_new_items,
  917. ai_content=ai_content,
  918. standalone_data=standalone_data,
  919. ai_stats=ai_stats,
  920. report_type=report_type,
  921. )
  922. # 统一添加批次头部(已预留空间,不会超限)
  923. batches = add_batch_headers(batches, "bark", batch_size)
  924. total_batches = len(batches)
  925. print(f"{log_prefix}消息分为 {total_batches} 批次发送 [{report_type}]")
  926. # 反转批次顺序,使得在Bark客户端显示时顺序正确
  927. # Bark显示最新消息在上面,所以我们从最后一批开始推送
  928. reversed_batches = list(reversed(batches))
  929. print(f"{log_prefix}将按反向顺序推送(最后批次先推送),确保客户端显示顺序正确")
  930. # 逐批发送(反向顺序)
  931. success_count = 0
  932. for idx, batch_content in enumerate(reversed_batches, 1):
  933. # 计算正确的批次编号(用户视角的编号)
  934. actual_batch_num = total_batches - idx + 1
  935. content_size = len(batch_content.encode("utf-8"))
  936. print(
  937. f"发送{log_prefix}第 {actual_batch_num}/{total_batches} 批次(推送顺序: {idx}/{total_batches}),大小:{content_size} 字节 [{report_type}]"
  938. )
  939. # 检查消息大小(Bark使用APNs,限制4KB)
  940. if content_size > 4096:
  941. print(
  942. f"警告:{log_prefix}第 {actual_batch_num}/{total_batches} 批次消息过大({content_size} 字节),可能被拒绝"
  943. )
  944. # 构建JSON payload
  945. payload = {
  946. "title": report_type,
  947. "markdown": batch_content,
  948. "device_key": device_key,
  949. "sound": "default",
  950. "group": "TrendRadar",
  951. "action": "none", # 点击推送跳到 APP 不弹出弹框,方便阅读
  952. }
  953. try:
  954. response = requests.post(
  955. api_endpoint,
  956. json=payload,
  957. proxies=proxies,
  958. timeout=30,
  959. )
  960. if response.status_code == 200:
  961. result = response.json()
  962. if result.get("code") == 200:
  963. print(f"{log_prefix}第 {actual_batch_num}/{total_batches} 批次发送成功 [{report_type}]")
  964. success_count += 1
  965. # 批次间间隔
  966. if idx < total_batches:
  967. time.sleep(batch_interval)
  968. else:
  969. print(
  970. f"{log_prefix}第 {actual_batch_num}/{total_batches} 批次发送失败 [{report_type}],错误:{result.get('message', '未知错误')}"
  971. )
  972. else:
  973. print(
  974. f"{log_prefix}第 {actual_batch_num}/{total_batches} 批次发送失败 [{report_type}],状态码:{response.status_code}"
  975. )
  976. try:
  977. print(f"错误详情:{response.text}")
  978. except:
  979. pass
  980. except requests.exceptions.ConnectTimeout:
  981. print(f"{log_prefix}第 {actual_batch_num}/{total_batches} 批次连接超时 [{report_type}]")
  982. except requests.exceptions.ReadTimeout:
  983. print(f"{log_prefix}第 {actual_batch_num}/{total_batches} 批次读取超时 [{report_type}]")
  984. except requests.exceptions.ConnectionError as e:
  985. print(f"{log_prefix}第 {actual_batch_num}/{total_batches} 批次连接错误 [{report_type}]:{e}")
  986. except Exception as e:
  987. print(f"{log_prefix}第 {actual_batch_num}/{total_batches} 批次发送异常 [{report_type}]:{e}")
  988. # 判断整体发送是否成功
  989. if success_count == total_batches:
  990. print(f"{log_prefix}所有 {total_batches} 批次发送完成 [{report_type}]")
  991. elif success_count > 0:
  992. print(f"{log_prefix}部分发送成功:{success_count}/{total_batches} 批次 [{report_type}]")
  993. else:
  994. print(f"{log_prefix}发送完全失败 [{report_type}]")
  995. return False
  996. return True
  997. def send_to_slack(
  998. webhook_url: str,
  999. report_data: Dict,
  1000. report_type: str,
  1001. update_info: Optional[Dict] = None,
  1002. proxy_url: Optional[str] = None,
  1003. mode: str = "daily",
  1004. account_label: str = "",
  1005. *,
  1006. batch_size: int = 4000,
  1007. batch_interval: float = 1.0,
  1008. split_content_func: Callable = None,
  1009. rss_items: Optional[list] = None,
  1010. rss_new_items: Optional[list] = None,
  1011. ai_analysis: Any = None,
  1012. display_regions: Optional[Dict] = None,
  1013. standalone_data: Optional[Dict] = None,
  1014. ) -> bool:
  1015. """
  1016. 发送到 Slack(支持分批发送,使用 mrkdwn 格式,支持热榜+RSS合并+独立展示区)
  1017. Args:
  1018. webhook_url: Slack Webhook URL
  1019. report_data: 报告数据
  1020. report_type: 报告类型
  1021. update_info: 更新信息(可选)
  1022. proxy_url: 代理 URL(可选)
  1023. mode: 报告模式 (daily/current)
  1024. account_label: 账号标签(多账号时显示)
  1025. batch_size: 批次大小(字节)
  1026. batch_interval: 批次发送间隔(秒)
  1027. split_content_func: 内容分批函数
  1028. rss_items: RSS 统计条目列表(可选,用于合并推送)
  1029. rss_new_items: RSS 新增条目列表(可选,用于新增区块)
  1030. Returns:
  1031. bool: 发送是否成功
  1032. """
  1033. headers = {"Content-Type": "application/json"}
  1034. proxies = None
  1035. if proxy_url:
  1036. proxies = {"http": proxy_url, "https": proxy_url}
  1037. # 日志前缀
  1038. log_prefix = f"Slack{account_label}" if account_label else "Slack"
  1039. # 渲染 AI 分析内容(如果有),合并到主内容中
  1040. ai_content = None
  1041. ai_stats = None
  1042. if ai_analysis:
  1043. ai_content = _render_ai_analysis(ai_analysis, "slack")
  1044. # 提取 AI 分析统计数据(只要 AI 分析成功就显示)
  1045. if getattr(ai_analysis, "success", False):
  1046. ai_stats = {
  1047. "total_news": getattr(ai_analysis, "total_news", 0),
  1048. "analyzed_news": getattr(ai_analysis, "analyzed_news", 0),
  1049. "max_news_limit": getattr(ai_analysis, "max_news_limit", 0),
  1050. "hotlist_count": getattr(ai_analysis, "hotlist_count", 0),
  1051. "rss_count": getattr(ai_analysis, "rss_count", 0),
  1052. "ai_mode": getattr(ai_analysis, "ai_mode", ""),
  1053. }
  1054. # 获取分批内容,预留批次头部空间
  1055. header_reserve = get_max_batch_header_size("slack")
  1056. batches = split_content_func(
  1057. report_data, "slack", update_info, max_bytes=batch_size - header_reserve, mode=mode,
  1058. rss_items=rss_items,
  1059. rss_new_items=rss_new_items,
  1060. ai_content=ai_content,
  1061. standalone_data=standalone_data,
  1062. ai_stats=ai_stats,
  1063. report_type=report_type,
  1064. )
  1065. # 统一添加批次头部(已预留空间,不会超限)
  1066. batches = add_batch_headers(batches, "slack", batch_size)
  1067. print(f"{log_prefix}消息分为 {len(batches)} 批次发送 [{report_type}]")
  1068. # 逐批发送
  1069. for i, batch_content in enumerate(batches, 1):
  1070. # 转换 Markdown 到 mrkdwn 格式
  1071. mrkdwn_content = convert_markdown_to_mrkdwn(batch_content)
  1072. content_size = len(mrkdwn_content.encode("utf-8"))
  1073. print(
  1074. f"发送{log_prefix}第 {i}/{len(batches)} 批次,大小:{content_size} 字节 [{report_type}]"
  1075. )
  1076. # 构建 Slack payload(使用简单的 text 字段,支持 mrkdwn)
  1077. payload = {"text": mrkdwn_content}
  1078. try:
  1079. response = requests.post(
  1080. webhook_url, headers=headers, json=payload, proxies=proxies, timeout=30
  1081. )
  1082. # Slack Incoming Webhooks 成功时返回 "ok" 文本
  1083. if response.status_code == 200 and response.text == "ok":
  1084. print(f"{log_prefix}第 {i}/{len(batches)} 批次发送成功 [{report_type}]")
  1085. # 批次间间隔
  1086. if i < len(batches):
  1087. time.sleep(batch_interval)
  1088. else:
  1089. error_msg = response.text if response.text else f"状态码:{response.status_code}"
  1090. print(
  1091. f"{log_prefix}第 {i}/{len(batches)} 批次发送失败 [{report_type}],错误:{error_msg}"
  1092. )
  1093. return False
  1094. except Exception as e:
  1095. print(f"{log_prefix}第 {i}/{len(batches)} 批次发送出错 [{report_type}]:{e}")
  1096. return False
  1097. print(f"{log_prefix}所有 {len(batches)} 批次发送完成 [{report_type}]")
  1098. return True
  1099. def send_to_generic_webhook(
  1100. webhook_url: str,
  1101. payload_template: Optional[str],
  1102. report_data: Dict,
  1103. report_type: str,
  1104. update_info: Optional[Dict] = None,
  1105. proxy_url: Optional[str] = None,
  1106. mode: str = "daily",
  1107. account_label: str = "",
  1108. *,
  1109. batch_size: int = 4000,
  1110. batch_interval: float = 1.0,
  1111. split_content_func: Optional[Callable] = None,
  1112. rss_items: Optional[list] = None,
  1113. rss_new_items: Optional[list] = None,
  1114. ai_analysis: Any = None,
  1115. display_regions: Optional[Dict] = None,
  1116. standalone_data: Optional[Dict] = None,
  1117. ) -> bool:
  1118. """
  1119. 发送到通用 Webhook(支持分批发送,支持自定义 JSON 模板,支持热榜+RSS合并+独立展示区)
  1120. Args:
  1121. webhook_url: Webhook URL
  1122. payload_template: JSON 模板字符串,支持 {title} 和 {content} 占位符
  1123. report_data: 报告数据
  1124. report_type: 报告类型
  1125. update_info: 更新信息(可选)
  1126. proxy_url: 代理 URL(可选)
  1127. mode: 报告模式 (daily/current)
  1128. account_label: 账号标签(多账号时显示)
  1129. batch_size: 批次大小(字节)
  1130. batch_interval: 批次发送间隔(秒)
  1131. split_content_func: 内容分批函数
  1132. rss_items: RSS 统计条目列表(可选,用于合并推送)
  1133. rss_new_items: RSS 新增条目列表(可选,用于新增区块)
  1134. Returns:
  1135. bool: 发送是否成功
  1136. """
  1137. if split_content_func is None:
  1138. raise ValueError("split_content_func is required")
  1139. headers = {"Content-Type": "application/json"}
  1140. proxies = None
  1141. if proxy_url:
  1142. proxies = {"http": proxy_url, "https": proxy_url}
  1143. # 日志前缀
  1144. log_prefix = f"通用Webhook{account_label}" if account_label else "通用Webhook"
  1145. # 渲染 AI 分析内容(如果有)
  1146. ai_content = None
  1147. ai_stats = None
  1148. if ai_analysis:
  1149. # 通用 Webhook 使用 markdown 格式渲染 AI 分析
  1150. ai_content = _render_ai_analysis(ai_analysis, "wework")
  1151. # 提取 AI 分析统计数据
  1152. if getattr(ai_analysis, "success", False):
  1153. ai_stats = {
  1154. "total_news": getattr(ai_analysis, "total_news", 0),
  1155. "analyzed_news": getattr(ai_analysis, "analyzed_news", 0),
  1156. "max_news_limit": getattr(ai_analysis, "max_news_limit", 0),
  1157. "hotlist_count": getattr(ai_analysis, "hotlist_count", 0),
  1158. "rss_count": getattr(ai_analysis, "rss_count", 0),
  1159. }
  1160. # 获取分批内容
  1161. # 使用 'wework' 作为 format_type 以获取 markdown 格式的通用输出
  1162. # 预留一定空间给模板外壳
  1163. template_overhead = 200
  1164. batches = split_content_func(
  1165. report_data, "wework", update_info, max_bytes=batch_size - template_overhead, mode=mode,
  1166. rss_items=rss_items,
  1167. rss_new_items=rss_new_items,
  1168. ai_content=ai_content,
  1169. standalone_data=standalone_data,
  1170. ai_stats=ai_stats,
  1171. report_type=report_type,
  1172. )
  1173. # 统一添加批次头部
  1174. batches = add_batch_headers(batches, "wework", batch_size)
  1175. print(f"{log_prefix}消息分为 {len(batches)} 批次发送 [{report_type}]")
  1176. # 逐批发送
  1177. for i, batch_content in enumerate(batches, 1):
  1178. content_size = len(batch_content.encode("utf-8"))
  1179. print(
  1180. f"发送{log_prefix}第 {i}/{len(batches)} 批次,大小:{content_size} 字节 [{report_type}]"
  1181. )
  1182. try:
  1183. # 构建 payload
  1184. if payload_template:
  1185. # 简单的字符串替换
  1186. # 注意:content 可能包含 JSON 特殊字符,需要先转义
  1187. json_content = json.dumps(batch_content)[1:-1] # 去掉首尾引号
  1188. json_title = json.dumps(report_type)[1:-1]
  1189. payload_str = payload_template.replace("{content}", json_content).replace("{title}", json_title)
  1190. # 尝试解析为 JSON 对象以验证有效性
  1191. try:
  1192. payload = json.loads(payload_str)
  1193. except json.JSONDecodeError as e:
  1194. print(f"{log_prefix} JSON 模板解析失败: {e}")
  1195. # 回退到默认格式
  1196. payload = {"title": report_type, "content": batch_content}
  1197. else:
  1198. # 默认格式
  1199. payload = {"title": report_type, "content": batch_content}
  1200. response = requests.post(
  1201. webhook_url, headers=headers, json=payload, proxies=proxies, timeout=30
  1202. )
  1203. if response.status_code >= 200 and response.status_code < 300:
  1204. print(f"{log_prefix}第 {i}/{len(batches)} 批次发送成功 [{report_type}]")
  1205. if i < len(batches):
  1206. time.sleep(batch_interval)
  1207. else:
  1208. print(
  1209. f"{log_prefix}第 {i}/{len(batches)} 批次发送失败 [{report_type}],状态码:{response.status_code}, 响应: {response.text}"
  1210. )
  1211. return False
  1212. except Exception as e:
  1213. print(f"{log_prefix}第 {i}/{len(batches)} 批次发送出错 [{report_type}]:{e}")
  1214. return False
  1215. print(f"{log_prefix}所有 {len(batches)} 批次发送完成 [{report_type}]")
  1216. return True