main.py 101 KB

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