main.py 82 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301
  1. # coding=utf-8
  2. import json
  3. import time
  4. import random
  5. from datetime import datetime
  6. import webbrowser
  7. from typing import Dict, List, Tuple, Optional, Union
  8. from pathlib import Path
  9. import os
  10. import requests
  11. import pytz
  12. CONFIG = {
  13. "VERSION": "1.2.1",
  14. "VERSION_CHECK_URL": "https://raw.githubusercontent.com/sansan0/TrendRadar/refs/heads/master/version",
  15. "SHOW_VERSION_UPDATE": True, # 控制显示版本更新提示,改成 False 将不接受新版本提示
  16. "FEISHU_MESSAGE_SEPARATOR": "━━━━━━━━━━━━━━━━━━━", # feishu消息分割线
  17. "REQUEST_INTERVAL": 1000, # 请求间隔(毫秒)
  18. "REPORT_TYPE": "daily", # 报告类型: "current"|"daily"|"both"
  19. "RANK_THRESHOLD": 5, # 排名高亮阈值
  20. "USE_PROXY": True, # 是否启用代理
  21. "DEFAULT_PROXY": "http://127.0.0.1:10086",
  22. "CONTINUE_WITHOUT_WEBHOOK": True, # 控制在没有webhook URL时是否继续执行爬虫
  23. # 飞书机器人的 webhook URL
  24. "FEISHU_WEBHOOK_URL": "",
  25. # 钉钉机器人的 webhook URL
  26. "DINGTALK_WEBHOOK_URL": "",
  27. # 企业微信机器人的 webhook URL
  28. "WEWORK_WEBHOOK_URL": "",
  29. # Telegram 要填两个
  30. "TELEGRAM_BOT_TOKEN": "",
  31. "TELEGRAM_CHAT_ID": "",
  32. # 用于让关注度更高的新闻在更前面显示,这里是权重排序配置,合起来是 1 就行
  33. "WEIGHT_CONFIG": {
  34. "RANK_WEIGHT": 0.6, # 排名
  35. "FREQUENCY_WEIGHT": 0.3, # 频次
  36. "HOTNESS_WEIGHT": 0.1, # 热度
  37. },
  38. }
  39. class TimeHelper:
  40. """时间处理工具"""
  41. @staticmethod
  42. def get_beijing_time() -> datetime:
  43. return datetime.now(pytz.timezone("Asia/Shanghai"))
  44. @staticmethod
  45. def format_date_folder() -> str:
  46. return TimeHelper.get_beijing_time().strftime("%Y年%m月%d日")
  47. @staticmethod
  48. def format_time_filename() -> str:
  49. return TimeHelper.get_beijing_time().strftime("%H时%M分")
  50. class VersionChecker:
  51. """版本检查工具"""
  52. @staticmethod
  53. def parse_version(version_str: str) -> Tuple[int, int, int]:
  54. """解析版本号字符串为元组"""
  55. try:
  56. parts = version_str.strip().split(".")
  57. if len(parts) != 3:
  58. raise ValueError("版本号格式不正确")
  59. return tuple(int(part) for part in parts)
  60. except (ValueError, AttributeError):
  61. print(f"无法解析版本号: {version_str}")
  62. return (0, 0, 0)
  63. @staticmethod
  64. def compare_versions(current: str, remote: str) -> int:
  65. """比较版本号"""
  66. current_tuple = VersionChecker.parse_version(current)
  67. remote_tuple = VersionChecker.parse_version(remote)
  68. if current_tuple < remote_tuple:
  69. return -1 # 需要更新
  70. elif current_tuple > remote_tuple:
  71. return 1 # 当前版本更新
  72. else:
  73. return 0 # 版本相同
  74. @staticmethod
  75. def check_for_updates(
  76. current_version: str,
  77. version_url: str,
  78. proxy_url: Optional[str] = None,
  79. timeout: int = 10,
  80. ) -> Tuple[bool, Optional[str]]:
  81. """检查是否有新版本"""
  82. try:
  83. proxies = None
  84. if proxy_url:
  85. proxies = {"http": proxy_url, "https": proxy_url}
  86. headers = {
  87. "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
  88. "Accept": "text/plain, */*",
  89. "Cache-Control": "no-cache",
  90. }
  91. response = requests.get(
  92. version_url, proxies=proxies, headers=headers, timeout=timeout
  93. )
  94. response.raise_for_status()
  95. remote_version = response.text.strip()
  96. print(f"当前版本: {current_version}, 远程版本: {remote_version}")
  97. comparison = VersionChecker.compare_versions(
  98. current_version, remote_version
  99. )
  100. need_update = comparison == -1
  101. return need_update, remote_version if need_update else None
  102. except Exception as e:
  103. print(f"版本检查失败: {e}")
  104. return False, None
  105. class FileHelper:
  106. """文件操作工具"""
  107. @staticmethod
  108. def ensure_directory_exists(directory: str) -> None:
  109. Path(directory).mkdir(parents=True, exist_ok=True)
  110. @staticmethod
  111. def get_output_path(subfolder: str, filename: str) -> str:
  112. date_folder = TimeHelper.format_date_folder()
  113. output_dir = Path("output") / date_folder / subfolder
  114. FileHelper.ensure_directory_exists(str(output_dir))
  115. return str(output_dir / filename)
  116. class DataFetcher:
  117. """数据获取器"""
  118. def __init__(self, proxy_url: Optional[str] = None):
  119. self.proxy_url = proxy_url
  120. def fetch_data(
  121. self,
  122. id_info: Union[str, Tuple[str, str]],
  123. max_retries: int = 2,
  124. min_retry_wait: int = 3,
  125. max_retry_wait: int = 5,
  126. ) -> Tuple[Optional[str], str, str]:
  127. """获取指定ID数据,支持重试"""
  128. if isinstance(id_info, tuple):
  129. id_value, alias = id_info
  130. else:
  131. id_value = id_info
  132. alias = id_value
  133. url = f"https://newsnow.busiyi.world/api/s?id={id_value}&latest"
  134. proxies = None
  135. if self.proxy_url:
  136. proxies = {"http": self.proxy_url, "https": self.proxy_url}
  137. headers = {
  138. "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
  139. "Accept": "application/json, text/plain, */*",
  140. "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
  141. "Connection": "keep-alive",
  142. "Cache-Control": "no-cache",
  143. }
  144. retries = 0
  145. while retries <= max_retries:
  146. try:
  147. response = requests.get(
  148. url, proxies=proxies, headers=headers, timeout=10
  149. )
  150. response.raise_for_status()
  151. data_text = response.text
  152. data_json = json.loads(data_text)
  153. status = data_json.get("status", "未知")
  154. if status not in ["success", "cache"]:
  155. raise ValueError(f"响应状态异常: {status}")
  156. status_info = "最新数据" if status == "success" else "缓存数据"
  157. print(f"获取 {id_value} 成功({status_info})")
  158. return data_text, id_value, alias
  159. except Exception as e:
  160. retries += 1
  161. if retries <= max_retries:
  162. base_wait = random.uniform(min_retry_wait, max_retry_wait)
  163. additional_wait = (retries - 1) * random.uniform(1, 2)
  164. wait_time = base_wait + additional_wait
  165. print(f"请求 {id_value} 失败: {e}. {wait_time:.2f}秒后重试...")
  166. time.sleep(wait_time)
  167. else:
  168. print(f"请求 {id_value} 失败: {e}")
  169. return None, id_value, alias
  170. return None, id_value, alias
  171. def crawl_websites(
  172. self,
  173. ids_list: List[Union[str, Tuple[str, str]]],
  174. request_interval: int = CONFIG["REQUEST_INTERVAL"],
  175. ) -> Tuple[Dict, Dict, List]:
  176. """爬取多个网站数据"""
  177. results = {}
  178. id_to_alias = {}
  179. failed_ids = []
  180. for i, id_info in enumerate(ids_list):
  181. if isinstance(id_info, tuple):
  182. id_value, alias = id_info
  183. else:
  184. id_value = id_info
  185. alias = id_value
  186. id_to_alias[id_value] = alias
  187. response, _, _ = self.fetch_data(id_info)
  188. if response:
  189. try:
  190. data = json.loads(response)
  191. results[id_value] = {}
  192. for index, item in enumerate(data.get("items", []), 1):
  193. title = item["title"]
  194. url = item.get("url", "")
  195. mobile_url = item.get("mobileUrl", "")
  196. if title in results[id_value]:
  197. results[id_value][title]["ranks"].append(index)
  198. else:
  199. results[id_value][title] = {
  200. "ranks": [index],
  201. "url": url,
  202. "mobileUrl": mobile_url,
  203. }
  204. except json.JSONDecodeError:
  205. print(f"解析 {id_value} 响应失败")
  206. failed_ids.append(id_value)
  207. except Exception as e:
  208. print(f"处理 {id_value} 数据出错: {e}")
  209. failed_ids.append(id_value)
  210. else:
  211. failed_ids.append(id_value)
  212. if i < len(ids_list) - 1:
  213. actual_interval = request_interval + random.randint(-10, 20)
  214. actual_interval = max(50, actual_interval)
  215. time.sleep(actual_interval / 1000)
  216. print(f"成功: {list(results.keys())}, 失败: {failed_ids}")
  217. return results, id_to_alias, failed_ids
  218. class DataProcessor:
  219. """数据处理器"""
  220. @staticmethod
  221. def detect_latest_new_titles(id_to_alias: Dict) -> Dict:
  222. """检测当日最新批次的新增标题"""
  223. date_folder = TimeHelper.format_date_folder()
  224. txt_dir = Path("output") / date_folder / "txt"
  225. if not txt_dir.exists():
  226. return {}
  227. files = sorted([f for f in txt_dir.iterdir() if f.suffix == ".txt"])
  228. if len(files) < 2:
  229. if len(files) == 1:
  230. return DataProcessor._parse_file_titles(files[0])
  231. return {}
  232. latest_file = files[-1]
  233. latest_titles = DataProcessor._parse_file_titles(latest_file)
  234. # 汇总历史标题
  235. historical_titles = {}
  236. for file_path in files[:-1]:
  237. historical_data = DataProcessor._parse_file_titles(file_path)
  238. for source_name, titles_data in historical_data.items():
  239. if source_name not in historical_titles:
  240. historical_titles[source_name] = set()
  241. for title in titles_data.keys():
  242. historical_titles[source_name].add(title)
  243. # 找出新增标题
  244. new_titles = {}
  245. for source_name, latest_source_titles in latest_titles.items():
  246. historical_set = historical_titles.get(source_name, set())
  247. source_new_titles = {}
  248. for title, title_data in latest_source_titles.items():
  249. if title not in historical_set:
  250. source_new_titles[title] = title_data
  251. if source_new_titles:
  252. source_id = None
  253. for id_val, alias in id_to_alias.items():
  254. if alias == source_name:
  255. source_id = id_val
  256. break
  257. if source_id:
  258. new_titles[source_id] = source_new_titles
  259. return new_titles
  260. @staticmethod
  261. def _parse_file_titles(file_path: Path) -> Dict:
  262. """解析单个txt文件的标题数据"""
  263. titles_by_source = {}
  264. with open(file_path, "r", encoding="utf-8") as f:
  265. content = f.read()
  266. sections = content.split("\n\n")
  267. for section in sections:
  268. if not section.strip() or "==== 以下ID请求失败 ====" in section:
  269. continue
  270. lines = section.strip().split("\n")
  271. if len(lines) < 2:
  272. continue
  273. source_name = lines[0].strip()
  274. titles_by_source[source_name] = {}
  275. for line in lines[1:]:
  276. if line.strip():
  277. try:
  278. title_part = line.strip()
  279. rank = None
  280. # 提取排名
  281. if (
  282. ". " in title_part
  283. and title_part.split(". ")[0].isdigit()
  284. ):
  285. rank_str, title_part = title_part.split(". ", 1)
  286. rank = int(rank_str)
  287. # 提取MOBILE URL
  288. mobile_url = ""
  289. if " [MOBILE:" in title_part:
  290. title_part, mobile_part = title_part.rsplit(
  291. " [MOBILE:", 1
  292. )
  293. if mobile_part.endswith("]"):
  294. mobile_url = mobile_part[:-1]
  295. # 提取URL
  296. url = ""
  297. if " [URL:" in title_part:
  298. title_part, url_part = title_part.rsplit(" [URL:", 1)
  299. if url_part.endswith("]"):
  300. url = url_part[:-1]
  301. title = title_part.strip()
  302. ranks = [rank] if rank is not None else [1]
  303. titles_by_source[source_name][title] = {
  304. "ranks": ranks,
  305. "url": url,
  306. "mobileUrl": mobile_url,
  307. }
  308. except Exception as e:
  309. print(f"解析标题行出错: {line}, 错误: {e}")
  310. return titles_by_source
  311. @staticmethod
  312. def save_titles_to_file(results: Dict, id_to_alias: Dict, failed_ids: List) -> str:
  313. """保存标题到文件"""
  314. file_path = FileHelper.get_output_path(
  315. "txt", f"{TimeHelper.format_time_filename()}.txt"
  316. )
  317. with open(file_path, "w", encoding="utf-8") as f:
  318. for id_value, title_data in results.items():
  319. display_name = id_to_alias.get(id_value, id_value)
  320. f.write(f"{display_name}\n")
  321. # 按排名排序标题
  322. sorted_titles = []
  323. for title, info in title_data.items():
  324. if isinstance(info, dict):
  325. ranks = info.get("ranks", [])
  326. url = info.get("url", "")
  327. mobile_url = info.get("mobileUrl", "")
  328. else:
  329. ranks = info if isinstance(info, list) else []
  330. url = ""
  331. mobile_url = ""
  332. rank = ranks[0] if ranks else 1
  333. sorted_titles.append((rank, title, url, mobile_url))
  334. sorted_titles.sort(key=lambda x: x[0])
  335. for rank, title, url, mobile_url in sorted_titles:
  336. line = f"{rank}. {title}"
  337. if url:
  338. line += f" [URL:{url}]"
  339. if mobile_url:
  340. line += f" [MOBILE:{mobile_url}]"
  341. f.write(line + "\n")
  342. f.write("\n")
  343. if failed_ids:
  344. f.write("==== 以下ID请求失败 ====\n")
  345. for id_value in failed_ids:
  346. display_name = id_to_alias.get(id_value, id_value)
  347. f.write(f"{display_name} (ID: {id_value})\n")
  348. return file_path
  349. @staticmethod
  350. def load_frequency_words(
  351. frequency_file: str = "frequency_words.txt",
  352. ) -> Tuple[List[Dict], List[str]]:
  353. """加载频率词配置"""
  354. frequency_path = Path(frequency_file)
  355. if not frequency_path.exists():
  356. print(f"频率词文件 {frequency_file} 不存在")
  357. return [], []
  358. with open(frequency_path, "r", encoding="utf-8") as f:
  359. content = f.read()
  360. word_groups = [
  361. group.strip() for group in content.split("\n\n") if group.strip()
  362. ]
  363. processed_groups = []
  364. filter_words = []
  365. for group in word_groups:
  366. words = [word.strip() for word in group.split("\n") if word.strip()]
  367. group_required_words = []
  368. group_normal_words = []
  369. group_filter_words = []
  370. for word in words:
  371. if word.startswith("!"):
  372. filter_words.append(word[1:])
  373. group_filter_words.append(word[1:])
  374. elif word.startswith("+"):
  375. group_required_words.append(word[1:])
  376. else:
  377. group_normal_words.append(word)
  378. if group_required_words or group_normal_words:
  379. if group_normal_words:
  380. group_key = " ".join(group_normal_words)
  381. else:
  382. group_key = " ".join(group_required_words)
  383. processed_groups.append(
  384. {
  385. "required": group_required_words,
  386. "normal": group_normal_words,
  387. "group_key": group_key,
  388. }
  389. )
  390. return processed_groups, filter_words
  391. @staticmethod
  392. def read_all_today_titles() -> Tuple[Dict, Dict, Dict]:
  393. """读取当天所有标题文件"""
  394. date_folder = TimeHelper.format_date_folder()
  395. txt_dir = Path("output") / date_folder / "txt"
  396. if not txt_dir.exists():
  397. return {}, {}, {}
  398. all_results = {}
  399. id_to_alias = {}
  400. title_info = {}
  401. files = sorted([f for f in txt_dir.iterdir() if f.suffix == ".txt"])
  402. for file_path in files:
  403. time_info = file_path.stem
  404. with open(file_path, "r", encoding="utf-8") as f:
  405. content = f.read()
  406. sections = content.split("\n\n")
  407. for section in sections:
  408. if not section.strip() or "==== 以下ID请求失败 ====" in section:
  409. continue
  410. lines = section.strip().split("\n")
  411. if len(lines) < 2:
  412. continue
  413. source_name = lines[0].strip()
  414. title_data = {}
  415. for line in lines[1:]:
  416. if line.strip():
  417. try:
  418. rank = None
  419. title_part = line.strip()
  420. # 提取行首的排名数字
  421. if (
  422. ". " in title_part
  423. and title_part.split(". ")[0].isdigit()
  424. ):
  425. parts = title_part.split(". ", 1)
  426. rank = int(parts[0])
  427. title_part = parts[1]
  428. # 提取 MOBILE URL
  429. mobile_url = ""
  430. if " [MOBILE:" in title_part:
  431. title_part, mobile_part = title_part.rsplit(
  432. " [MOBILE:", 1
  433. )
  434. if mobile_part.endswith("]"):
  435. mobile_url = mobile_part[:-1]
  436. # 提取 URL
  437. url = ""
  438. if " [URL:" in title_part:
  439. title_part, url_part = title_part.rsplit(
  440. " [URL:", 1
  441. )
  442. if url_part.endswith("]"):
  443. url = url_part[:-1]
  444. title = title_part.strip()
  445. ranks = [rank] if rank is not None else [1]
  446. title_data[title] = {
  447. "ranks": ranks,
  448. "url": url,
  449. "mobileUrl": mobile_url,
  450. }
  451. except Exception as e:
  452. print(f"解析标题行出错: {line}, 错误: {e}")
  453. DataProcessor._process_source_data(
  454. source_name,
  455. title_data,
  456. time_info,
  457. all_results,
  458. title_info,
  459. id_to_alias,
  460. )
  461. # 转换为ID格式
  462. id_results = {}
  463. id_title_info = {}
  464. for name, titles in all_results.items():
  465. for id_value, alias in id_to_alias.items():
  466. if alias == name:
  467. id_results[id_value] = titles
  468. id_title_info[id_value] = title_info[name]
  469. break
  470. return id_results, id_to_alias, id_title_info
  471. @staticmethod
  472. def _process_source_data(
  473. source_name: str,
  474. title_data: Dict,
  475. time_info: str,
  476. all_results: Dict,
  477. title_info: Dict,
  478. id_to_alias: Dict,
  479. ) -> None:
  480. """处理来源数据,合并重复标题"""
  481. if source_name not in all_results:
  482. all_results[source_name] = title_data
  483. if source_name not in title_info:
  484. title_info[source_name] = {}
  485. for title, data in title_data.items():
  486. ranks = data.get("ranks", [])
  487. url = data.get("url", "")
  488. mobile_url = data.get("mobileUrl", "")
  489. title_info[source_name][title] = {
  490. "first_time": time_info,
  491. "last_time": time_info,
  492. "count": 1,
  493. "ranks": ranks,
  494. "url": url,
  495. "mobileUrl": mobile_url,
  496. }
  497. reversed_id = source_name.lower().replace(" ", "-")
  498. id_to_alias[reversed_id] = source_name
  499. else:
  500. for title, data in title_data.items():
  501. ranks = data.get("ranks", [])
  502. url = data.get("url", "")
  503. mobile_url = data.get("mobileUrl", "")
  504. if title not in all_results[source_name]:
  505. all_results[source_name][title] = {
  506. "ranks": ranks,
  507. "url": url,
  508. "mobileUrl": mobile_url,
  509. }
  510. title_info[source_name][title] = {
  511. "first_time": time_info,
  512. "last_time": time_info,
  513. "count": 1,
  514. "ranks": ranks,
  515. "url": url,
  516. "mobileUrl": mobile_url,
  517. }
  518. else:
  519. existing_data = all_results[source_name][title]
  520. existing_ranks = existing_data.get("ranks", [])
  521. existing_url = existing_data.get("url", "")
  522. existing_mobile_url = existing_data.get("mobileUrl", "")
  523. merged_ranks = existing_ranks.copy()
  524. for rank in ranks:
  525. if rank not in merged_ranks:
  526. merged_ranks.append(rank)
  527. all_results[source_name][title] = {
  528. "ranks": merged_ranks,
  529. "url": existing_url or url,
  530. "mobileUrl": existing_mobile_url or mobile_url,
  531. }
  532. title_info[source_name][title]["last_time"] = time_info
  533. title_info[source_name][title]["ranks"] = merged_ranks
  534. title_info[source_name][title]["count"] += 1
  535. if not title_info[source_name][title].get("url"):
  536. title_info[source_name][title]["url"] = url
  537. if not title_info[source_name][title].get("mobileUrl"):
  538. title_info[source_name][title]["mobileUrl"] = mobile_url
  539. class StatisticsCalculator:
  540. """统计计算器"""
  541. @staticmethod
  542. def calculate_news_weight(
  543. title_data: Dict, rank_threshold: int = CONFIG["RANK_THRESHOLD"]
  544. ) -> float:
  545. """计算新闻权重,用于排序"""
  546. ranks = title_data.get("ranks", [])
  547. if not ranks:
  548. return 0.0
  549. count = title_data.get("count", len(ranks))
  550. weight_config = CONFIG["WEIGHT_CONFIG"]
  551. # 排名权重:Σ(11 - min(rank, 10)) / 出现次数
  552. rank_scores = []
  553. for rank in ranks:
  554. score = 11 - min(rank, 10)
  555. rank_scores.append(score)
  556. rank_weight = sum(rank_scores) / len(ranks) if ranks else 0
  557. # 频次权重:min(出现次数, 10) × 10
  558. frequency_weight = min(count, 10) * 10
  559. # 热度加成:高排名次数 / 总出现次数 × 100
  560. high_rank_count = sum(1 for rank in ranks if rank <= rank_threshold)
  561. hotness_ratio = high_rank_count / len(ranks) if ranks else 0
  562. hotness_weight = hotness_ratio * 100
  563. # 综合权重计算
  564. total_weight = (
  565. rank_weight * weight_config["RANK_WEIGHT"]
  566. + frequency_weight * weight_config["FREQUENCY_WEIGHT"]
  567. + hotness_weight * weight_config["HOTNESS_WEIGHT"]
  568. )
  569. return total_weight
  570. @staticmethod
  571. def sort_titles_by_weight(
  572. titles_list: List[Dict], rank_threshold: int = CONFIG["RANK_THRESHOLD"]
  573. ) -> List[Dict]:
  574. """按权重对新闻标题列表进行排序"""
  575. def get_sort_key(title_data):
  576. weight = StatisticsCalculator.calculate_news_weight(
  577. title_data, rank_threshold
  578. )
  579. ranks = title_data.get("ranks", [])
  580. count = title_data.get("count", 1)
  581. # 主要按权重排序,权重相同时按最高排名排序,再相同时按出现次数排序
  582. min_rank = min(ranks) if ranks else 999
  583. return (-weight, min_rank, -count)
  584. return sorted(titles_list, key=get_sort_key)
  585. @staticmethod
  586. def _matches_word_groups(
  587. title: str, word_groups: List[Dict], filter_words: List[str]
  588. ) -> bool:
  589. """检查标题是否匹配词组规则"""
  590. title_lower = title.lower()
  591. # 过滤词检查
  592. if any(filter_word.lower() in title_lower for filter_word in filter_words):
  593. return False
  594. # 词组匹配检查
  595. for group in word_groups:
  596. required_words = group["required"]
  597. normal_words = group["normal"]
  598. # 必须词检查
  599. if required_words:
  600. all_required_present = all(
  601. req_word.lower() in title_lower for req_word in required_words
  602. )
  603. if not all_required_present:
  604. continue
  605. # 普通词检查
  606. if normal_words:
  607. any_normal_present = any(
  608. normal_word.lower() in title_lower for normal_word in normal_words
  609. )
  610. if not any_normal_present:
  611. continue
  612. return True
  613. return False
  614. @staticmethod
  615. def count_word_frequency(
  616. results: Dict,
  617. word_groups: List[Dict],
  618. filter_words: List[str],
  619. id_to_alias: Dict,
  620. title_info: Optional[Dict] = None,
  621. rank_threshold: int = CONFIG["RANK_THRESHOLD"],
  622. new_titles: Optional[Dict] = None,
  623. ) -> Tuple[List[Dict], int]:
  624. """统计词频,支持必须词、频率词、过滤词,并标记新增标题"""
  625. word_stats = {}
  626. total_titles = 0
  627. processed_titles = {}
  628. if title_info is None:
  629. title_info = {}
  630. if new_titles is None:
  631. new_titles = {}
  632. for group in word_groups:
  633. group_key = group["group_key"]
  634. word_stats[group_key] = {"count": 0, "titles": {}}
  635. for source_id, titles_data in results.items():
  636. total_titles += len(titles_data)
  637. if source_id not in processed_titles:
  638. processed_titles[source_id] = {}
  639. for title, title_data in titles_data.items():
  640. if title in processed_titles.get(source_id, {}):
  641. continue
  642. # 使用统一的匹配逻辑
  643. if not StatisticsCalculator._matches_word_groups(
  644. title, word_groups, filter_words
  645. ):
  646. continue
  647. source_ranks = title_data.get("ranks", [])
  648. source_url = title_data.get("url", "")
  649. source_mobile_url = title_data.get("mobileUrl", "")
  650. # 找到匹配的词组
  651. title_lower = title.lower()
  652. for group in word_groups:
  653. required_words = group["required"]
  654. normal_words = group["normal"]
  655. # 再次检查匹配
  656. if required_words:
  657. all_required_present = all(
  658. req_word.lower() in title_lower
  659. for req_word in required_words
  660. )
  661. if not all_required_present:
  662. continue
  663. if normal_words:
  664. any_normal_present = any(
  665. normal_word.lower() in title_lower
  666. for normal_word in normal_words
  667. )
  668. if not any_normal_present:
  669. continue
  670. group_key = group["group_key"]
  671. word_stats[group_key]["count"] += 1
  672. if source_id not in word_stats[group_key]["titles"]:
  673. word_stats[group_key]["titles"][source_id] = []
  674. first_time = ""
  675. last_time = ""
  676. count_info = 1
  677. ranks = source_ranks if source_ranks else []
  678. url = source_url
  679. mobile_url = source_mobile_url
  680. if (
  681. title_info
  682. and source_id in title_info
  683. and title in title_info[source_id]
  684. ):
  685. info = title_info[source_id][title]
  686. first_time = info.get("first_time", "")
  687. last_time = info.get("last_time", "")
  688. count_info = info.get("count", 1)
  689. if "ranks" in info and info["ranks"]:
  690. ranks = info["ranks"]
  691. url = info.get("url", source_url)
  692. mobile_url = info.get("mobileUrl", source_mobile_url)
  693. if not ranks:
  694. ranks = [99]
  695. time_display = StatisticsCalculator._format_time_display(
  696. first_time, last_time
  697. )
  698. source_alias = id_to_alias.get(source_id, source_id)
  699. is_new = source_id in new_titles and title in new_titles[source_id]
  700. word_stats[group_key]["titles"][source_id].append(
  701. {
  702. "title": title,
  703. "source_alias": source_alias,
  704. "first_time": first_time,
  705. "last_time": last_time,
  706. "time_display": time_display,
  707. "count": count_info,
  708. "ranks": ranks,
  709. "rank_threshold": rank_threshold,
  710. "url": url,
  711. "mobileUrl": mobile_url,
  712. "is_new": is_new,
  713. }
  714. )
  715. if source_id not in processed_titles:
  716. processed_titles[source_id] = {}
  717. processed_titles[source_id][title] = True
  718. break
  719. stats = []
  720. for group_key, data in word_stats.items():
  721. all_titles = []
  722. for source_id, title_list in data["titles"].items():
  723. all_titles.extend(title_list)
  724. # 按权重排序标题
  725. sorted_titles = StatisticsCalculator.sort_titles_by_weight(
  726. all_titles, rank_threshold
  727. )
  728. stats.append(
  729. {
  730. "word": group_key,
  731. "count": data["count"],
  732. "titles": sorted_titles,
  733. "percentage": (
  734. round(data["count"] / total_titles * 100, 2)
  735. if total_titles > 0
  736. else 0
  737. ),
  738. }
  739. )
  740. stats.sort(key=lambda x: x["count"], reverse=True)
  741. return stats, total_titles
  742. @staticmethod
  743. def _format_rank_base(
  744. ranks: List[int], rank_threshold: int = 5, format_type: str = "html"
  745. ) -> str:
  746. """基础排名格式化方法"""
  747. if not ranks:
  748. return ""
  749. unique_ranks = sorted(set(ranks))
  750. min_rank = unique_ranks[0]
  751. max_rank = unique_ranks[-1]
  752. # 根据格式类型选择不同的标记方式
  753. if format_type == "html":
  754. highlight_start = "<font color='red'><strong>"
  755. highlight_end = "</strong></font>"
  756. elif format_type == "feishu":
  757. highlight_start = "<font color='red'>**"
  758. highlight_end = "**</font>"
  759. elif format_type == "dingtalk":
  760. highlight_start = "**"
  761. highlight_end = "**"
  762. elif format_type == "wework":
  763. highlight_start = "**"
  764. highlight_end = "**"
  765. elif format_type == "telegram":
  766. highlight_start = "<b>"
  767. highlight_end = "</b>"
  768. else:
  769. highlight_start = "**"
  770. highlight_end = "**"
  771. # 格式化排名显示
  772. if min_rank <= rank_threshold:
  773. if min_rank == max_rank:
  774. return f"{highlight_start}[{min_rank}]{highlight_end}"
  775. else:
  776. return f"{highlight_start}[{min_rank} - {max_rank}]{highlight_end}"
  777. else:
  778. if min_rank == max_rank:
  779. return f"[{min_rank}]"
  780. else:
  781. return f"[{min_rank} - {max_rank}]"
  782. @staticmethod
  783. def _format_rank_for_html(ranks: List[int], rank_threshold: int = 5) -> str:
  784. """格式化HTML排名显示"""
  785. return StatisticsCalculator._format_rank_base(ranks, rank_threshold, "html")
  786. @staticmethod
  787. def _format_rank_for_feishu(ranks: List[int], rank_threshold: int = 5) -> str:
  788. """格式化飞书排名显示"""
  789. return StatisticsCalculator._format_rank_base(ranks, rank_threshold, "feishu")
  790. @staticmethod
  791. def _format_rank_for_dingtalk(ranks: List[int], rank_threshold: int = 5) -> str:
  792. """格式化钉钉排名显示"""
  793. return StatisticsCalculator._format_rank_base(ranks, rank_threshold, "dingtalk")
  794. @staticmethod
  795. def _format_rank_for_wework(ranks: List[int], rank_threshold: int = 5) -> str:
  796. """格式化企业微信排名显示"""
  797. return StatisticsCalculator._format_rank_base(ranks, rank_threshold, "wework")
  798. @staticmethod
  799. def _format_rank_for_telegram(ranks: List[int], rank_threshold: int = 5) -> str:
  800. """格式化Telegram排名显示"""
  801. return StatisticsCalculator._format_rank_base(ranks, rank_threshold, "telegram")
  802. @staticmethod
  803. def _format_time_display(first_time: str, last_time: str) -> str:
  804. """格式化时间显示"""
  805. if not first_time:
  806. return ""
  807. if first_time == last_time or not last_time:
  808. return first_time
  809. else:
  810. return f"[{first_time} ~ {last_time}]"
  811. class ReportGenerator:
  812. """报告生成器"""
  813. @staticmethod
  814. def generate_html_report(
  815. stats: List[Dict],
  816. total_titles: int,
  817. failed_ids: Optional[List] = None,
  818. is_daily: bool = False,
  819. new_titles: Optional[Dict] = None,
  820. id_to_alias: Optional[Dict] = None,
  821. ) -> str:
  822. """生成HTML报告"""
  823. if is_daily:
  824. filename = "当日统计.html"
  825. else:
  826. filename = f"{TimeHelper.format_time_filename()}.html"
  827. file_path = FileHelper.get_output_path("html", filename)
  828. # 数据处理层
  829. report_data = ReportGenerator._prepare_report_data(
  830. stats, failed_ids, new_titles, id_to_alias
  831. )
  832. # 渲染层
  833. html_content = ReportGenerator._render_html_content(
  834. report_data, total_titles, is_daily
  835. )
  836. with open(file_path, "w", encoding="utf-8") as f:
  837. f.write(html_content)
  838. if is_daily:
  839. root_file_path = Path("index.html")
  840. with open(root_file_path, "w", encoding="utf-8") as f:
  841. f.write(html_content)
  842. return file_path
  843. @staticmethod
  844. def _prepare_report_data(
  845. stats: List[Dict],
  846. failed_ids: Optional[List] = None,
  847. new_titles: Optional[Dict] = None,
  848. id_to_alias: Optional[Dict] = None,
  849. ) -> Dict:
  850. """准备报告数据"""
  851. filtered_new_titles = {}
  852. if new_titles and id_to_alias:
  853. word_groups, filter_words = DataProcessor.load_frequency_words()
  854. for source_id, titles_data in new_titles.items():
  855. filtered_titles = ReportGenerator._apply_frequency_filter(
  856. titles_data, word_groups, filter_words
  857. )
  858. if filtered_titles:
  859. filtered_new_titles[source_id] = filtered_titles
  860. processed_stats = []
  861. for stat in stats:
  862. if stat["count"] <= 0:
  863. continue
  864. processed_titles = []
  865. for title_data in stat["titles"]:
  866. processed_title = {
  867. "title": title_data["title"],
  868. "source_alias": title_data["source_alias"],
  869. "time_display": title_data["time_display"],
  870. "count": title_data["count"],
  871. "ranks": title_data["ranks"],
  872. "rank_threshold": title_data["rank_threshold"],
  873. "url": title_data.get("url", ""),
  874. "mobile_url": title_data.get("mobileUrl", ""),
  875. "is_new": title_data.get("is_new", False),
  876. }
  877. processed_titles.append(processed_title)
  878. processed_stats.append(
  879. {
  880. "word": stat["word"],
  881. "count": stat["count"],
  882. "percentage": stat.get("percentage", 0),
  883. "titles": processed_titles,
  884. }
  885. )
  886. processed_new_titles = []
  887. if filtered_new_titles and id_to_alias:
  888. for source_id, titles_data in filtered_new_titles.items():
  889. source_alias = id_to_alias.get(source_id, source_id)
  890. source_titles = []
  891. for title, title_data in titles_data.items():
  892. url, mobile_url, ranks = ReportGenerator._extract_title_data_fields(
  893. title_data
  894. )
  895. processed_title = {
  896. "title": title,
  897. "source_alias": source_alias,
  898. "time_display": "",
  899. "count": 1,
  900. "ranks": ranks,
  901. "rank_threshold": CONFIG["RANK_THRESHOLD"],
  902. "url": url,
  903. "mobile_url": mobile_url,
  904. "is_new": True,
  905. }
  906. source_titles.append(processed_title)
  907. if source_titles:
  908. processed_new_titles.append(
  909. {
  910. "source_id": source_id,
  911. "source_alias": source_alias,
  912. "titles": source_titles,
  913. }
  914. )
  915. return {
  916. "stats": processed_stats,
  917. "new_titles": processed_new_titles,
  918. "failed_ids": failed_ids or [],
  919. "total_new_count": sum(
  920. len(source["titles"]) for source in processed_new_titles
  921. ),
  922. }
  923. @staticmethod
  924. def _extract_title_data_fields(title_data) -> Tuple[str, str, List[int]]:
  925. """提取标题数据的通用字段"""
  926. url = title_data.get("url", "")
  927. mobile_url = title_data.get("mobileUrl", "")
  928. ranks = title_data.get("ranks", [])
  929. return url, mobile_url, ranks
  930. @staticmethod
  931. def _apply_frequency_filter(
  932. titles_data: Dict, word_groups: List[Dict], filter_words: List[str]
  933. ) -> Dict:
  934. """应用频率词过滤逻辑"""
  935. filtered_titles = {}
  936. for title, title_data in titles_data.items():
  937. if StatisticsCalculator._matches_word_groups(
  938. title, word_groups, filter_words
  939. ):
  940. filtered_titles[title] = title_data
  941. return filtered_titles
  942. @staticmethod
  943. def _html_escape(text: str) -> str:
  944. """HTML转义"""
  945. if not isinstance(text, str):
  946. text = str(text)
  947. return (
  948. text.replace("&", "&amp;")
  949. .replace("<", "&lt;")
  950. .replace(">", "&gt;")
  951. .replace('"', "&quot;")
  952. .replace("'", "&#x27;")
  953. )
  954. @staticmethod
  955. def _format_title_html(title_data: Dict) -> str:
  956. """格式化HTML标题显示"""
  957. rank_display = StatisticsCalculator._format_rank_for_html(
  958. title_data["ranks"], title_data["rank_threshold"]
  959. )
  960. link_url = title_data["mobile_url"] or title_data["url"]
  961. escaped_title = ReportGenerator._html_escape(title_data["title"])
  962. escaped_source_alias = ReportGenerator._html_escape(title_data["source_alias"])
  963. if link_url:
  964. escaped_url = ReportGenerator._html_escape(link_url)
  965. formatted_title = f'[{escaped_source_alias}] <a href="{escaped_url}" target="_blank" class="news-link">{escaped_title}</a>'
  966. else:
  967. formatted_title = (
  968. f'[{escaped_source_alias}] <span class="no-link">{escaped_title}</span>'
  969. )
  970. if rank_display:
  971. formatted_title += f" {rank_display}"
  972. if title_data["time_display"]:
  973. escaped_time = ReportGenerator._html_escape(title_data["time_display"])
  974. formatted_title += f" <font color='grey'>- {escaped_time}</font>"
  975. if title_data["count"] > 1:
  976. formatted_title += f" <font color='green'>({title_data['count']}次)</font>"
  977. if title_data["is_new"]:
  978. formatted_title = f"<div class='new-title'>🆕 {formatted_title}</div>"
  979. return formatted_title
  980. @staticmethod
  981. def _render_html_content(
  982. report_data: Dict, total_titles: int, is_daily: bool = False
  983. ) -> str:
  984. """渲染HTML内容"""
  985. html = """
  986. <!DOCTYPE html>
  987. <html>
  988. <head>
  989. <meta charset="UTF-8">
  990. <title>频率词统计报告</title>
  991. <style>
  992. body { font-family: Arial, sans-serif; margin: 20px; }
  993. h1, h2 { color: #333; }
  994. table { border-collapse: collapse; width: 100%; margin-top: 20px; }
  995. th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
  996. th { background-color: #f2f2f2; }
  997. tr:nth-child(even) { background-color: #f9f9f9; }
  998. .word { font-weight: bold; }
  999. .count { text-align: center; }
  1000. .percentage { text-align: center; }
  1001. .titles { max-width: 500px; }
  1002. .source { color: #666; font-style: italic; }
  1003. .error { color: #d9534f; }
  1004. .news-link {
  1005. color: #007bff;
  1006. text-decoration: none;
  1007. border-bottom: 1px dotted #007bff;
  1008. }
  1009. .news-link:hover {
  1010. color: #0056b3;
  1011. text-decoration: underline;
  1012. }
  1013. .news-link:visited {
  1014. color: #6f42c1;
  1015. }
  1016. .no-link {
  1017. color: #333;
  1018. }
  1019. .new-title {
  1020. background-color: #fff3cd;
  1021. border: 1px solid #ffc107;
  1022. border-radius: 3px;
  1023. padding: 2px 6px;
  1024. margin: 2px 0;
  1025. }
  1026. .new-section {
  1027. background-color: #d1ecf1;
  1028. border: 1px solid #bee5eb;
  1029. border-radius: 5px;
  1030. padding: 10px;
  1031. margin-top: 10px;
  1032. }
  1033. .new-section h3 {
  1034. color: #0c5460;
  1035. margin-top: 0;
  1036. }
  1037. </style>
  1038. </head>
  1039. <body>
  1040. <h1>频率词统计报告</h1>
  1041. """
  1042. if is_daily:
  1043. html += "<p>报告类型: 当日汇总</p>"
  1044. now = TimeHelper.get_beijing_time()
  1045. html += f"<p>总标题数: {total_titles}</p>"
  1046. html += f"<p>生成时间: {now.strftime('%Y-%m-%d %H:%M:%S')}</p>"
  1047. # 渲染失败平台
  1048. if report_data["failed_ids"]:
  1049. html += """
  1050. <div class="error">
  1051. <h2>请求失败的平台</h2>
  1052. <ul>
  1053. """
  1054. for id_value in report_data["failed_ids"]:
  1055. html += f"<li>{ReportGenerator._html_escape(id_value)}</li>"
  1056. html += """
  1057. </ul>
  1058. </div>
  1059. """
  1060. # 渲染统计表格
  1061. html += """
  1062. <table>
  1063. <tr>
  1064. <th>排名</th>
  1065. <th>频率词</th>
  1066. <th>出现次数</th>
  1067. <th>占比</th>
  1068. <th>相关标题</th>
  1069. </tr>
  1070. """
  1071. for i, stat in enumerate(report_data["stats"], 1):
  1072. formatted_titles = []
  1073. for title_data in stat["titles"]:
  1074. formatted_title = ReportGenerator._format_title_html(title_data)
  1075. formatted_titles.append(formatted_title)
  1076. escaped_word = ReportGenerator._html_escape(stat["word"])
  1077. html += f"""
  1078. <tr>
  1079. <td>{i}</td>
  1080. <td class="word">{escaped_word}</td>
  1081. <td class="count">{stat['count']}</td>
  1082. <td class="percentage">{stat.get('percentage', 0)}%</td>
  1083. <td class="titles">{"<br>".join(formatted_titles)}</td>
  1084. </tr>
  1085. """
  1086. html += """
  1087. </table>
  1088. """
  1089. # 渲染新增新闻部分
  1090. if report_data["new_titles"]:
  1091. html += f"""
  1092. <div class="new-section">
  1093. <h3>🆕 本次新增热点新闻 (共 {report_data['total_new_count']} 条)</h3>
  1094. """
  1095. for source_data in report_data["new_titles"]:
  1096. escaped_source = ReportGenerator._html_escape(
  1097. source_data["source_alias"]
  1098. )
  1099. html += (
  1100. f"<h4>{escaped_source} ({len(source_data['titles'])} 条)</h4><ul>"
  1101. )
  1102. for title_data in source_data["titles"]:
  1103. title_data_copy = title_data.copy()
  1104. title_data_copy["is_new"] = False
  1105. formatted_title = ReportGenerator._format_title_html(
  1106. title_data_copy
  1107. )
  1108. # 移除来源标签
  1109. if "] " in formatted_title:
  1110. formatted_title = formatted_title.split("] ", 1)[1]
  1111. html += f"<li>{formatted_title}</li>"
  1112. html += "</ul>"
  1113. html += "</div>"
  1114. html += """
  1115. </body>
  1116. </html>
  1117. """
  1118. return html
  1119. @staticmethod
  1120. def _format_title_feishu(title_data: Dict, show_source: bool = True) -> str:
  1121. """格式化飞书标题显示"""
  1122. rank_display = StatisticsCalculator._format_rank_for_feishu(
  1123. title_data["ranks"], title_data["rank_threshold"]
  1124. )
  1125. link_url = title_data["mobile_url"] or title_data["url"]
  1126. if link_url:
  1127. formatted_title = f"[{title_data['title']}]({link_url})"
  1128. else:
  1129. formatted_title = title_data["title"]
  1130. title_prefix = "🆕 " if title_data["is_new"] else ""
  1131. if show_source:
  1132. result = f"<font color='grey'>[{title_data['source_alias']}]</font> {title_prefix}{formatted_title}"
  1133. else:
  1134. result = f"{title_prefix}{formatted_title}"
  1135. if rank_display:
  1136. result += f" {rank_display}"
  1137. if title_data["time_display"]:
  1138. result += f" <font color='grey'>- {title_data['time_display']}</font>"
  1139. if title_data["count"] > 1:
  1140. result += f" <font color='green'>({title_data['count']}次)</font>"
  1141. return result
  1142. @staticmethod
  1143. def _format_title_dingtalk(title_data: Dict, show_source: bool = True) -> str:
  1144. """格式化钉钉标题显示"""
  1145. rank_display = StatisticsCalculator._format_rank_for_dingtalk(
  1146. title_data["ranks"], title_data["rank_threshold"]
  1147. )
  1148. link_url = title_data["mobile_url"] or title_data["url"]
  1149. if link_url:
  1150. formatted_title = f"[{title_data['title']}]({link_url})"
  1151. else:
  1152. formatted_title = title_data["title"]
  1153. title_prefix = "🆕 " if title_data["is_new"] else ""
  1154. if show_source:
  1155. result = f"[{title_data['source_alias']}] {title_prefix}{formatted_title}"
  1156. else:
  1157. result = f"{title_prefix}{formatted_title}"
  1158. if rank_display:
  1159. result += f" {rank_display}"
  1160. if title_data["time_display"]:
  1161. result += f" - {title_data['time_display']}"
  1162. if title_data["count"] > 1:
  1163. result += f" ({title_data['count']}次)"
  1164. return result
  1165. @staticmethod
  1166. def _format_title_wework(title_data: Dict, show_source: bool = True) -> str:
  1167. """格式化企业微信标题显示"""
  1168. rank_display = StatisticsCalculator._format_rank_for_wework(
  1169. title_data["ranks"], title_data["rank_threshold"]
  1170. )
  1171. link_url = title_data["mobile_url"] or title_data["url"]
  1172. if link_url:
  1173. formatted_title = f"[{title_data['title']}]({link_url})"
  1174. else:
  1175. formatted_title = title_data["title"]
  1176. title_prefix = "🆕 " if title_data["is_new"] else ""
  1177. if show_source:
  1178. result = f"[{title_data['source_alias']}] {title_prefix}{formatted_title}"
  1179. else:
  1180. result = f"{title_prefix}{formatted_title}"
  1181. if rank_display:
  1182. result += f" {rank_display}"
  1183. if title_data["time_display"]:
  1184. result += f" - {title_data['time_display']}"
  1185. if title_data["count"] > 1:
  1186. result += f" ({title_data['count']}次)"
  1187. return result
  1188. @staticmethod
  1189. def _format_title_telegram(title_data: Dict, show_source: bool = True) -> str:
  1190. """格式化Telegram标题显示"""
  1191. rank_display = StatisticsCalculator._format_rank_for_telegram(
  1192. title_data["ranks"], title_data["rank_threshold"]
  1193. )
  1194. link_url = title_data["mobile_url"] or title_data["url"]
  1195. if link_url:
  1196. formatted_title = f'<a href="{link_url}">{ReportGenerator._html_escape(title_data["title"])}</a>'
  1197. else:
  1198. formatted_title = title_data["title"]
  1199. title_prefix = "🆕 " if title_data["is_new"] else ""
  1200. if show_source:
  1201. result = f"[{title_data['source_alias']}] {title_prefix}{formatted_title}"
  1202. else:
  1203. result = f"{title_prefix}{formatted_title}"
  1204. if rank_display:
  1205. result += f" {rank_display}"
  1206. if title_data["time_display"]:
  1207. result += f" <code>- {title_data['time_display']}</code>"
  1208. if title_data["count"] > 1:
  1209. result += f" <code>({title_data['count']}次)</code>"
  1210. return result
  1211. @staticmethod
  1212. def _render_feishu_content(
  1213. report_data: Dict, update_info: Optional[Dict] = None
  1214. ) -> str:
  1215. """渲染飞书内容"""
  1216. text_content = ""
  1217. # 渲染热点词汇统计
  1218. if report_data["stats"]:
  1219. text_content += "📊 **热点词汇统计**\n\n"
  1220. total_count = len(report_data["stats"])
  1221. for i, stat in enumerate(report_data["stats"]):
  1222. word = stat["word"]
  1223. count = stat["count"]
  1224. sequence_display = f"<font color='grey'>[{i + 1}/{total_count}]</font>"
  1225. if count >= 10:
  1226. text_content += f"🔥 {sequence_display} **{word}** : <font color='red'>{count}</font> 条\n\n"
  1227. elif count >= 5:
  1228. text_content += f"📈 {sequence_display} **{word}** : <font color='orange'>{count}</font> 条\n\n"
  1229. else:
  1230. text_content += f"📌 {sequence_display} **{word}** : {count} 条\n\n"
  1231. for j, title_data in enumerate(stat["titles"], 1):
  1232. formatted_title = ReportGenerator._format_title_feishu(
  1233. title_data, show_source=True
  1234. )
  1235. text_content += f" {j}. {formatted_title}\n"
  1236. if j < len(stat["titles"]):
  1237. text_content += "\n"
  1238. if i < len(report_data["stats"]) - 1:
  1239. text_content += f"\n{CONFIG['FEISHU_MESSAGE_SEPARATOR']}\n\n"
  1240. if not text_content:
  1241. text_content = "📭 暂无匹配的热点词汇\n\n"
  1242. # 渲染新增新闻部分
  1243. if report_data["new_titles"]:
  1244. if text_content and "暂无匹配" not in text_content:
  1245. text_content += f"\n{CONFIG['FEISHU_MESSAGE_SEPARATOR']}\n\n"
  1246. text_content += (
  1247. f"🆕 **本次新增热点新闻** (共 {report_data['total_new_count']} 条)\n\n"
  1248. )
  1249. for source_data in report_data["new_titles"]:
  1250. text_content += f"**{source_data['source_alias']}** ({len(source_data['titles'])} 条):\n"
  1251. for j, title_data in enumerate(source_data["titles"], 1):
  1252. title_data_copy = title_data.copy()
  1253. title_data_copy["is_new"] = False
  1254. formatted_title = ReportGenerator._format_title_feishu(
  1255. title_data_copy, show_source=False
  1256. )
  1257. text_content += f" {j}. {formatted_title}\n"
  1258. text_content += "\n"
  1259. # 渲染失败平台
  1260. if report_data["failed_ids"]:
  1261. if text_content and "暂无匹配" not in text_content:
  1262. text_content += f"\n{CONFIG['FEISHU_MESSAGE_SEPARATOR']}\n\n"
  1263. text_content += "⚠️ **数据获取失败的平台:**\n\n"
  1264. for i, id_value in enumerate(report_data["failed_ids"], 1):
  1265. text_content += f" • <font color='red'>{id_value}</font>\n"
  1266. # 添加时间戳
  1267. now = TimeHelper.get_beijing_time()
  1268. text_content += f"\n\n<font color='grey'>更新时间:{now.strftime('%Y-%m-%d %H:%M:%S')}</font>"
  1269. # 版本更新提示
  1270. if update_info:
  1271. text_content += f"\n<font color='grey'>TrendRadar 发现新版本 {update_info['remote_version']},当前 {update_info['current_version']}</font>"
  1272. return text_content
  1273. @staticmethod
  1274. def _render_dingtalk_content(
  1275. report_data: Dict, update_info: Optional[Dict] = None
  1276. ) -> str:
  1277. """渲染钉钉内容"""
  1278. text_content = ""
  1279. # 计算总标题数
  1280. total_titles = sum(
  1281. len(stat["titles"]) for stat in report_data["stats"] if stat["count"] > 0
  1282. )
  1283. now = TimeHelper.get_beijing_time()
  1284. # 顶部统计信息
  1285. text_content += f"**总新闻数:** {total_titles}\n\n"
  1286. text_content += f"**时间:** {now.strftime('%Y-%m-%d %H:%M:%S')}\n\n"
  1287. text_content += f"**类型:** 热点分析报告\n\n"
  1288. text_content += "---\n\n"
  1289. # 渲染热点词汇统计
  1290. if report_data["stats"]:
  1291. text_content += "📊 **热点词汇统计**\n\n"
  1292. total_count = len(report_data["stats"])
  1293. for i, stat in enumerate(report_data["stats"]):
  1294. word = stat["word"]
  1295. count = stat["count"]
  1296. sequence_display = f"[{i + 1}/{total_count}]"
  1297. if count >= 10:
  1298. text_content += (
  1299. f"🔥 {sequence_display} **{word}** : **{count}** 条\n\n"
  1300. )
  1301. elif count >= 5:
  1302. text_content += (
  1303. f"📈 {sequence_display} **{word}** : **{count}** 条\n\n"
  1304. )
  1305. else:
  1306. text_content += f"📌 {sequence_display} **{word}** : {count} 条\n\n"
  1307. for j, title_data in enumerate(stat["titles"], 1):
  1308. formatted_title = ReportGenerator._format_title_dingtalk(
  1309. title_data, show_source=True
  1310. )
  1311. text_content += f" {j}. {formatted_title}\n"
  1312. if j < len(stat["titles"]):
  1313. text_content += "\n"
  1314. if i < len(report_data["stats"]) - 1:
  1315. text_content += f"\n---\n\n"
  1316. if not report_data["stats"]:
  1317. text_content += "📭 暂无匹配的热点词汇\n\n"
  1318. # 渲染新增新闻部分
  1319. if report_data["new_titles"]:
  1320. if text_content and "暂无匹配" not in text_content:
  1321. text_content += f"\n---\n\n"
  1322. text_content += (
  1323. f"🆕 **本次新增热点新闻** (共 {report_data['total_new_count']} 条)\n\n"
  1324. )
  1325. for source_data in report_data["new_titles"]:
  1326. text_content += f"**{source_data['source_alias']}** ({len(source_data['titles'])} 条):\n\n"
  1327. for j, title_data in enumerate(source_data["titles"], 1):
  1328. title_data_copy = title_data.copy()
  1329. title_data_copy["is_new"] = False
  1330. formatted_title = ReportGenerator._format_title_dingtalk(
  1331. title_data_copy, show_source=False
  1332. )
  1333. text_content += f" {j}. {formatted_title}\n"
  1334. text_content += "\n"
  1335. # 渲染失败平台
  1336. if report_data["failed_ids"]:
  1337. if text_content and "暂无匹配" not in text_content:
  1338. text_content += f"\n---\n\n"
  1339. text_content += "⚠️ **数据获取失败的平台:**\n\n"
  1340. for i, id_value in enumerate(report_data["failed_ids"], 1):
  1341. text_content += f" • **{id_value}**\n"
  1342. # 添加时间戳
  1343. text_content += f"\n\n> 更新时间:{now.strftime('%Y-%m-%d %H:%M:%S')}"
  1344. # 版本更新提示
  1345. if update_info:
  1346. text_content += f"\n> TrendRadar 发现新版本 **{update_info['remote_version']}**,当前 **{update_info['current_version']}**"
  1347. return text_content
  1348. @staticmethod
  1349. def _render_wework_content(
  1350. report_data: Dict, update_info: Optional[Dict] = None
  1351. ) -> str:
  1352. """渲染企业微信内容"""
  1353. text_content = ""
  1354. # 计算总标题数
  1355. total_titles = sum(
  1356. len(stat["titles"]) for stat in report_data["stats"] if stat["count"] > 0
  1357. )
  1358. now = TimeHelper.get_beijing_time()
  1359. # 顶部统计信息
  1360. text_content += f"**总新闻数:** {total_titles}\n\n"
  1361. text_content += f"**时间:** {now.strftime('%Y-%m-%d %H:%M:%S')}\n\n"
  1362. text_content += f"**类型:** 热点分析报告\n\n\n\n"
  1363. # 渲染热点词汇统计
  1364. if report_data["stats"]:
  1365. text_content += "📊 **热点词汇统计**\n\n"
  1366. total_count = len(report_data["stats"])
  1367. for i, stat in enumerate(report_data["stats"]):
  1368. word = stat["word"]
  1369. count = stat["count"]
  1370. sequence_display = f"[{i + 1}/{total_count}]"
  1371. if count >= 10:
  1372. text_content += (
  1373. f"🔥 {sequence_display} **{word}** : **{count}** 条\n\n"
  1374. )
  1375. elif count >= 5:
  1376. text_content += (
  1377. f"📈 {sequence_display} **{word}** : **{count}** 条\n\n"
  1378. )
  1379. else:
  1380. text_content += f"📌 {sequence_display} **{word}** : {count} 条\n\n"
  1381. for j, title_data in enumerate(stat["titles"], 1):
  1382. formatted_title = ReportGenerator._format_title_wework(
  1383. title_data, show_source=True
  1384. )
  1385. text_content += f" {j}. {formatted_title}\n"
  1386. if j < len(stat["titles"]):
  1387. text_content += "\n"
  1388. if i < len(report_data["stats"]) - 1:
  1389. text_content += f"\n\n\n\n"
  1390. if not report_data["stats"]:
  1391. text_content += "📭 暂无匹配的热点词汇\n\n"
  1392. # 渲染新增新闻部分
  1393. if report_data["new_titles"]:
  1394. if text_content and "暂无匹配" not in text_content:
  1395. text_content += f"\n\n\n\n"
  1396. text_content += (
  1397. f"🆕 **本次新增热点新闻** (共 {report_data['total_new_count']} 条)\n\n"
  1398. )
  1399. for source_data in report_data["new_titles"]:
  1400. text_content += f"**{source_data['source_alias']}** ({len(source_data['titles'])} 条):\n\n"
  1401. for j, title_data in enumerate(source_data["titles"], 1):
  1402. title_data_copy = title_data.copy()
  1403. title_data_copy["is_new"] = False
  1404. formatted_title = ReportGenerator._format_title_wework(
  1405. title_data_copy, show_source=False
  1406. )
  1407. text_content += f" {j}. {formatted_title}\n"
  1408. text_content += "\n"
  1409. # 渲染失败平台
  1410. if report_data["failed_ids"]:
  1411. if text_content and "暂无匹配" not in text_content:
  1412. text_content += f"\n\n\n\n"
  1413. text_content += "⚠️ **数据获取失败的平台:**\n\n"
  1414. for i, id_value in enumerate(report_data["failed_ids"], 1):
  1415. text_content += f" • {id_value}\n"
  1416. # 添加时间戳
  1417. text_content += f"\n\n\n> 更新时间:{now.strftime('%Y-%m-%d %H:%M:%S')}"
  1418. # 版本更新提示
  1419. if update_info:
  1420. text_content += f"\n> TrendRadar 发现新版本 **{update_info['remote_version']}**,当前 **{update_info['current_version']}**"
  1421. return text_content
  1422. @staticmethod
  1423. def _render_telegram_content(
  1424. report_data: Dict, update_info: Optional[Dict] = None
  1425. ) -> str:
  1426. """渲染Telegram内容"""
  1427. text_content = ""
  1428. # 计算总标题数
  1429. total_titles = sum(
  1430. len(stat["titles"]) for stat in report_data["stats"] if stat["count"] > 0
  1431. )
  1432. now = TimeHelper.get_beijing_time()
  1433. # 顶部统计信息
  1434. text_content += f"总新闻数: {total_titles}\n"
  1435. text_content += f"时间: {now.strftime('%Y-%m-%d %H:%M:%S')}\n"
  1436. text_content += f"类型: 热点分析报告\n\n"
  1437. # 渲染热点词汇统计
  1438. if report_data["stats"]:
  1439. text_content += "📊 热点词汇统计\n\n"
  1440. total_count = len(report_data["stats"])
  1441. for i, stat in enumerate(report_data["stats"]):
  1442. word = stat["word"]
  1443. count = stat["count"]
  1444. sequence_display = f"[{i + 1}/{total_count}]"
  1445. if count >= 10:
  1446. text_content += f"🔥 {sequence_display} {word} : {count} 条\n\n"
  1447. elif count >= 5:
  1448. text_content += f"📈 {sequence_display} {word} : {count} 条\n\n"
  1449. else:
  1450. text_content += f"📌 {sequence_display} {word} : {count} 条\n\n"
  1451. for j, title_data in enumerate(stat["titles"], 1):
  1452. formatted_title = ReportGenerator._format_title_telegram(
  1453. title_data, show_source=True
  1454. )
  1455. text_content += f" {j}. {formatted_title}\n"
  1456. if j < len(stat["titles"]):
  1457. text_content += "\n"
  1458. if i < len(report_data["stats"]) - 1:
  1459. text_content += f"\n\n"
  1460. if not report_data["stats"]:
  1461. text_content += "📭 暂无匹配的热点词汇\n\n"
  1462. # 渲染新增新闻部分
  1463. if report_data["new_titles"]:
  1464. if text_content and "暂无匹配" not in text_content:
  1465. text_content += f"\n\n"
  1466. text_content += (
  1467. f"🆕 本次新增热点新闻 (共 {report_data['total_new_count']} 条)\n\n"
  1468. )
  1469. for source_data in report_data["new_titles"]:
  1470. text_content += f"{source_data['source_alias']} ({len(source_data['titles'])} 条):\n\n"
  1471. for j, title_data in enumerate(source_data["titles"], 1):
  1472. title_data_copy = title_data.copy()
  1473. title_data_copy["is_new"] = False
  1474. formatted_title = ReportGenerator._format_title_telegram(
  1475. title_data_copy, show_source=False
  1476. )
  1477. text_content += f" {j}. {formatted_title}\n"
  1478. text_content += "\n"
  1479. # 渲染失败平台
  1480. if report_data["failed_ids"]:
  1481. if text_content and "暂无匹配" not in text_content:
  1482. text_content += f"\n\n"
  1483. text_content += "⚠️ 数据获取失败的平台:\n\n"
  1484. for i, id_value in enumerate(report_data["failed_ids"], 1):
  1485. text_content += f" • {id_value}\n"
  1486. text_content += f"\n\n更新时间:{now.strftime('%Y-%m-%d %H:%M:%S')}"
  1487. # 版本更新提示
  1488. if update_info:
  1489. text_content += f"\nTrendRadar 发现新版本 {update_info['remote_version']},当前 {update_info['current_version']}"
  1490. return text_content
  1491. @staticmethod
  1492. def send_to_webhooks(
  1493. stats: List[Dict],
  1494. failed_ids: Optional[List] = None,
  1495. report_type: str = "单次爬取",
  1496. new_titles: Optional[Dict] = None,
  1497. id_to_alias: Optional[Dict] = None,
  1498. update_info: Optional[Dict] = None,
  1499. proxy_url: Optional[str] = None,
  1500. ) -> Dict[str, bool]:
  1501. """发送数据到多个webhook平台"""
  1502. results = {}
  1503. # 数据处理层
  1504. report_data = ReportGenerator._prepare_report_data(
  1505. stats, failed_ids, new_titles, id_to_alias
  1506. )
  1507. # 获取环境变量中的webhook配置
  1508. feishu_url = os.environ.get("FEISHU_WEBHOOK_URL", CONFIG["FEISHU_WEBHOOK_URL"])
  1509. dingtalk_url = os.environ.get(
  1510. "DINGTALK_WEBHOOK_URL", CONFIG["DINGTALK_WEBHOOK_URL"]
  1511. )
  1512. wework_url = os.environ.get("WEWORK_WEBHOOK_URL", CONFIG["WEWORK_WEBHOOK_URL"])
  1513. telegram_token = os.environ.get(
  1514. "TELEGRAM_BOT_TOKEN", CONFIG["TELEGRAM_BOT_TOKEN"]
  1515. )
  1516. telegram_chat_id = os.environ.get(
  1517. "TELEGRAM_CHAT_ID", CONFIG["TELEGRAM_CHAT_ID"]
  1518. )
  1519. update_info_to_send = update_info if CONFIG["SHOW_VERSION_UPDATE"] else None
  1520. # 发送到飞书
  1521. if feishu_url:
  1522. results["feishu"] = ReportGenerator._send_to_feishu(
  1523. feishu_url, report_data, report_type, update_info_to_send, proxy_url
  1524. )
  1525. # 发送到钉钉
  1526. if dingtalk_url:
  1527. results["dingtalk"] = ReportGenerator._send_to_dingtalk(
  1528. dingtalk_url, report_data, report_type, update_info_to_send, proxy_url
  1529. )
  1530. # 发送到企业微信
  1531. if wework_url:
  1532. results["wework"] = ReportGenerator._send_to_wework(
  1533. wework_url, report_data, report_type, update_info_to_send, proxy_url
  1534. )
  1535. # 发送到Telegram
  1536. if telegram_token and telegram_chat_id:
  1537. results["telegram"] = ReportGenerator._send_to_telegram(
  1538. telegram_token,
  1539. telegram_chat_id,
  1540. report_data,
  1541. report_type,
  1542. update_info_to_send,
  1543. proxy_url,
  1544. )
  1545. if not results:
  1546. print("未配置任何webhook URL,跳过通知发送")
  1547. return results
  1548. @staticmethod
  1549. def _send_to_feishu(
  1550. webhook_url: str,
  1551. report_data: Dict,
  1552. report_type: str,
  1553. update_info: Optional[Dict] = None,
  1554. proxy_url: Optional[str] = None,
  1555. ) -> bool:
  1556. """发送到飞书"""
  1557. headers = {"Content-Type": "application/json"}
  1558. text_content = ReportGenerator._render_feishu_content(report_data, update_info)
  1559. total_titles = sum(
  1560. len(stat["titles"]) for stat in report_data["stats"] if stat["count"] > 0
  1561. )
  1562. now = TimeHelper.get_beijing_time()
  1563. payload = {
  1564. "msg_type": "text",
  1565. "content": {
  1566. "total_titles": total_titles,
  1567. "timestamp": now.strftime("%Y-%m-%d %H:%M:%S"),
  1568. "report_type": report_type,
  1569. "text": text_content,
  1570. },
  1571. }
  1572. proxies = None
  1573. if proxy_url:
  1574. proxies = {"http": proxy_url, "https": proxy_url}
  1575. try:
  1576. response = requests.post(
  1577. webhook_url, headers=headers, json=payload, proxies=proxies, timeout=30
  1578. )
  1579. if response.status_code == 200:
  1580. print(f"飞书通知发送成功 [{report_type}]")
  1581. return True
  1582. else:
  1583. print(
  1584. f"飞书通知发送失败 [{report_type}],状态码:{response.status_code}"
  1585. )
  1586. return False
  1587. except Exception as e:
  1588. print(f"飞书通知发送出错 [{report_type}]:{e}")
  1589. return False
  1590. @staticmethod
  1591. def _send_to_dingtalk(
  1592. webhook_url: str,
  1593. report_data: Dict,
  1594. report_type: str,
  1595. update_info: Optional[Dict] = None,
  1596. proxy_url: Optional[str] = None,
  1597. ) -> bool:
  1598. """发送到钉钉"""
  1599. headers = {"Content-Type": "application/json"}
  1600. text_content = ReportGenerator._render_dingtalk_content(
  1601. report_data, update_info
  1602. )
  1603. payload = {
  1604. "msgtype": "markdown",
  1605. "markdown": {
  1606. "title": f"TrendRadar 热点分析报告 - {report_type}",
  1607. "text": text_content,
  1608. },
  1609. }
  1610. proxies = None
  1611. if proxy_url:
  1612. proxies = {"http": proxy_url, "https": proxy_url}
  1613. try:
  1614. response = requests.post(
  1615. webhook_url, headers=headers, json=payload, proxies=proxies, timeout=30
  1616. )
  1617. if response.status_code == 200:
  1618. result = response.json()
  1619. if result.get("errcode") == 0:
  1620. print(f"钉钉通知发送成功 [{report_type}]")
  1621. return True
  1622. else:
  1623. print(
  1624. f"钉钉通知发送失败 [{report_type}],错误:{result.get('errmsg')}"
  1625. )
  1626. return False
  1627. else:
  1628. print(
  1629. f"钉钉通知发送失败 [{report_type}],状态码:{response.status_code}"
  1630. )
  1631. return False
  1632. except Exception as e:
  1633. print(f"钉钉通知发送出错 [{report_type}]:{e}")
  1634. return False
  1635. @staticmethod
  1636. def _send_to_wework(
  1637. webhook_url: str,
  1638. report_data: Dict,
  1639. report_type: str,
  1640. update_info: Optional[Dict] = None,
  1641. proxy_url: Optional[str] = None,
  1642. ) -> bool:
  1643. """发送到企业微信"""
  1644. headers = {"Content-Type": "application/json"}
  1645. text_content = ReportGenerator._render_wework_content(report_data, update_info)
  1646. payload = {"msgtype": "markdown", "markdown": {"content": text_content}}
  1647. proxies = None
  1648. if proxy_url:
  1649. proxies = {"http": proxy_url, "https": proxy_url}
  1650. try:
  1651. response = requests.post(
  1652. webhook_url, headers=headers, json=payload, proxies=proxies, timeout=30
  1653. )
  1654. if response.status_code == 200:
  1655. result = response.json()
  1656. if result.get("errcode") == 0:
  1657. print(f"企业微信通知发送成功 [{report_type}]")
  1658. return True
  1659. else:
  1660. print(
  1661. f"企业微信通知发送失败 [{report_type}],错误:{result.get('errmsg')}"
  1662. )
  1663. return False
  1664. else:
  1665. print(
  1666. f"企业微信通知发送失败 [{report_type}],状态码:{response.status_code}"
  1667. )
  1668. return False
  1669. except Exception as e:
  1670. print(f"企业微信通知发送出错 [{report_type}]:{e}")
  1671. return False
  1672. @staticmethod
  1673. def _send_to_telegram(
  1674. bot_token: str,
  1675. chat_id: str,
  1676. report_data: Dict,
  1677. report_type: str,
  1678. update_info: Optional[Dict] = None,
  1679. proxy_url: Optional[str] = None,
  1680. ) -> bool:
  1681. """发送到Telegram"""
  1682. headers = {"Content-Type": "application/json"}
  1683. text_content = ReportGenerator._render_telegram_content(
  1684. report_data, update_info
  1685. )
  1686. url = f"https://api.telegram.org/bot{bot_token}/sendMessage"
  1687. payload = {
  1688. "chat_id": chat_id,
  1689. "text": text_content,
  1690. "parse_mode": "HTML",
  1691. "disable_web_page_preview": True,
  1692. }
  1693. proxies = None
  1694. if proxy_url:
  1695. proxies = {"http": proxy_url, "https": proxy_url}
  1696. try:
  1697. response = requests.post(
  1698. url, headers=headers, json=payload, proxies=proxies, timeout=30
  1699. )
  1700. if response.status_code == 200:
  1701. result = response.json()
  1702. if result.get("ok"):
  1703. print(f"Telegram通知发送成功 [{report_type}]")
  1704. return True
  1705. else:
  1706. print(
  1707. f"Telegram通知发送失败 [{report_type}],错误:{result.get('description')}"
  1708. )
  1709. return False
  1710. else:
  1711. print(
  1712. f"Telegram通知发送失败 [{report_type}],状态码:{response.status_code}"
  1713. )
  1714. return False
  1715. except Exception as e:
  1716. print(f"Telegram通知发送出错 [{report_type}]:{e}")
  1717. return False
  1718. class NewsAnalyzer:
  1719. """新闻分析器"""
  1720. def __init__(
  1721. self,
  1722. request_interval: int = CONFIG["REQUEST_INTERVAL"],
  1723. report_type: str = CONFIG["REPORT_TYPE"],
  1724. rank_threshold: int = CONFIG["RANK_THRESHOLD"],
  1725. ):
  1726. self.request_interval = request_interval
  1727. self.report_type = report_type
  1728. self.rank_threshold = rank_threshold
  1729. self.is_github_actions = os.environ.get("GITHUB_ACTIONS") == "true"
  1730. self.update_info = None
  1731. self.proxy_url = None
  1732. if not self.is_github_actions and CONFIG["USE_PROXY"]:
  1733. self.proxy_url = CONFIG["DEFAULT_PROXY"]
  1734. print("本地环境,使用代理")
  1735. elif not self.is_github_actions and not CONFIG["USE_PROXY"]:
  1736. print("本地环境,未启用代理")
  1737. else:
  1738. print("GitHub Actions环境,不使用代理")
  1739. self.data_fetcher = DataFetcher(self.proxy_url)
  1740. if self.is_github_actions:
  1741. self._check_version_update()
  1742. def _check_version_update(self) -> None:
  1743. """检查版本更新"""
  1744. try:
  1745. need_update, remote_version = VersionChecker.check_for_updates(
  1746. CONFIG["VERSION"], CONFIG["VERSION_CHECK_URL"], self.proxy_url
  1747. )
  1748. if need_update and remote_version:
  1749. self.update_info = {
  1750. "current_version": CONFIG["VERSION"],
  1751. "remote_version": remote_version,
  1752. }
  1753. print(f"发现新版本: {remote_version} (当前: {CONFIG['VERSION']})")
  1754. else:
  1755. print("版本检查完成,当前为最新版本")
  1756. except Exception as e:
  1757. print(f"版本检查出错: {e}")
  1758. def generate_daily_summary(self) -> Optional[str]:
  1759. """生成当日统计报告"""
  1760. print("生成当日统计报告...")
  1761. all_results, id_to_alias, title_info = DataProcessor.read_all_today_titles()
  1762. if not all_results:
  1763. print("没有找到当天的数据")
  1764. return None
  1765. total_titles = sum(len(titles) for titles in all_results.values())
  1766. print(f"读取到 {total_titles} 个标题")
  1767. latest_new_titles = DataProcessor.detect_latest_new_titles(id_to_alias)
  1768. if latest_new_titles:
  1769. total_new_count = sum(len(titles) for titles in latest_new_titles.values())
  1770. print(f"检测到 {total_new_count} 条最新新增新闻")
  1771. word_groups, filter_words = DataProcessor.load_frequency_words()
  1772. stats, total_titles = StatisticsCalculator.count_word_frequency(
  1773. all_results,
  1774. word_groups,
  1775. filter_words,
  1776. id_to_alias,
  1777. title_info,
  1778. self.rank_threshold,
  1779. latest_new_titles,
  1780. )
  1781. html_file = ReportGenerator.generate_html_report(
  1782. stats,
  1783. total_titles,
  1784. is_daily=True,
  1785. new_titles=latest_new_titles,
  1786. id_to_alias=id_to_alias,
  1787. )
  1788. print(f"当日HTML统计报告已生成: {html_file}")
  1789. if self.report_type in ["daily", "both"]:
  1790. ReportGenerator.send_to_webhooks(
  1791. stats,
  1792. [],
  1793. "当日汇总",
  1794. latest_new_titles,
  1795. id_to_alias,
  1796. self.update_info,
  1797. self.proxy_url,
  1798. )
  1799. return html_file
  1800. def run(self) -> None:
  1801. """执行分析流程"""
  1802. now = TimeHelper.get_beijing_time()
  1803. print(f"当前北京时间: {now.strftime('%Y-%m-%d %H:%M:%S')}")
  1804. # 检查是否配置了任何webhook URL
  1805. has_webhook = any(
  1806. [
  1807. os.environ.get("FEISHU_WEBHOOK_URL", CONFIG["FEISHU_WEBHOOK_URL"]),
  1808. os.environ.get("DINGTALK_WEBHOOK_URL", CONFIG["DINGTALK_WEBHOOK_URL"]),
  1809. os.environ.get("WEWORK_WEBHOOK_URL", CONFIG["WEWORK_WEBHOOK_URL"]),
  1810. (
  1811. os.environ.get("TELEGRAM_BOT_TOKEN", CONFIG["TELEGRAM_BOT_TOKEN"])
  1812. and os.environ.get("TELEGRAM_CHAT_ID", CONFIG["TELEGRAM_CHAT_ID"])
  1813. ),
  1814. ]
  1815. )
  1816. if not has_webhook and not CONFIG["CONTINUE_WITHOUT_WEBHOOK"]:
  1817. print(
  1818. "错误: 未配置任何webhook URL且CONTINUE_WITHOUT_WEBHOOK为False,程序退出"
  1819. )
  1820. return
  1821. if not has_webhook:
  1822. print("未配置任何webhook URL,将继续执行爬虫但不发送通知")
  1823. print(f"报告类型: {self.report_type}")
  1824. ids = [
  1825. ("toutiao", "今日头条"),
  1826. ("baidu", "百度热搜"),
  1827. ("wallstreetcn-hot", "华尔街见闻"),
  1828. ("thepaper", "澎湃新闻"),
  1829. ("bilibili-hot-search", "bilibili 热搜"),
  1830. ("cls-hot", "财联社热门"),
  1831. ("ifeng", "凤凰网"),
  1832. "tieba",
  1833. "weibo",
  1834. "douyin",
  1835. "zhihu",
  1836. ]
  1837. print(f"开始爬取数据,请求间隔 {self.request_interval} 毫秒")
  1838. FileHelper.ensure_directory_exists("output")
  1839. results, id_to_alias, failed_ids = self.data_fetcher.crawl_websites(
  1840. ids, self.request_interval
  1841. )
  1842. title_file = DataProcessor.save_titles_to_file(results, id_to_alias, failed_ids)
  1843. print(f"标题已保存到: {title_file}")
  1844. new_titles = DataProcessor.detect_latest_new_titles(id_to_alias)
  1845. # 构建标题信息
  1846. time_info = Path(title_file).stem
  1847. title_info = {}
  1848. for source_id, titles_data in results.items():
  1849. title_info[source_id] = {}
  1850. for title, title_data in titles_data.items():
  1851. ranks = title_data.get("ranks", [])
  1852. url = title_data.get("url", "")
  1853. mobile_url = title_data.get("mobileUrl", "")
  1854. title_info[source_id][title] = {
  1855. "first_time": time_info,
  1856. "last_time": time_info,
  1857. "count": 1,
  1858. "ranks": ranks,
  1859. "url": url,
  1860. "mobileUrl": mobile_url,
  1861. }
  1862. word_groups, filter_words = DataProcessor.load_frequency_words()
  1863. stats, total_titles = StatisticsCalculator.count_word_frequency(
  1864. results,
  1865. word_groups,
  1866. filter_words,
  1867. id_to_alias,
  1868. title_info,
  1869. self.rank_threshold,
  1870. new_titles,
  1871. )
  1872. if self.report_type in ["current", "both"]:
  1873. ReportGenerator.send_to_webhooks(
  1874. stats,
  1875. failed_ids,
  1876. "单次爬取",
  1877. new_titles,
  1878. id_to_alias,
  1879. self.update_info,
  1880. self.proxy_url,
  1881. )
  1882. html_file = ReportGenerator.generate_html_report(
  1883. stats, total_titles, failed_ids, False, new_titles, id_to_alias
  1884. )
  1885. print(f"HTML报告已生成: {html_file}")
  1886. daily_html = self.generate_daily_summary()
  1887. if not self.is_github_actions and html_file:
  1888. file_url = "file://" + str(Path(html_file).resolve())
  1889. print(f"正在打开HTML报告: {file_url}")
  1890. webbrowser.open(file_url)
  1891. if daily_html:
  1892. daily_url = "file://" + str(Path(daily_html).resolve())
  1893. print(f"正在打开当日统计报告: {daily_url}")
  1894. webbrowser.open(daily_url)
  1895. def main():
  1896. analyzer = NewsAnalyzer(
  1897. request_interval=CONFIG["REQUEST_INTERVAL"],
  1898. report_type=CONFIG["REPORT_TYPE"],
  1899. rank_threshold=CONFIG["RANK_THRESHOLD"],
  1900. )
  1901. analyzer.run()
  1902. if __name__ == "__main__":
  1903. main()