main.py 188 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083
  1. # coding=utf-8
  2. import json
  3. import os
  4. import random
  5. import re
  6. import time
  7. import webbrowser
  8. import smtplib
  9. from email.mime.text import MIMEText
  10. from email.mime.multipart import MIMEMultipart
  11. from email.header import Header
  12. from email.utils import formataddr, formatdate, make_msgid
  13. from datetime import datetime
  14. from pathlib import Path
  15. from typing import Dict, List, Tuple, Optional, Union
  16. import pytz
  17. import requests
  18. import yaml
  19. VERSION = "3.4.1"
  20. # === SMTP邮件配置 ===
  21. SMTP_CONFIGS = {
  22. # Gmail(使用 STARTTLS)
  23. "gmail.com": {"server": "smtp.gmail.com", "port": 587, "encryption": "TLS"},
  24. # QQ邮箱(使用 SSL,更稳定)
  25. "qq.com": {"server": "smtp.qq.com", "port": 465, "encryption": "SSL"},
  26. # Outlook(使用 STARTTLS)
  27. "outlook.com": {
  28. "server": "smtp-mail.outlook.com",
  29. "port": 587,
  30. "encryption": "TLS",
  31. },
  32. "hotmail.com": {
  33. "server": "smtp-mail.outlook.com",
  34. "port": 587,
  35. "encryption": "TLS",
  36. },
  37. "live.com": {"server": "smtp-mail.outlook.com", "port": 587, "encryption": "TLS"},
  38. # 网易邮箱(使用 SSL,更稳定)
  39. "163.com": {"server": "smtp.163.com", "port": 465, "encryption": "SSL"},
  40. "126.com": {"server": "smtp.126.com", "port": 465, "encryption": "SSL"},
  41. # 新浪邮箱(使用 SSL)
  42. "sina.com": {"server": "smtp.sina.com", "port": 465, "encryption": "SSL"},
  43. # 搜狐邮箱(使用 SSL)
  44. "sohu.com": {"server": "smtp.sohu.com", "port": 465, "encryption": "SSL"},
  45. # 天翼邮箱(使用 SSL)
  46. "189.cn": {"server": "smtp.189.cn", "port": 465, "encryption": "SSL"},
  47. # 阿里云邮箱(使用 TLS)
  48. "aliyun.com": {"server": "smtp.aliyun.com", "port": 465, "encryption": "TLS"},
  49. }
  50. # === 配置管理 ===
  51. def load_config():
  52. """加载配置文件"""
  53. config_path = os.environ.get("CONFIG_PATH", "config/config.yaml")
  54. if not Path(config_path).exists():
  55. raise FileNotFoundError(f"配置文件 {config_path} 不存在")
  56. with open(config_path, "r", encoding="utf-8") as f:
  57. config_data = yaml.safe_load(f)
  58. print(f"配置文件加载成功: {config_path}")
  59. # 构建配置
  60. config = {
  61. "VERSION_CHECK_URL": config_data["app"]["version_check_url"],
  62. "SHOW_VERSION_UPDATE": config_data["app"]["show_version_update"],
  63. "REQUEST_INTERVAL": config_data["crawler"]["request_interval"],
  64. "REPORT_MODE": os.environ.get("REPORT_MODE", "").strip()
  65. or config_data["report"]["mode"],
  66. "RANK_THRESHOLD": config_data["report"]["rank_threshold"],
  67. "SORT_BY_POSITION_FIRST": os.environ.get("SORT_BY_POSITION_FIRST", "").strip().lower()
  68. in ("true", "1")
  69. if os.environ.get("SORT_BY_POSITION_FIRST", "").strip()
  70. else config_data["report"].get("sort_by_position_first", False),
  71. "MAX_NEWS_PER_KEYWORD": int(
  72. os.environ.get("MAX_NEWS_PER_KEYWORD", "").strip() or "0"
  73. )
  74. or config_data["report"].get("max_news_per_keyword", 0),
  75. "USE_PROXY": config_data["crawler"]["use_proxy"],
  76. "DEFAULT_PROXY": config_data["crawler"]["default_proxy"],
  77. "ENABLE_CRAWLER": os.environ.get("ENABLE_CRAWLER", "").strip().lower()
  78. in ("true", "1")
  79. if os.environ.get("ENABLE_CRAWLER", "").strip()
  80. else config_data["crawler"]["enable_crawler"],
  81. "ENABLE_NOTIFICATION": os.environ.get("ENABLE_NOTIFICATION", "").strip().lower()
  82. in ("true", "1")
  83. if os.environ.get("ENABLE_NOTIFICATION", "").strip()
  84. else config_data["notification"]["enable_notification"],
  85. "MESSAGE_BATCH_SIZE": config_data["notification"]["message_batch_size"],
  86. "DINGTALK_BATCH_SIZE": config_data["notification"].get(
  87. "dingtalk_batch_size", 20000
  88. ),
  89. "FEISHU_BATCH_SIZE": config_data["notification"].get("feishu_batch_size", 29000),
  90. "BARK_BATCH_SIZE": config_data["notification"].get("bark_batch_size", 3600),
  91. "SLACK_BATCH_SIZE": config_data["notification"].get("slack_batch_size", 4000),
  92. "BATCH_SEND_INTERVAL": config_data["notification"]["batch_send_interval"],
  93. "FEISHU_MESSAGE_SEPARATOR": config_data["notification"][
  94. "feishu_message_separator"
  95. ],
  96. "PUSH_WINDOW": {
  97. "ENABLED": os.environ.get("PUSH_WINDOW_ENABLED", "").strip().lower()
  98. in ("true", "1")
  99. if os.environ.get("PUSH_WINDOW_ENABLED", "").strip()
  100. else config_data["notification"]
  101. .get("push_window", {})
  102. .get("enabled", False),
  103. "TIME_RANGE": {
  104. "START": os.environ.get("PUSH_WINDOW_START", "").strip()
  105. or config_data["notification"]
  106. .get("push_window", {})
  107. .get("time_range", {})
  108. .get("start", "08:00"),
  109. "END": os.environ.get("PUSH_WINDOW_END", "").strip()
  110. or config_data["notification"]
  111. .get("push_window", {})
  112. .get("time_range", {})
  113. .get("end", "22:00"),
  114. },
  115. "ONCE_PER_DAY": os.environ.get("PUSH_WINDOW_ONCE_PER_DAY", "").strip().lower()
  116. in ("true", "1")
  117. if os.environ.get("PUSH_WINDOW_ONCE_PER_DAY", "").strip()
  118. else config_data["notification"]
  119. .get("push_window", {})
  120. .get("once_per_day", True),
  121. "RECORD_RETENTION_DAYS": int(
  122. os.environ.get("PUSH_WINDOW_RETENTION_DAYS", "").strip() or "0"
  123. )
  124. or config_data["notification"]
  125. .get("push_window", {})
  126. .get("push_record_retention_days", 7),
  127. },
  128. "WEIGHT_CONFIG": {
  129. "RANK_WEIGHT": config_data["weight"]["rank_weight"],
  130. "FREQUENCY_WEIGHT": config_data["weight"]["frequency_weight"],
  131. "HOTNESS_WEIGHT": config_data["weight"]["hotness_weight"],
  132. },
  133. "PLATFORMS": config_data["platforms"],
  134. }
  135. # 通知渠道配置(环境变量优先)
  136. notification = config_data.get("notification", {})
  137. webhooks = notification.get("webhooks", {})
  138. config["FEISHU_WEBHOOK_URL"] = os.environ.get(
  139. "FEISHU_WEBHOOK_URL", ""
  140. ).strip() or webhooks.get("feishu_url", "")
  141. config["DINGTALK_WEBHOOK_URL"] = os.environ.get(
  142. "DINGTALK_WEBHOOK_URL", ""
  143. ).strip() or webhooks.get("dingtalk_url", "")
  144. config["WEWORK_WEBHOOK_URL"] = os.environ.get(
  145. "WEWORK_WEBHOOK_URL", ""
  146. ).strip() or webhooks.get("wework_url", "")
  147. config["WEWORK_MSG_TYPE"] = os.environ.get(
  148. "WEWORK_MSG_TYPE", ""
  149. ).strip() or webhooks.get("wework_msg_type", "markdown")
  150. config["TELEGRAM_BOT_TOKEN"] = os.environ.get(
  151. "TELEGRAM_BOT_TOKEN", ""
  152. ).strip() or webhooks.get("telegram_bot_token", "")
  153. config["TELEGRAM_CHAT_ID"] = os.environ.get(
  154. "TELEGRAM_CHAT_ID", ""
  155. ).strip() or webhooks.get("telegram_chat_id", "")
  156. # 邮件配置
  157. config["EMAIL_FROM"] = os.environ.get("EMAIL_FROM", "").strip() or webhooks.get(
  158. "email_from", ""
  159. )
  160. config["EMAIL_PASSWORD"] = os.environ.get(
  161. "EMAIL_PASSWORD", ""
  162. ).strip() or webhooks.get("email_password", "")
  163. config["EMAIL_TO"] = os.environ.get("EMAIL_TO", "").strip() or webhooks.get(
  164. "email_to", ""
  165. )
  166. config["EMAIL_SMTP_SERVER"] = os.environ.get(
  167. "EMAIL_SMTP_SERVER", ""
  168. ).strip() or webhooks.get("email_smtp_server", "")
  169. config["EMAIL_SMTP_PORT"] = os.environ.get(
  170. "EMAIL_SMTP_PORT", ""
  171. ).strip() or webhooks.get("email_smtp_port", "")
  172. # ntfy配置
  173. config["NTFY_SERVER_URL"] = (
  174. os.environ.get("NTFY_SERVER_URL", "").strip()
  175. or webhooks.get("ntfy_server_url")
  176. or "https://ntfy.sh"
  177. )
  178. config["NTFY_TOPIC"] = os.environ.get("NTFY_TOPIC", "").strip() or webhooks.get(
  179. "ntfy_topic", ""
  180. )
  181. config["NTFY_TOKEN"] = os.environ.get("NTFY_TOKEN", "").strip() or webhooks.get(
  182. "ntfy_token", ""
  183. )
  184. # Bark配置
  185. config["BARK_URL"] = os.environ.get("BARK_URL", "").strip() or webhooks.get(
  186. "bark_url", ""
  187. )
  188. # Slack配置
  189. config["SLACK_WEBHOOK_URL"] = os.environ.get("SLACK_WEBHOOK_URL", "").strip() or webhooks.get(
  190. "slack_webhook_url", ""
  191. )
  192. # 输出配置来源信息
  193. notification_sources = []
  194. if config["FEISHU_WEBHOOK_URL"]:
  195. source = "环境变量" if os.environ.get("FEISHU_WEBHOOK_URL") else "配置文件"
  196. notification_sources.append(f"飞书({source})")
  197. if config["DINGTALK_WEBHOOK_URL"]:
  198. source = "环境变量" if os.environ.get("DINGTALK_WEBHOOK_URL") else "配置文件"
  199. notification_sources.append(f"钉钉({source})")
  200. if config["WEWORK_WEBHOOK_URL"]:
  201. source = "环境变量" if os.environ.get("WEWORK_WEBHOOK_URL") else "配置文件"
  202. notification_sources.append(f"企业微信({source})")
  203. if config["TELEGRAM_BOT_TOKEN"] and config["TELEGRAM_CHAT_ID"]:
  204. token_source = (
  205. "环境变量" if os.environ.get("TELEGRAM_BOT_TOKEN") else "配置文件"
  206. )
  207. chat_source = "环境变量" if os.environ.get("TELEGRAM_CHAT_ID") else "配置文件"
  208. notification_sources.append(f"Telegram({token_source}/{chat_source})")
  209. if config["EMAIL_FROM"] and config["EMAIL_PASSWORD"] and config["EMAIL_TO"]:
  210. from_source = "环境变量" if os.environ.get("EMAIL_FROM") else "配置文件"
  211. notification_sources.append(f"邮件({from_source})")
  212. if config["NTFY_SERVER_URL"] and config["NTFY_TOPIC"]:
  213. server_source = "环境变量" if os.environ.get("NTFY_SERVER_URL") else "配置文件"
  214. notification_sources.append(f"ntfy({server_source})")
  215. if config["BARK_URL"]:
  216. bark_source = "环境变量" if os.environ.get("BARK_URL") else "配置文件"
  217. notification_sources.append(f"Bark({bark_source})")
  218. if config["SLACK_WEBHOOK_URL"]:
  219. slack_source = "环境变量" if os.environ.get("SLACK_WEBHOOK_URL") else "配置文件"
  220. notification_sources.append(f"Slack({slack_source})")
  221. if notification_sources:
  222. print(f"通知渠道配置来源: {', '.join(notification_sources)}")
  223. else:
  224. print("未配置任何通知渠道")
  225. return config
  226. print("正在加载配置...")
  227. CONFIG = load_config()
  228. print(f"TrendRadar v{VERSION} 配置加载完成")
  229. print(f"监控平台数量: {len(CONFIG['PLATFORMS'])}")
  230. # === 工具函数 ===
  231. def get_beijing_time():
  232. """获取北京时间"""
  233. return datetime.now(pytz.timezone("Asia/Shanghai"))
  234. def format_date_folder():
  235. """格式化日期文件夹"""
  236. return get_beijing_time().strftime("%Y年%m月%d日")
  237. def format_time_filename():
  238. """格式化时间文件名"""
  239. return get_beijing_time().strftime("%H时%M分")
  240. def clean_title(title: str) -> str:
  241. """清理标题中的特殊字符"""
  242. if not isinstance(title, str):
  243. title = str(title)
  244. cleaned_title = title.replace("\n", " ").replace("\r", " ")
  245. cleaned_title = re.sub(r"\s+", " ", cleaned_title)
  246. cleaned_title = cleaned_title.strip()
  247. return cleaned_title
  248. def ensure_directory_exists(directory: str):
  249. """确保目录存在"""
  250. Path(directory).mkdir(parents=True, exist_ok=True)
  251. def get_output_path(subfolder: str, filename: str) -> str:
  252. """获取输出路径"""
  253. date_folder = format_date_folder()
  254. output_dir = Path("output") / date_folder / subfolder
  255. ensure_directory_exists(str(output_dir))
  256. return str(output_dir / filename)
  257. def check_version_update(
  258. current_version: str, version_url: str, proxy_url: Optional[str] = None
  259. ) -> Tuple[bool, Optional[str]]:
  260. """检查版本更新"""
  261. try:
  262. proxies = None
  263. if proxy_url:
  264. proxies = {"http": proxy_url, "https": proxy_url}
  265. headers = {
  266. "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
  267. "Accept": "text/plain, */*",
  268. "Cache-Control": "no-cache",
  269. }
  270. response = requests.get(
  271. version_url, proxies=proxies, headers=headers, timeout=10
  272. )
  273. response.raise_for_status()
  274. remote_version = response.text.strip()
  275. print(f"当前版本: {current_version}, 远程版本: {remote_version}")
  276. # 比较版本
  277. def parse_version(version_str):
  278. try:
  279. parts = version_str.strip().split(".")
  280. if len(parts) != 3:
  281. raise ValueError("版本号格式不正确")
  282. return int(parts[0]), int(parts[1]), int(parts[2])
  283. except:
  284. return 0, 0, 0
  285. current_tuple = parse_version(current_version)
  286. remote_tuple = parse_version(remote_version)
  287. need_update = current_tuple < remote_tuple
  288. return need_update, remote_version if need_update else None
  289. except Exception as e:
  290. print(f"版本检查失败: {e}")
  291. return False, None
  292. def is_first_crawl_today() -> bool:
  293. """检测是否是当天第一次爬取"""
  294. date_folder = format_date_folder()
  295. txt_dir = Path("output") / date_folder / "txt"
  296. if not txt_dir.exists():
  297. return True
  298. files = sorted([f for f in txt_dir.iterdir() if f.suffix == ".txt"])
  299. return len(files) <= 1
  300. def html_escape(text: str) -> str:
  301. """HTML转义"""
  302. if not isinstance(text, str):
  303. text = str(text)
  304. return (
  305. text.replace("&", "&amp;")
  306. .replace("<", "&lt;")
  307. .replace(">", "&gt;")
  308. .replace('"', "&quot;")
  309. .replace("'", "&#x27;")
  310. )
  311. # === 推送记录管理 ===
  312. class PushRecordManager:
  313. """推送记录管理器"""
  314. def __init__(self):
  315. self.record_dir = Path("output") / ".push_records"
  316. self.ensure_record_dir()
  317. self.cleanup_old_records()
  318. def ensure_record_dir(self):
  319. """确保记录目录存在"""
  320. self.record_dir.mkdir(parents=True, exist_ok=True)
  321. def get_today_record_file(self) -> Path:
  322. """获取今天的记录文件路径"""
  323. today = get_beijing_time().strftime("%Y%m%d")
  324. return self.record_dir / f"push_record_{today}.json"
  325. def cleanup_old_records(self):
  326. """清理过期的推送记录"""
  327. retention_days = CONFIG["PUSH_WINDOW"]["RECORD_RETENTION_DAYS"]
  328. current_time = get_beijing_time()
  329. for record_file in self.record_dir.glob("push_record_*.json"):
  330. try:
  331. date_str = record_file.stem.replace("push_record_", "")
  332. file_date = datetime.strptime(date_str, "%Y%m%d")
  333. file_date = pytz.timezone("Asia/Shanghai").localize(file_date)
  334. if (current_time - file_date).days > retention_days:
  335. record_file.unlink()
  336. print(f"清理过期推送记录: {record_file.name}")
  337. except Exception as e:
  338. print(f"清理记录文件失败 {record_file}: {e}")
  339. def has_pushed_today(self) -> bool:
  340. """检查今天是否已经推送过"""
  341. record_file = self.get_today_record_file()
  342. if not record_file.exists():
  343. return False
  344. try:
  345. with open(record_file, "r", encoding="utf-8") as f:
  346. record = json.load(f)
  347. return record.get("pushed", False)
  348. except Exception as e:
  349. print(f"读取推送记录失败: {e}")
  350. return False
  351. def record_push(self, report_type: str):
  352. """记录推送"""
  353. record_file = self.get_today_record_file()
  354. now = get_beijing_time()
  355. record = {
  356. "pushed": True,
  357. "push_time": now.strftime("%Y-%m-%d %H:%M:%S"),
  358. "report_type": report_type,
  359. }
  360. try:
  361. with open(record_file, "w", encoding="utf-8") as f:
  362. json.dump(record, f, ensure_ascii=False, indent=2)
  363. print(f"推送记录已保存: {report_type} at {now.strftime('%H:%M:%S')}")
  364. except Exception as e:
  365. print(f"保存推送记录失败: {e}")
  366. def is_in_time_range(self, start_time: str, end_time: str) -> bool:
  367. """检查当前时间是否在指定时间范围内"""
  368. now = get_beijing_time()
  369. current_time = now.strftime("%H:%M")
  370. def normalize_time(time_str: str) -> str:
  371. """将时间字符串标准化为 HH:MM 格式"""
  372. try:
  373. parts = time_str.strip().split(":")
  374. if len(parts) != 2:
  375. raise ValueError(f"时间格式错误: {time_str}")
  376. hour = int(parts[0])
  377. minute = int(parts[1])
  378. if not (0 <= hour <= 23 and 0 <= minute <= 59):
  379. raise ValueError(f"时间范围错误: {time_str}")
  380. return f"{hour:02d}:{minute:02d}"
  381. except Exception as e:
  382. print(f"时间格式化错误 '{time_str}': {e}")
  383. return time_str
  384. normalized_start = normalize_time(start_time)
  385. normalized_end = normalize_time(end_time)
  386. normalized_current = normalize_time(current_time)
  387. result = normalized_start <= normalized_current <= normalized_end
  388. if not result:
  389. print(f"时间窗口判断:当前 {normalized_current},窗口 {normalized_start}-{normalized_end}")
  390. return result
  391. # === 数据获取 ===
  392. class DataFetcher:
  393. """数据获取器"""
  394. def __init__(self, proxy_url: Optional[str] = None):
  395. self.proxy_url = proxy_url
  396. def fetch_data(
  397. self,
  398. id_info: Union[str, Tuple[str, str]],
  399. max_retries: int = 2,
  400. min_retry_wait: int = 3,
  401. max_retry_wait: int = 5,
  402. ) -> Tuple[Optional[str], str, str]:
  403. """获取指定ID数据,支持重试"""
  404. if isinstance(id_info, tuple):
  405. id_value, alias = id_info
  406. else:
  407. id_value = id_info
  408. alias = id_value
  409. url = f"https://newsnow.busiyi.world/api/s?id={id_value}&latest"
  410. proxies = None
  411. if self.proxy_url:
  412. proxies = {"http": self.proxy_url, "https": self.proxy_url}
  413. headers = {
  414. "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",
  415. "Accept": "application/json, text/plain, */*",
  416. "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
  417. "Connection": "keep-alive",
  418. "Cache-Control": "no-cache",
  419. }
  420. retries = 0
  421. while retries <= max_retries:
  422. try:
  423. response = requests.get(
  424. url, proxies=proxies, headers=headers, timeout=10
  425. )
  426. response.raise_for_status()
  427. data_text = response.text
  428. data_json = json.loads(data_text)
  429. status = data_json.get("status", "未知")
  430. if status not in ["success", "cache"]:
  431. raise ValueError(f"响应状态异常: {status}")
  432. status_info = "最新数据" if status == "success" else "缓存数据"
  433. print(f"获取 {id_value} 成功({status_info})")
  434. return data_text, id_value, alias
  435. except Exception as e:
  436. retries += 1
  437. if retries <= max_retries:
  438. base_wait = random.uniform(min_retry_wait, max_retry_wait)
  439. additional_wait = (retries - 1) * random.uniform(1, 2)
  440. wait_time = base_wait + additional_wait
  441. print(f"请求 {id_value} 失败: {e}. {wait_time:.2f}秒后重试...")
  442. time.sleep(wait_time)
  443. else:
  444. print(f"请求 {id_value} 失败: {e}")
  445. return None, id_value, alias
  446. return None, id_value, alias
  447. def crawl_websites(
  448. self,
  449. ids_list: List[Union[str, Tuple[str, str]]],
  450. request_interval: int = CONFIG["REQUEST_INTERVAL"],
  451. ) -> Tuple[Dict, Dict, List]:
  452. """爬取多个网站数据"""
  453. results = {}
  454. id_to_name = {}
  455. failed_ids = []
  456. for i, id_info in enumerate(ids_list):
  457. if isinstance(id_info, tuple):
  458. id_value, name = id_info
  459. else:
  460. id_value = id_info
  461. name = id_value
  462. id_to_name[id_value] = name
  463. response, _, _ = self.fetch_data(id_info)
  464. if response:
  465. try:
  466. data = json.loads(response)
  467. results[id_value] = {}
  468. for index, item in enumerate(data.get("items", []), 1):
  469. title = item.get("title")
  470. # 跳过无效标题(None、float、空字符串)
  471. if title is None or isinstance(title, float) or not str(title).strip():
  472. continue
  473. title = str(title).strip()
  474. url = item.get("url", "")
  475. mobile_url = item.get("mobileUrl", "")
  476. if title in results[id_value]:
  477. results[id_value][title]["ranks"].append(index)
  478. else:
  479. results[id_value][title] = {
  480. "ranks": [index],
  481. "url": url,
  482. "mobileUrl": mobile_url,
  483. }
  484. except json.JSONDecodeError:
  485. print(f"解析 {id_value} 响应失败")
  486. failed_ids.append(id_value)
  487. except Exception as e:
  488. print(f"处理 {id_value} 数据出错: {e}")
  489. failed_ids.append(id_value)
  490. else:
  491. failed_ids.append(id_value)
  492. if i < len(ids_list) - 1:
  493. actual_interval = request_interval + random.randint(-10, 20)
  494. actual_interval = max(50, actual_interval)
  495. time.sleep(actual_interval / 1000)
  496. print(f"成功: {list(results.keys())}, 失败: {failed_ids}")
  497. return results, id_to_name, failed_ids
  498. # === 数据处理 ===
  499. def save_titles_to_file(results: Dict, id_to_name: Dict, failed_ids: List) -> str:
  500. """保存标题到文件"""
  501. file_path = get_output_path("txt", f"{format_time_filename()}.txt")
  502. with open(file_path, "w", encoding="utf-8") as f:
  503. for id_value, title_data in results.items():
  504. # id | name 或 id
  505. name = id_to_name.get(id_value)
  506. if name and name != id_value:
  507. f.write(f"{id_value} | {name}\n")
  508. else:
  509. f.write(f"{id_value}\n")
  510. # 按排名排序标题
  511. sorted_titles = []
  512. for title, info in title_data.items():
  513. cleaned_title = clean_title(title)
  514. if isinstance(info, dict):
  515. ranks = info.get("ranks", [])
  516. url = info.get("url", "")
  517. mobile_url = info.get("mobileUrl", "")
  518. else:
  519. ranks = info if isinstance(info, list) else []
  520. url = ""
  521. mobile_url = ""
  522. rank = ranks[0] if ranks else 1
  523. sorted_titles.append((rank, cleaned_title, url, mobile_url))
  524. sorted_titles.sort(key=lambda x: x[0])
  525. for rank, cleaned_title, url, mobile_url in sorted_titles:
  526. line = f"{rank}. {cleaned_title}"
  527. if url:
  528. line += f" [URL:{url}]"
  529. if mobile_url:
  530. line += f" [MOBILE:{mobile_url}]"
  531. f.write(line + "\n")
  532. f.write("\n")
  533. if failed_ids:
  534. f.write("==== 以下ID请求失败 ====\n")
  535. for id_value in failed_ids:
  536. f.write(f"{id_value}\n")
  537. return file_path
  538. def load_frequency_words(
  539. frequency_file: Optional[str] = None,
  540. ) -> Tuple[List[Dict], List[str]]:
  541. """加载频率词配置"""
  542. if frequency_file is None:
  543. frequency_file = os.environ.get(
  544. "FREQUENCY_WORDS_PATH", "config/frequency_words.txt"
  545. )
  546. frequency_path = Path(frequency_file)
  547. if not frequency_path.exists():
  548. raise FileNotFoundError(f"频率词文件 {frequency_file} 不存在")
  549. with open(frequency_path, "r", encoding="utf-8") as f:
  550. content = f.read()
  551. word_groups = [group.strip() for group in content.split("\n\n") if group.strip()]
  552. processed_groups = []
  553. filter_words = []
  554. for group in word_groups:
  555. words = [word.strip() for word in group.split("\n") if word.strip()]
  556. group_required_words = []
  557. group_normal_words = []
  558. group_filter_words = []
  559. group_max_count = 0 # 默认不限制
  560. for word in words:
  561. if word.startswith("@"):
  562. # 解析最大显示数量(只接受正整数)
  563. try:
  564. count = int(word[1:])
  565. if count > 0:
  566. group_max_count = count
  567. except (ValueError, IndexError):
  568. pass # 忽略无效的@数字格式
  569. elif word.startswith("!"):
  570. filter_words.append(word[1:])
  571. group_filter_words.append(word[1:])
  572. elif word.startswith("+"):
  573. group_required_words.append(word[1:])
  574. else:
  575. group_normal_words.append(word)
  576. if group_required_words or group_normal_words:
  577. if group_normal_words:
  578. group_key = " ".join(group_normal_words)
  579. else:
  580. group_key = " ".join(group_required_words)
  581. processed_groups.append(
  582. {
  583. "required": group_required_words,
  584. "normal": group_normal_words,
  585. "group_key": group_key,
  586. "max_count": group_max_count, # 新增字段
  587. }
  588. )
  589. return processed_groups, filter_words
  590. def parse_file_titles(file_path: Path) -> Tuple[Dict, Dict]:
  591. """解析单个txt文件的标题数据,返回(titles_by_id, id_to_name)"""
  592. titles_by_id = {}
  593. id_to_name = {}
  594. with open(file_path, "r", encoding="utf-8") as f:
  595. content = f.read()
  596. sections = content.split("\n\n")
  597. for section in sections:
  598. if not section.strip() or "==== 以下ID请求失败 ====" in section:
  599. continue
  600. lines = section.strip().split("\n")
  601. if len(lines) < 2:
  602. continue
  603. # id | name 或 id
  604. header_line = lines[0].strip()
  605. if " | " in header_line:
  606. parts = header_line.split(" | ", 1)
  607. source_id = parts[0].strip()
  608. name = parts[1].strip()
  609. id_to_name[source_id] = name
  610. else:
  611. source_id = header_line
  612. id_to_name[source_id] = source_id
  613. titles_by_id[source_id] = {}
  614. for line in lines[1:]:
  615. if line.strip():
  616. try:
  617. title_part = line.strip()
  618. rank = None
  619. # 提取排名
  620. if ". " in title_part and title_part.split(". ")[0].isdigit():
  621. rank_str, title_part = title_part.split(". ", 1)
  622. rank = int(rank_str)
  623. # 提取 MOBILE URL
  624. mobile_url = ""
  625. if " [MOBILE:" in title_part:
  626. title_part, mobile_part = title_part.rsplit(" [MOBILE:", 1)
  627. if mobile_part.endswith("]"):
  628. mobile_url = mobile_part[:-1]
  629. # 提取 URL
  630. url = ""
  631. if " [URL:" in title_part:
  632. title_part, url_part = title_part.rsplit(" [URL:", 1)
  633. if url_part.endswith("]"):
  634. url = url_part[:-1]
  635. title = clean_title(title_part.strip())
  636. ranks = [rank] if rank is not None else [1]
  637. titles_by_id[source_id][title] = {
  638. "ranks": ranks,
  639. "url": url,
  640. "mobileUrl": mobile_url,
  641. }
  642. except Exception as e:
  643. print(f"解析标题行出错: {line}, 错误: {e}")
  644. return titles_by_id, id_to_name
  645. def read_all_today_titles(
  646. current_platform_ids: Optional[List[str]] = None,
  647. ) -> Tuple[Dict, Dict, Dict]:
  648. """读取当天所有标题文件,支持按当前监控平台过滤"""
  649. date_folder = format_date_folder()
  650. txt_dir = Path("output") / date_folder / "txt"
  651. if not txt_dir.exists():
  652. return {}, {}, {}
  653. all_results = {}
  654. final_id_to_name = {}
  655. title_info = {}
  656. files = sorted([f for f in txt_dir.iterdir() if f.suffix == ".txt"])
  657. for file_path in files:
  658. time_info = file_path.stem
  659. titles_by_id, file_id_to_name = parse_file_titles(file_path)
  660. if current_platform_ids is not None:
  661. filtered_titles_by_id = {}
  662. filtered_id_to_name = {}
  663. for source_id, title_data in titles_by_id.items():
  664. if source_id in current_platform_ids:
  665. filtered_titles_by_id[source_id] = title_data
  666. if source_id in file_id_to_name:
  667. filtered_id_to_name[source_id] = file_id_to_name[source_id]
  668. titles_by_id = filtered_titles_by_id
  669. file_id_to_name = filtered_id_to_name
  670. final_id_to_name.update(file_id_to_name)
  671. for source_id, title_data in titles_by_id.items():
  672. process_source_data(
  673. source_id, title_data, time_info, all_results, title_info
  674. )
  675. return all_results, final_id_to_name, title_info
  676. def process_source_data(
  677. source_id: str,
  678. title_data: Dict,
  679. time_info: str,
  680. all_results: Dict,
  681. title_info: Dict,
  682. ) -> None:
  683. """处理来源数据,合并重复标题"""
  684. if source_id not in all_results:
  685. all_results[source_id] = title_data
  686. if source_id not in title_info:
  687. title_info[source_id] = {}
  688. for title, data in title_data.items():
  689. ranks = data.get("ranks", [])
  690. url = data.get("url", "")
  691. mobile_url = data.get("mobileUrl", "")
  692. title_info[source_id][title] = {
  693. "first_time": time_info,
  694. "last_time": time_info,
  695. "count": 1,
  696. "ranks": ranks,
  697. "url": url,
  698. "mobileUrl": mobile_url,
  699. }
  700. else:
  701. for title, data in title_data.items():
  702. ranks = data.get("ranks", [])
  703. url = data.get("url", "")
  704. mobile_url = data.get("mobileUrl", "")
  705. if title not in all_results[source_id]:
  706. all_results[source_id][title] = {
  707. "ranks": ranks,
  708. "url": url,
  709. "mobileUrl": mobile_url,
  710. }
  711. title_info[source_id][title] = {
  712. "first_time": time_info,
  713. "last_time": time_info,
  714. "count": 1,
  715. "ranks": ranks,
  716. "url": url,
  717. "mobileUrl": mobile_url,
  718. }
  719. else:
  720. existing_data = all_results[source_id][title]
  721. existing_ranks = existing_data.get("ranks", [])
  722. existing_url = existing_data.get("url", "")
  723. existing_mobile_url = existing_data.get("mobileUrl", "")
  724. merged_ranks = existing_ranks.copy()
  725. for rank in ranks:
  726. if rank not in merged_ranks:
  727. merged_ranks.append(rank)
  728. all_results[source_id][title] = {
  729. "ranks": merged_ranks,
  730. "url": existing_url or url,
  731. "mobileUrl": existing_mobile_url or mobile_url,
  732. }
  733. title_info[source_id][title]["last_time"] = time_info
  734. title_info[source_id][title]["ranks"] = merged_ranks
  735. title_info[source_id][title]["count"] += 1
  736. if not title_info[source_id][title].get("url"):
  737. title_info[source_id][title]["url"] = url
  738. if not title_info[source_id][title].get("mobileUrl"):
  739. title_info[source_id][title]["mobileUrl"] = mobile_url
  740. def detect_latest_new_titles(current_platform_ids: Optional[List[str]] = None) -> Dict:
  741. """检测当日最新批次的新增标题,支持按当前监控平台过滤"""
  742. date_folder = format_date_folder()
  743. txt_dir = Path("output") / date_folder / "txt"
  744. if not txt_dir.exists():
  745. return {}
  746. files = sorted([f for f in txt_dir.iterdir() if f.suffix == ".txt"])
  747. if len(files) < 2:
  748. return {}
  749. # 解析最新文件
  750. latest_file = files[-1]
  751. latest_titles, _ = parse_file_titles(latest_file)
  752. # 如果指定了当前平台列表,过滤最新文件数据
  753. if current_platform_ids is not None:
  754. filtered_latest_titles = {}
  755. for source_id, title_data in latest_titles.items():
  756. if source_id in current_platform_ids:
  757. filtered_latest_titles[source_id] = title_data
  758. latest_titles = filtered_latest_titles
  759. # 汇总历史标题(按平台过滤)
  760. historical_titles = {}
  761. for file_path in files[:-1]:
  762. historical_data, _ = parse_file_titles(file_path)
  763. # 过滤历史数据
  764. if current_platform_ids is not None:
  765. filtered_historical_data = {}
  766. for source_id, title_data in historical_data.items():
  767. if source_id in current_platform_ids:
  768. filtered_historical_data[source_id] = title_data
  769. historical_data = filtered_historical_data
  770. for source_id, titles_data in historical_data.items():
  771. if source_id not in historical_titles:
  772. historical_titles[source_id] = set()
  773. for title in titles_data.keys():
  774. historical_titles[source_id].add(title)
  775. # 找出新增标题
  776. new_titles = {}
  777. for source_id, latest_source_titles in latest_titles.items():
  778. historical_set = historical_titles.get(source_id, set())
  779. source_new_titles = {}
  780. for title, title_data in latest_source_titles.items():
  781. if title not in historical_set:
  782. source_new_titles[title] = title_data
  783. if source_new_titles:
  784. new_titles[source_id] = source_new_titles
  785. return new_titles
  786. # === 统计和分析 ===
  787. def calculate_news_weight(
  788. title_data: Dict, rank_threshold: int = CONFIG["RANK_THRESHOLD"]
  789. ) -> float:
  790. """计算新闻权重,用于排序"""
  791. ranks = title_data.get("ranks", [])
  792. if not ranks:
  793. return 0.0
  794. count = title_data.get("count", len(ranks))
  795. weight_config = CONFIG["WEIGHT_CONFIG"]
  796. # 排名权重:Σ(11 - min(rank, 10)) / 出现次数
  797. rank_scores = []
  798. for rank in ranks:
  799. score = 11 - min(rank, 10)
  800. rank_scores.append(score)
  801. rank_weight = sum(rank_scores) / len(ranks) if ranks else 0
  802. # 频次权重:min(出现次数, 10) × 10
  803. frequency_weight = min(count, 10) * 10
  804. # 热度加成:高排名次数 / 总出现次数 × 100
  805. high_rank_count = sum(1 for rank in ranks if rank <= rank_threshold)
  806. hotness_ratio = high_rank_count / len(ranks) if ranks else 0
  807. hotness_weight = hotness_ratio * 100
  808. total_weight = (
  809. rank_weight * weight_config["RANK_WEIGHT"]
  810. + frequency_weight * weight_config["FREQUENCY_WEIGHT"]
  811. + hotness_weight * weight_config["HOTNESS_WEIGHT"]
  812. )
  813. return total_weight
  814. def matches_word_groups(
  815. title: str, word_groups: List[Dict], filter_words: List[str]
  816. ) -> bool:
  817. """检查标题是否匹配词组规则"""
  818. # 防御性类型检查:确保 title 是有效字符串
  819. if not isinstance(title, str):
  820. title = str(title) if title is not None else ""
  821. if not title.strip():
  822. return False
  823. # 如果没有配置词组,则匹配所有标题(支持显示全部新闻)
  824. if not word_groups:
  825. return True
  826. title_lower = title.lower()
  827. # 过滤词检查
  828. if any(filter_word.lower() in title_lower for filter_word in filter_words):
  829. return False
  830. # 词组匹配检查
  831. for group in word_groups:
  832. required_words = group["required"]
  833. normal_words = group["normal"]
  834. # 必须词检查
  835. if required_words:
  836. all_required_present = all(
  837. req_word.lower() in title_lower for req_word in required_words
  838. )
  839. if not all_required_present:
  840. continue
  841. # 普通词检查
  842. if normal_words:
  843. any_normal_present = any(
  844. normal_word.lower() in title_lower for normal_word in normal_words
  845. )
  846. if not any_normal_present:
  847. continue
  848. return True
  849. return False
  850. def format_time_display(first_time: str, last_time: str) -> str:
  851. """格式化时间显示"""
  852. if not first_time:
  853. return ""
  854. if first_time == last_time or not last_time:
  855. return first_time
  856. else:
  857. return f"[{first_time} ~ {last_time}]"
  858. def format_rank_display(ranks: List[int], rank_threshold: int, format_type: str) -> str:
  859. """统一的排名格式化方法"""
  860. if not ranks:
  861. return ""
  862. unique_ranks = sorted(set(ranks))
  863. min_rank = unique_ranks[0]
  864. max_rank = unique_ranks[-1]
  865. if format_type == "html":
  866. highlight_start = "<font color='red'><strong>"
  867. highlight_end = "</strong></font>"
  868. elif format_type == "feishu":
  869. highlight_start = "<font color='red'>**"
  870. highlight_end = "**</font>"
  871. elif format_type == "dingtalk":
  872. highlight_start = "**"
  873. highlight_end = "**"
  874. elif format_type == "wework":
  875. highlight_start = "**"
  876. highlight_end = "**"
  877. elif format_type == "telegram":
  878. highlight_start = "<b>"
  879. highlight_end = "</b>"
  880. elif format_type == "slack":
  881. highlight_start = "*"
  882. highlight_end = "*"
  883. else:
  884. highlight_start = "**"
  885. highlight_end = "**"
  886. if min_rank <= rank_threshold:
  887. if min_rank == max_rank:
  888. return f"{highlight_start}[{min_rank}]{highlight_end}"
  889. else:
  890. return f"{highlight_start}[{min_rank} - {max_rank}]{highlight_end}"
  891. else:
  892. if min_rank == max_rank:
  893. return f"[{min_rank}]"
  894. else:
  895. return f"[{min_rank} - {max_rank}]"
  896. def count_word_frequency(
  897. results: Dict,
  898. word_groups: List[Dict],
  899. filter_words: List[str],
  900. id_to_name: Dict,
  901. title_info: Optional[Dict] = None,
  902. rank_threshold: int = CONFIG["RANK_THRESHOLD"],
  903. new_titles: Optional[Dict] = None,
  904. mode: str = "daily",
  905. ) -> Tuple[List[Dict], int]:
  906. """统计词频,支持必须词、频率词、过滤词,并标记新增标题"""
  907. # 如果没有配置词组,创建一个包含所有新闻的虚拟词组
  908. if not word_groups:
  909. print("频率词配置为空,将显示所有新闻")
  910. word_groups = [{"required": [], "normal": [], "group_key": "全部新闻"}]
  911. filter_words = [] # 清空过滤词,显示所有新闻
  912. is_first_today = is_first_crawl_today()
  913. # 确定处理的数据源和新增标记逻辑
  914. if mode == "incremental":
  915. if is_first_today:
  916. # 增量模式 + 当天第一次:处理所有新闻,都标记为新增
  917. results_to_process = results
  918. all_news_are_new = True
  919. else:
  920. # 增量模式 + 当天非第一次:只处理新增的新闻
  921. results_to_process = new_titles if new_titles else {}
  922. all_news_are_new = True
  923. elif mode == "current":
  924. # current 模式:只处理当前时间批次的新闻,但统计信息来自全部历史
  925. if title_info:
  926. latest_time = None
  927. for source_titles in title_info.values():
  928. for title_data in source_titles.values():
  929. last_time = title_data.get("last_time", "")
  930. if last_time:
  931. if latest_time is None or last_time > latest_time:
  932. latest_time = last_time
  933. # 只处理 last_time 等于最新时间的新闻
  934. if latest_time:
  935. results_to_process = {}
  936. for source_id, source_titles in results.items():
  937. if source_id in title_info:
  938. filtered_titles = {}
  939. for title, title_data in source_titles.items():
  940. if title in title_info[source_id]:
  941. info = title_info[source_id][title]
  942. if info.get("last_time") == latest_time:
  943. filtered_titles[title] = title_data
  944. if filtered_titles:
  945. results_to_process[source_id] = filtered_titles
  946. print(
  947. f"当前榜单模式:最新时间 {latest_time},筛选出 {sum(len(titles) for titles in results_to_process.values())} 条当前榜单新闻"
  948. )
  949. else:
  950. results_to_process = results
  951. else:
  952. results_to_process = results
  953. all_news_are_new = False
  954. else:
  955. # 当日汇总模式:处理所有新闻
  956. results_to_process = results
  957. all_news_are_new = False
  958. total_input_news = sum(len(titles) for titles in results.values())
  959. filter_status = (
  960. "全部显示"
  961. if len(word_groups) == 1 and word_groups[0]["group_key"] == "全部新闻"
  962. else "频率词过滤"
  963. )
  964. print(f"当日汇总模式:处理 {total_input_news} 条新闻,模式:{filter_status}")
  965. word_stats = {}
  966. total_titles = 0
  967. processed_titles = {}
  968. matched_new_count = 0
  969. if title_info is None:
  970. title_info = {}
  971. if new_titles is None:
  972. new_titles = {}
  973. for group in word_groups:
  974. group_key = group["group_key"]
  975. word_stats[group_key] = {"count": 0, "titles": {}}
  976. for source_id, titles_data in results_to_process.items():
  977. total_titles += len(titles_data)
  978. if source_id not in processed_titles:
  979. processed_titles[source_id] = {}
  980. for title, title_data in titles_data.items():
  981. if title in processed_titles.get(source_id, {}):
  982. continue
  983. # 使用统一的匹配逻辑
  984. matches_frequency_words = matches_word_groups(
  985. title, word_groups, filter_words
  986. )
  987. if not matches_frequency_words:
  988. continue
  989. # 如果是增量模式或 current 模式第一次,统计匹配的新增新闻数量
  990. if (mode == "incremental" and all_news_are_new) or (
  991. mode == "current" and is_first_today
  992. ):
  993. matched_new_count += 1
  994. source_ranks = title_data.get("ranks", [])
  995. source_url = title_data.get("url", "")
  996. source_mobile_url = title_data.get("mobileUrl", "")
  997. # 找到匹配的词组(防御性转换确保类型安全)
  998. title_lower = str(title).lower() if not isinstance(title, str) else title.lower()
  999. for group in word_groups:
  1000. required_words = group["required"]
  1001. normal_words = group["normal"]
  1002. # 如果是"全部新闻"模式,所有标题都匹配第一个(唯一的)词组
  1003. if len(word_groups) == 1 and word_groups[0]["group_key"] == "全部新闻":
  1004. group_key = group["group_key"]
  1005. word_stats[group_key]["count"] += 1
  1006. if source_id not in word_stats[group_key]["titles"]:
  1007. word_stats[group_key]["titles"][source_id] = []
  1008. else:
  1009. # 原有的匹配逻辑
  1010. if required_words:
  1011. all_required_present = all(
  1012. req_word.lower() in title_lower
  1013. for req_word in required_words
  1014. )
  1015. if not all_required_present:
  1016. continue
  1017. if normal_words:
  1018. any_normal_present = any(
  1019. normal_word.lower() in title_lower
  1020. for normal_word in normal_words
  1021. )
  1022. if not any_normal_present:
  1023. continue
  1024. group_key = group["group_key"]
  1025. word_stats[group_key]["count"] += 1
  1026. if source_id not in word_stats[group_key]["titles"]:
  1027. word_stats[group_key]["titles"][source_id] = []
  1028. first_time = ""
  1029. last_time = ""
  1030. count_info = 1
  1031. ranks = source_ranks if source_ranks else []
  1032. url = source_url
  1033. mobile_url = source_mobile_url
  1034. # 对于 current 模式,从历史统计信息中获取完整数据
  1035. if (
  1036. mode == "current"
  1037. and title_info
  1038. and source_id in title_info
  1039. and title in title_info[source_id]
  1040. ):
  1041. info = title_info[source_id][title]
  1042. first_time = info.get("first_time", "")
  1043. last_time = info.get("last_time", "")
  1044. count_info = info.get("count", 1)
  1045. if "ranks" in info and info["ranks"]:
  1046. ranks = info["ranks"]
  1047. url = info.get("url", source_url)
  1048. mobile_url = info.get("mobileUrl", source_mobile_url)
  1049. elif (
  1050. title_info
  1051. and source_id in title_info
  1052. and title in title_info[source_id]
  1053. ):
  1054. info = title_info[source_id][title]
  1055. first_time = info.get("first_time", "")
  1056. last_time = info.get("last_time", "")
  1057. count_info = info.get("count", 1)
  1058. if "ranks" in info and info["ranks"]:
  1059. ranks = info["ranks"]
  1060. url = info.get("url", source_url)
  1061. mobile_url = info.get("mobileUrl", source_mobile_url)
  1062. if not ranks:
  1063. ranks = [99]
  1064. time_display = format_time_display(first_time, last_time)
  1065. source_name = id_to_name.get(source_id, source_id)
  1066. # 判断是否为新增
  1067. is_new = False
  1068. if all_news_are_new:
  1069. # 增量模式下所有处理的新闻都是新增,或者当天第一次的所有新闻都是新增
  1070. is_new = True
  1071. elif new_titles and source_id in new_titles:
  1072. # 检查是否在新增列表中
  1073. new_titles_for_source = new_titles[source_id]
  1074. is_new = title in new_titles_for_source
  1075. word_stats[group_key]["titles"][source_id].append(
  1076. {
  1077. "title": title,
  1078. "source_name": source_name,
  1079. "first_time": first_time,
  1080. "last_time": last_time,
  1081. "time_display": time_display,
  1082. "count": count_info,
  1083. "ranks": ranks,
  1084. "rank_threshold": rank_threshold,
  1085. "url": url,
  1086. "mobileUrl": mobile_url,
  1087. "is_new": is_new,
  1088. }
  1089. )
  1090. if source_id not in processed_titles:
  1091. processed_titles[source_id] = {}
  1092. processed_titles[source_id][title] = True
  1093. break
  1094. # 最后统一打印汇总信息
  1095. if mode == "incremental":
  1096. if is_first_today:
  1097. total_input_news = sum(len(titles) for titles in results.values())
  1098. filter_status = (
  1099. "全部显示"
  1100. if len(word_groups) == 1 and word_groups[0]["group_key"] == "全部新闻"
  1101. else "频率词匹配"
  1102. )
  1103. print(
  1104. f"增量模式:当天第一次爬取,{total_input_news} 条新闻中有 {matched_new_count} 条{filter_status}"
  1105. )
  1106. else:
  1107. if new_titles:
  1108. total_new_count = sum(len(titles) for titles in new_titles.values())
  1109. filter_status = (
  1110. "全部显示"
  1111. if len(word_groups) == 1
  1112. and word_groups[0]["group_key"] == "全部新闻"
  1113. else "匹配频率词"
  1114. )
  1115. print(
  1116. f"增量模式:{total_new_count} 条新增新闻中,有 {matched_new_count} 条{filter_status}"
  1117. )
  1118. if matched_new_count == 0 and len(word_groups) > 1:
  1119. print("增量模式:没有新增新闻匹配频率词,将不会发送通知")
  1120. else:
  1121. print("增量模式:未检测到新增新闻")
  1122. elif mode == "current":
  1123. total_input_news = sum(len(titles) for titles in results_to_process.values())
  1124. if is_first_today:
  1125. filter_status = (
  1126. "全部显示"
  1127. if len(word_groups) == 1 and word_groups[0]["group_key"] == "全部新闻"
  1128. else "频率词匹配"
  1129. )
  1130. print(
  1131. f"当前榜单模式:当天第一次爬取,{total_input_news} 条当前榜单新闻中有 {matched_new_count} 条{filter_status}"
  1132. )
  1133. else:
  1134. matched_count = sum(stat["count"] for stat in word_stats.values())
  1135. filter_status = (
  1136. "全部显示"
  1137. if len(word_groups) == 1 and word_groups[0]["group_key"] == "全部新闻"
  1138. else "频率词匹配"
  1139. )
  1140. print(
  1141. f"当前榜单模式:{total_input_news} 条当前榜单新闻中有 {matched_count} 条{filter_status}"
  1142. )
  1143. stats = []
  1144. # 创建 group_key 到位置和最大数量的映射
  1145. group_key_to_position = {
  1146. group["group_key"]: idx for idx, group in enumerate(word_groups)
  1147. }
  1148. group_key_to_max_count = {
  1149. group["group_key"]: group.get("max_count", 0) for group in word_groups
  1150. }
  1151. for group_key, data in word_stats.items():
  1152. all_titles = []
  1153. for source_id, title_list in data["titles"].items():
  1154. all_titles.extend(title_list)
  1155. # 按权重排序
  1156. sorted_titles = sorted(
  1157. all_titles,
  1158. key=lambda x: (
  1159. -calculate_news_weight(x, rank_threshold),
  1160. min(x["ranks"]) if x["ranks"] else 999,
  1161. -x["count"],
  1162. ),
  1163. )
  1164. # 应用最大显示数量限制(优先级:单独配置 > 全局配置)
  1165. group_max_count = group_key_to_max_count.get(group_key, 0)
  1166. if group_max_count == 0:
  1167. # 使用全局配置
  1168. group_max_count = CONFIG.get("MAX_NEWS_PER_KEYWORD", 0)
  1169. if group_max_count > 0:
  1170. sorted_titles = sorted_titles[:group_max_count]
  1171. stats.append(
  1172. {
  1173. "word": group_key,
  1174. "count": data["count"],
  1175. "position": group_key_to_position.get(group_key, 999),
  1176. "titles": sorted_titles,
  1177. "percentage": (
  1178. round(data["count"] / total_titles * 100, 2)
  1179. if total_titles > 0
  1180. else 0
  1181. ),
  1182. }
  1183. )
  1184. # 根据配置选择排序优先级
  1185. if CONFIG.get("SORT_BY_POSITION_FIRST", False):
  1186. # 先按配置位置,再按热点条数
  1187. stats.sort(key=lambda x: (x["position"], -x["count"]))
  1188. else:
  1189. # 先按热点条数,再按配置位置(原逻辑)
  1190. stats.sort(key=lambda x: (-x["count"], x["position"]))
  1191. return stats, total_titles
  1192. # === 报告生成 ===
  1193. def prepare_report_data(
  1194. stats: List[Dict],
  1195. failed_ids: Optional[List] = None,
  1196. new_titles: Optional[Dict] = None,
  1197. id_to_name: Optional[Dict] = None,
  1198. mode: str = "daily",
  1199. ) -> Dict:
  1200. """准备报告数据"""
  1201. processed_new_titles = []
  1202. # 在增量模式下隐藏新增新闻区域
  1203. hide_new_section = mode == "incremental"
  1204. # 只有在非隐藏模式下才处理新增新闻部分
  1205. if not hide_new_section:
  1206. filtered_new_titles = {}
  1207. if new_titles and id_to_name:
  1208. word_groups, filter_words = load_frequency_words()
  1209. for source_id, titles_data in new_titles.items():
  1210. filtered_titles = {}
  1211. for title, title_data in titles_data.items():
  1212. if matches_word_groups(title, word_groups, filter_words):
  1213. filtered_titles[title] = title_data
  1214. if filtered_titles:
  1215. filtered_new_titles[source_id] = filtered_titles
  1216. if filtered_new_titles and id_to_name:
  1217. for source_id, titles_data in filtered_new_titles.items():
  1218. source_name = id_to_name.get(source_id, source_id)
  1219. source_titles = []
  1220. for title, title_data in titles_data.items():
  1221. url = title_data.get("url", "")
  1222. mobile_url = title_data.get("mobileUrl", "")
  1223. ranks = title_data.get("ranks", [])
  1224. processed_title = {
  1225. "title": title,
  1226. "source_name": source_name,
  1227. "time_display": "",
  1228. "count": 1,
  1229. "ranks": ranks,
  1230. "rank_threshold": CONFIG["RANK_THRESHOLD"],
  1231. "url": url,
  1232. "mobile_url": mobile_url,
  1233. "is_new": True,
  1234. }
  1235. source_titles.append(processed_title)
  1236. if source_titles:
  1237. processed_new_titles.append(
  1238. {
  1239. "source_id": source_id,
  1240. "source_name": source_name,
  1241. "titles": source_titles,
  1242. }
  1243. )
  1244. processed_stats = []
  1245. for stat in stats:
  1246. if stat["count"] <= 0:
  1247. continue
  1248. processed_titles = []
  1249. for title_data in stat["titles"]:
  1250. processed_title = {
  1251. "title": title_data["title"],
  1252. "source_name": title_data["source_name"],
  1253. "time_display": title_data["time_display"],
  1254. "count": title_data["count"],
  1255. "ranks": title_data["ranks"],
  1256. "rank_threshold": title_data["rank_threshold"],
  1257. "url": title_data.get("url", ""),
  1258. "mobile_url": title_data.get("mobileUrl", ""),
  1259. "is_new": title_data.get("is_new", False),
  1260. }
  1261. processed_titles.append(processed_title)
  1262. processed_stats.append(
  1263. {
  1264. "word": stat["word"],
  1265. "count": stat["count"],
  1266. "percentage": stat.get("percentage", 0),
  1267. "titles": processed_titles,
  1268. }
  1269. )
  1270. return {
  1271. "stats": processed_stats,
  1272. "new_titles": processed_new_titles,
  1273. "failed_ids": failed_ids or [],
  1274. "total_new_count": sum(
  1275. len(source["titles"]) for source in processed_new_titles
  1276. ),
  1277. }
  1278. def format_title_for_platform(
  1279. platform: str, title_data: Dict, show_source: bool = True
  1280. ) -> str:
  1281. """统一的标题格式化方法"""
  1282. rank_display = format_rank_display(
  1283. title_data["ranks"], title_data["rank_threshold"], platform
  1284. )
  1285. link_url = title_data["mobile_url"] or title_data["url"]
  1286. cleaned_title = clean_title(title_data["title"])
  1287. if platform == "feishu":
  1288. if link_url:
  1289. formatted_title = f"[{cleaned_title}]({link_url})"
  1290. else:
  1291. formatted_title = cleaned_title
  1292. title_prefix = "🆕 " if title_data.get("is_new") else ""
  1293. if show_source:
  1294. result = f"<font color='grey'>[{title_data['source_name']}]</font> {title_prefix}{formatted_title}"
  1295. else:
  1296. result = f"{title_prefix}{formatted_title}"
  1297. if rank_display:
  1298. result += f" {rank_display}"
  1299. if title_data["time_display"]:
  1300. result += f" <font color='grey'>- {title_data['time_display']}</font>"
  1301. if title_data["count"] > 1:
  1302. result += f" <font color='green'>({title_data['count']}次)</font>"
  1303. return result
  1304. elif platform == "dingtalk":
  1305. if link_url:
  1306. formatted_title = f"[{cleaned_title}]({link_url})"
  1307. else:
  1308. formatted_title = cleaned_title
  1309. title_prefix = "🆕 " if title_data.get("is_new") else ""
  1310. if show_source:
  1311. result = f"[{title_data['source_name']}] {title_prefix}{formatted_title}"
  1312. else:
  1313. result = f"{title_prefix}{formatted_title}"
  1314. if rank_display:
  1315. result += f" {rank_display}"
  1316. if title_data["time_display"]:
  1317. result += f" - {title_data['time_display']}"
  1318. if title_data["count"] > 1:
  1319. result += f" ({title_data['count']}次)"
  1320. return result
  1321. elif platform in ("wework", "bark"):
  1322. # WeWork 和 Bark 使用 markdown 格式
  1323. if link_url:
  1324. formatted_title = f"[{cleaned_title}]({link_url})"
  1325. else:
  1326. formatted_title = cleaned_title
  1327. title_prefix = "🆕 " if title_data.get("is_new") else ""
  1328. if show_source:
  1329. result = f"[{title_data['source_name']}] {title_prefix}{formatted_title}"
  1330. else:
  1331. result = f"{title_prefix}{formatted_title}"
  1332. if rank_display:
  1333. result += f" {rank_display}"
  1334. if title_data["time_display"]:
  1335. result += f" - {title_data['time_display']}"
  1336. if title_data["count"] > 1:
  1337. result += f" ({title_data['count']}次)"
  1338. return result
  1339. elif platform == "telegram":
  1340. if link_url:
  1341. formatted_title = f'<a href="{link_url}">{html_escape(cleaned_title)}</a>'
  1342. else:
  1343. formatted_title = cleaned_title
  1344. title_prefix = "🆕 " if title_data.get("is_new") else ""
  1345. if show_source:
  1346. result = f"[{title_data['source_name']}] {title_prefix}{formatted_title}"
  1347. else:
  1348. result = f"{title_prefix}{formatted_title}"
  1349. if rank_display:
  1350. result += f" {rank_display}"
  1351. if title_data["time_display"]:
  1352. result += f" <code>- {title_data['time_display']}</code>"
  1353. if title_data["count"] > 1:
  1354. result += f" <code>({title_data['count']}次)</code>"
  1355. return result
  1356. elif platform == "ntfy":
  1357. if link_url:
  1358. formatted_title = f"[{cleaned_title}]({link_url})"
  1359. else:
  1360. formatted_title = cleaned_title
  1361. title_prefix = "🆕 " if title_data.get("is_new") else ""
  1362. if show_source:
  1363. result = f"[{title_data['source_name']}] {title_prefix}{formatted_title}"
  1364. else:
  1365. result = f"{title_prefix}{formatted_title}"
  1366. if rank_display:
  1367. result += f" {rank_display}"
  1368. if title_data["time_display"]:
  1369. result += f" `- {title_data['time_display']}`"
  1370. if title_data["count"] > 1:
  1371. result += f" `({title_data['count']}次)`"
  1372. return result
  1373. elif platform == "slack":
  1374. # Slack 使用 mrkdwn 格式
  1375. if link_url:
  1376. # Slack 链接格式: <url|text>
  1377. formatted_title = f"<{link_url}|{cleaned_title}>"
  1378. else:
  1379. formatted_title = cleaned_title
  1380. title_prefix = "🆕 " if title_data.get("is_new") else ""
  1381. if show_source:
  1382. result = f"[{title_data['source_name']}] {title_prefix}{formatted_title}"
  1383. else:
  1384. result = f"{title_prefix}{formatted_title}"
  1385. # 排名(使用 * 加粗)
  1386. rank_display = format_rank_display(
  1387. title_data["ranks"], title_data["rank_threshold"], "slack"
  1388. )
  1389. if rank_display:
  1390. result += f" {rank_display}"
  1391. if title_data["time_display"]:
  1392. result += f" `- {title_data['time_display']}`"
  1393. if title_data["count"] > 1:
  1394. result += f" `({title_data['count']}次)`"
  1395. return result
  1396. elif platform == "html":
  1397. rank_display = format_rank_display(
  1398. title_data["ranks"], title_data["rank_threshold"], "html"
  1399. )
  1400. link_url = title_data["mobile_url"] or title_data["url"]
  1401. escaped_title = html_escape(cleaned_title)
  1402. escaped_source_name = html_escape(title_data["source_name"])
  1403. if link_url:
  1404. escaped_url = html_escape(link_url)
  1405. formatted_title = f'[{escaped_source_name}] <a href="{escaped_url}" target="_blank" class="news-link">{escaped_title}</a>'
  1406. else:
  1407. formatted_title = (
  1408. f'[{escaped_source_name}] <span class="no-link">{escaped_title}</span>'
  1409. )
  1410. if rank_display:
  1411. formatted_title += f" {rank_display}"
  1412. if title_data["time_display"]:
  1413. escaped_time = html_escape(title_data["time_display"])
  1414. formatted_title += f" <font color='grey'>- {escaped_time}</font>"
  1415. if title_data["count"] > 1:
  1416. formatted_title += f" <font color='green'>({title_data['count']}次)</font>"
  1417. if title_data.get("is_new"):
  1418. formatted_title = f"<div class='new-title'>🆕 {formatted_title}</div>"
  1419. return formatted_title
  1420. else:
  1421. return cleaned_title
  1422. def generate_html_report(
  1423. stats: List[Dict],
  1424. total_titles: int,
  1425. failed_ids: Optional[List] = None,
  1426. new_titles: Optional[Dict] = None,
  1427. id_to_name: Optional[Dict] = None,
  1428. mode: str = "daily",
  1429. is_daily_summary: bool = False,
  1430. update_info: Optional[Dict] = None,
  1431. ) -> str:
  1432. """生成HTML报告"""
  1433. if is_daily_summary:
  1434. if mode == "current":
  1435. filename = "当前榜单汇总.html"
  1436. elif mode == "incremental":
  1437. filename = "当日增量.html"
  1438. else:
  1439. filename = "当日汇总.html"
  1440. else:
  1441. filename = f"{format_time_filename()}.html"
  1442. file_path = get_output_path("html", filename)
  1443. report_data = prepare_report_data(stats, failed_ids, new_titles, id_to_name, mode)
  1444. html_content = render_html_content(
  1445. report_data, total_titles, is_daily_summary, mode, update_info
  1446. )
  1447. with open(file_path, "w", encoding="utf-8") as f:
  1448. f.write(html_content)
  1449. if is_daily_summary:
  1450. root_file_path = Path("index.html")
  1451. with open(root_file_path, "w", encoding="utf-8") as f:
  1452. f.write(html_content)
  1453. return file_path
  1454. def render_html_content(
  1455. report_data: Dict,
  1456. total_titles: int,
  1457. is_daily_summary: bool = False,
  1458. mode: str = "daily",
  1459. update_info: Optional[Dict] = None,
  1460. ) -> str:
  1461. """渲染HTML内容"""
  1462. html = """
  1463. <!DOCTYPE html>
  1464. <html>
  1465. <head>
  1466. <meta charset="UTF-8">
  1467. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  1468. <title>热点新闻分析</title>
  1469. <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js" integrity="sha512-BNaRQnYJYiPSqHHDb58B0yaPfCu+Wgds8Gp/gU33kqBtgNS4tSPHuGibyoeqMV/TJlSKda6FXzoEyYGjTe+vXA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
  1470. <style>
  1471. * { box-sizing: border-box; }
  1472. body {
  1473. font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', system-ui, sans-serif;
  1474. margin: 0;
  1475. padding: 16px;
  1476. background: #fafafa;
  1477. color: #333;
  1478. line-height: 1.5;
  1479. }
  1480. .container {
  1481. max-width: 600px;
  1482. margin: 0 auto;
  1483. background: white;
  1484. border-radius: 12px;
  1485. overflow: hidden;
  1486. box-shadow: 0 2px 16px rgba(0,0,0,0.06);
  1487. }
  1488. .header {
  1489. background: linear-gradient(135deg, #4f46e5 0%, #7c3aed 100%);
  1490. color: white;
  1491. padding: 32px 24px;
  1492. text-align: center;
  1493. position: relative;
  1494. }
  1495. .save-buttons {
  1496. position: absolute;
  1497. top: 16px;
  1498. right: 16px;
  1499. display: flex;
  1500. gap: 8px;
  1501. }
  1502. .save-btn {
  1503. background: rgba(255, 255, 255, 0.2);
  1504. border: 1px solid rgba(255, 255, 255, 0.3);
  1505. color: white;
  1506. padding: 8px 16px;
  1507. border-radius: 6px;
  1508. cursor: pointer;
  1509. font-size: 13px;
  1510. font-weight: 500;
  1511. transition: all 0.2s ease;
  1512. backdrop-filter: blur(10px);
  1513. white-space: nowrap;
  1514. }
  1515. .save-btn:hover {
  1516. background: rgba(255, 255, 255, 0.3);
  1517. border-color: rgba(255, 255, 255, 0.5);
  1518. transform: translateY(-1px);
  1519. }
  1520. .save-btn:active {
  1521. transform: translateY(0);
  1522. }
  1523. .save-btn:disabled {
  1524. opacity: 0.6;
  1525. cursor: not-allowed;
  1526. }
  1527. .header-title {
  1528. font-size: 22px;
  1529. font-weight: 700;
  1530. margin: 0 0 20px 0;
  1531. }
  1532. .header-info {
  1533. display: grid;
  1534. grid-template-columns: 1fr 1fr;
  1535. gap: 16px;
  1536. font-size: 14px;
  1537. opacity: 0.95;
  1538. }
  1539. .info-item {
  1540. text-align: center;
  1541. }
  1542. .info-label {
  1543. display: block;
  1544. font-size: 12px;
  1545. opacity: 0.8;
  1546. margin-bottom: 4px;
  1547. }
  1548. .info-value {
  1549. font-weight: 600;
  1550. font-size: 16px;
  1551. }
  1552. .content {
  1553. padding: 24px;
  1554. }
  1555. .word-group {
  1556. margin-bottom: 40px;
  1557. }
  1558. .word-group:first-child {
  1559. margin-top: 0;
  1560. }
  1561. .word-header {
  1562. display: flex;
  1563. align-items: center;
  1564. justify-content: space-between;
  1565. margin-bottom: 20px;
  1566. padding-bottom: 8px;
  1567. border-bottom: 1px solid #f0f0f0;
  1568. }
  1569. .word-info {
  1570. display: flex;
  1571. align-items: center;
  1572. gap: 12px;
  1573. }
  1574. .word-name {
  1575. font-size: 17px;
  1576. font-weight: 600;
  1577. color: #1a1a1a;
  1578. }
  1579. .word-count {
  1580. color: #666;
  1581. font-size: 13px;
  1582. font-weight: 500;
  1583. }
  1584. .word-count.hot { color: #dc2626; font-weight: 600; }
  1585. .word-count.warm { color: #ea580c; font-weight: 600; }
  1586. .word-index {
  1587. color: #999;
  1588. font-size: 12px;
  1589. }
  1590. .news-item {
  1591. margin-bottom: 20px;
  1592. padding: 16px 0;
  1593. border-bottom: 1px solid #f5f5f5;
  1594. position: relative;
  1595. display: flex;
  1596. gap: 12px;
  1597. align-items: center;
  1598. }
  1599. .news-item:last-child {
  1600. border-bottom: none;
  1601. }
  1602. .news-item.new::after {
  1603. content: "NEW";
  1604. position: absolute;
  1605. top: 12px;
  1606. right: 0;
  1607. background: #fbbf24;
  1608. color: #92400e;
  1609. font-size: 9px;
  1610. font-weight: 700;
  1611. padding: 3px 6px;
  1612. border-radius: 4px;
  1613. letter-spacing: 0.5px;
  1614. }
  1615. .news-number {
  1616. color: #999;
  1617. font-size: 13px;
  1618. font-weight: 600;
  1619. min-width: 20px;
  1620. text-align: center;
  1621. flex-shrink: 0;
  1622. background: #f8f9fa;
  1623. border-radius: 50%;
  1624. width: 24px;
  1625. height: 24px;
  1626. display: flex;
  1627. align-items: center;
  1628. justify-content: center;
  1629. align-self: flex-start;
  1630. margin-top: 8px;
  1631. }
  1632. .news-content {
  1633. flex: 1;
  1634. min-width: 0;
  1635. padding-right: 40px;
  1636. }
  1637. .news-item.new .news-content {
  1638. padding-right: 50px;
  1639. }
  1640. .news-header {
  1641. display: flex;
  1642. align-items: center;
  1643. gap: 8px;
  1644. margin-bottom: 8px;
  1645. flex-wrap: wrap;
  1646. }
  1647. .source-name {
  1648. color: #666;
  1649. font-size: 12px;
  1650. font-weight: 500;
  1651. }
  1652. .rank-num {
  1653. color: #fff;
  1654. background: #6b7280;
  1655. font-size: 10px;
  1656. font-weight: 700;
  1657. padding: 2px 6px;
  1658. border-radius: 10px;
  1659. min-width: 18px;
  1660. text-align: center;
  1661. }
  1662. .rank-num.top { background: #dc2626; }
  1663. .rank-num.high { background: #ea580c; }
  1664. .time-info {
  1665. color: #999;
  1666. font-size: 11px;
  1667. }
  1668. .count-info {
  1669. color: #059669;
  1670. font-size: 11px;
  1671. font-weight: 500;
  1672. }
  1673. .news-title {
  1674. font-size: 15px;
  1675. line-height: 1.4;
  1676. color: #1a1a1a;
  1677. margin: 0;
  1678. }
  1679. .news-link {
  1680. color: #2563eb;
  1681. text-decoration: none;
  1682. }
  1683. .news-link:hover {
  1684. text-decoration: underline;
  1685. }
  1686. .news-link:visited {
  1687. color: #7c3aed;
  1688. }
  1689. .new-section {
  1690. margin-top: 40px;
  1691. padding-top: 24px;
  1692. border-top: 2px solid #f0f0f0;
  1693. }
  1694. .new-section-title {
  1695. color: #1a1a1a;
  1696. font-size: 16px;
  1697. font-weight: 600;
  1698. margin: 0 0 20px 0;
  1699. }
  1700. .new-source-group {
  1701. margin-bottom: 24px;
  1702. }
  1703. .new-source-title {
  1704. color: #666;
  1705. font-size: 13px;
  1706. font-weight: 500;
  1707. margin: 0 0 12px 0;
  1708. padding-bottom: 6px;
  1709. border-bottom: 1px solid #f5f5f5;
  1710. }
  1711. .new-item {
  1712. display: flex;
  1713. align-items: center;
  1714. gap: 12px;
  1715. padding: 8px 0;
  1716. border-bottom: 1px solid #f9f9f9;
  1717. }
  1718. .new-item:last-child {
  1719. border-bottom: none;
  1720. }
  1721. .new-item-number {
  1722. color: #999;
  1723. font-size: 12px;
  1724. font-weight: 600;
  1725. min-width: 18px;
  1726. text-align: center;
  1727. flex-shrink: 0;
  1728. background: #f8f9fa;
  1729. border-radius: 50%;
  1730. width: 20px;
  1731. height: 20px;
  1732. display: flex;
  1733. align-items: center;
  1734. justify-content: center;
  1735. }
  1736. .new-item-rank {
  1737. color: #fff;
  1738. background: #6b7280;
  1739. font-size: 10px;
  1740. font-weight: 700;
  1741. padding: 3px 6px;
  1742. border-radius: 8px;
  1743. min-width: 20px;
  1744. text-align: center;
  1745. flex-shrink: 0;
  1746. }
  1747. .new-item-rank.top { background: #dc2626; }
  1748. .new-item-rank.high { background: #ea580c; }
  1749. .new-item-content {
  1750. flex: 1;
  1751. min-width: 0;
  1752. }
  1753. .new-item-title {
  1754. font-size: 14px;
  1755. line-height: 1.4;
  1756. color: #1a1a1a;
  1757. margin: 0;
  1758. }
  1759. .error-section {
  1760. background: #fef2f2;
  1761. border: 1px solid #fecaca;
  1762. border-radius: 8px;
  1763. padding: 16px;
  1764. margin-bottom: 24px;
  1765. }
  1766. .error-title {
  1767. color: #dc2626;
  1768. font-size: 14px;
  1769. font-weight: 600;
  1770. margin: 0 0 8px 0;
  1771. }
  1772. .error-list {
  1773. list-style: none;
  1774. padding: 0;
  1775. margin: 0;
  1776. }
  1777. .error-item {
  1778. color: #991b1b;
  1779. font-size: 13px;
  1780. padding: 2px 0;
  1781. font-family: 'SF Mono', Consolas, monospace;
  1782. }
  1783. .footer {
  1784. margin-top: 32px;
  1785. padding: 20px 24px;
  1786. background: #f8f9fa;
  1787. border-top: 1px solid #e5e7eb;
  1788. text-align: center;
  1789. }
  1790. .footer-content {
  1791. font-size: 13px;
  1792. color: #6b7280;
  1793. line-height: 1.6;
  1794. }
  1795. .footer-link {
  1796. color: #4f46e5;
  1797. text-decoration: none;
  1798. font-weight: 500;
  1799. transition: color 0.2s ease;
  1800. }
  1801. .footer-link:hover {
  1802. color: #7c3aed;
  1803. text-decoration: underline;
  1804. }
  1805. .project-name {
  1806. font-weight: 600;
  1807. color: #374151;
  1808. }
  1809. @media (max-width: 480px) {
  1810. body { padding: 12px; }
  1811. .header { padding: 24px 20px; }
  1812. .content { padding: 20px; }
  1813. .footer { padding: 16px 20px; }
  1814. .header-info { grid-template-columns: 1fr; gap: 12px; }
  1815. .news-header { gap: 6px; }
  1816. .news-content { padding-right: 45px; }
  1817. .news-item { gap: 8px; }
  1818. .new-item { gap: 8px; }
  1819. .news-number { width: 20px; height: 20px; font-size: 12px; }
  1820. .save-buttons {
  1821. position: static;
  1822. margin-bottom: 16px;
  1823. display: flex;
  1824. gap: 8px;
  1825. justify-content: center;
  1826. flex-direction: column;
  1827. width: 100%;
  1828. }
  1829. .save-btn {
  1830. width: 100%;
  1831. }
  1832. }
  1833. </style>
  1834. </head>
  1835. <body>
  1836. <div class="container">
  1837. <div class="header">
  1838. <div class="save-buttons">
  1839. <button class="save-btn" onclick="saveAsImage()">保存为图片</button>
  1840. <button class="save-btn" onclick="saveAsMultipleImages()">分段保存</button>
  1841. </div>
  1842. <div class="header-title">热点新闻分析</div>
  1843. <div class="header-info">
  1844. <div class="info-item">
  1845. <span class="info-label">报告类型</span>
  1846. <span class="info-value">"""
  1847. # 处理报告类型显示
  1848. if is_daily_summary:
  1849. if mode == "current":
  1850. html += "当前榜单"
  1851. elif mode == "incremental":
  1852. html += "增量模式"
  1853. else:
  1854. html += "当日汇总"
  1855. else:
  1856. html += "实时分析"
  1857. html += """</span>
  1858. </div>
  1859. <div class="info-item">
  1860. <span class="info-label">新闻总数</span>
  1861. <span class="info-value">"""
  1862. html += f"{total_titles} 条"
  1863. # 计算筛选后的热点新闻数量
  1864. hot_news_count = sum(len(stat["titles"]) for stat in report_data["stats"])
  1865. html += """</span>
  1866. </div>
  1867. <div class="info-item">
  1868. <span class="info-label">热点新闻</span>
  1869. <span class="info-value">"""
  1870. html += f"{hot_news_count} 条"
  1871. html += """</span>
  1872. </div>
  1873. <div class="info-item">
  1874. <span class="info-label">生成时间</span>
  1875. <span class="info-value">"""
  1876. now = get_beijing_time()
  1877. html += now.strftime("%m-%d %H:%M")
  1878. html += """</span>
  1879. </div>
  1880. </div>
  1881. </div>
  1882. <div class="content">"""
  1883. # 处理失败ID错误信息
  1884. if report_data["failed_ids"]:
  1885. html += """
  1886. <div class="error-section">
  1887. <div class="error-title">⚠️ 请求失败的平台</div>
  1888. <ul class="error-list">"""
  1889. for id_value in report_data["failed_ids"]:
  1890. html += f'<li class="error-item">{html_escape(id_value)}</li>'
  1891. html += """
  1892. </ul>
  1893. </div>"""
  1894. # 处理主要统计数据
  1895. if report_data["stats"]:
  1896. total_count = len(report_data["stats"])
  1897. for i, stat in enumerate(report_data["stats"], 1):
  1898. count = stat["count"]
  1899. # 确定热度等级
  1900. if count >= 10:
  1901. count_class = "hot"
  1902. elif count >= 5:
  1903. count_class = "warm"
  1904. else:
  1905. count_class = ""
  1906. escaped_word = html_escape(stat["word"])
  1907. html += f"""
  1908. <div class="word-group">
  1909. <div class="word-header">
  1910. <div class="word-info">
  1911. <div class="word-name">{escaped_word}</div>
  1912. <div class="word-count {count_class}">{count} 条</div>
  1913. </div>
  1914. <div class="word-index">{i}/{total_count}</div>
  1915. </div>"""
  1916. # 处理每个词组下的新闻标题,给每条新闻标上序号
  1917. for j, title_data in enumerate(stat["titles"], 1):
  1918. is_new = title_data.get("is_new", False)
  1919. new_class = "new" if is_new else ""
  1920. html += f"""
  1921. <div class="news-item {new_class}">
  1922. <div class="news-number">{j}</div>
  1923. <div class="news-content">
  1924. <div class="news-header">
  1925. <span class="source-name">{html_escape(title_data["source_name"])}</span>"""
  1926. # 处理排名显示
  1927. ranks = title_data.get("ranks", [])
  1928. if ranks:
  1929. min_rank = min(ranks)
  1930. max_rank = max(ranks)
  1931. rank_threshold = title_data.get("rank_threshold", 10)
  1932. # 确定排名等级
  1933. if min_rank <= 3:
  1934. rank_class = "top"
  1935. elif min_rank <= rank_threshold:
  1936. rank_class = "high"
  1937. else:
  1938. rank_class = ""
  1939. if min_rank == max_rank:
  1940. rank_text = str(min_rank)
  1941. else:
  1942. rank_text = f"{min_rank}-{max_rank}"
  1943. html += f'<span class="rank-num {rank_class}">{rank_text}</span>'
  1944. # 处理时间显示
  1945. time_display = title_data.get("time_display", "")
  1946. if time_display:
  1947. # 简化时间显示格式,将波浪线替换为~
  1948. simplified_time = (
  1949. time_display.replace(" ~ ", "~")
  1950. .replace("[", "")
  1951. .replace("]", "")
  1952. )
  1953. html += (
  1954. f'<span class="time-info">{html_escape(simplified_time)}</span>'
  1955. )
  1956. # 处理出现次数
  1957. count_info = title_data.get("count", 1)
  1958. if count_info > 1:
  1959. html += f'<span class="count-info">{count_info}次</span>'
  1960. html += """
  1961. </div>
  1962. <div class="news-title">"""
  1963. # 处理标题和链接
  1964. escaped_title = html_escape(title_data["title"])
  1965. link_url = title_data.get("mobile_url") or title_data.get("url", "")
  1966. if link_url:
  1967. escaped_url = html_escape(link_url)
  1968. html += f'<a href="{escaped_url}" target="_blank" class="news-link">{escaped_title}</a>'
  1969. else:
  1970. html += escaped_title
  1971. html += """
  1972. </div>
  1973. </div>
  1974. </div>"""
  1975. html += """
  1976. </div>"""
  1977. # 处理新增新闻区域
  1978. if report_data["new_titles"]:
  1979. html += f"""
  1980. <div class="new-section">
  1981. <div class="new-section-title">本次新增热点 (共 {report_data['total_new_count']} 条)</div>"""
  1982. for source_data in report_data["new_titles"]:
  1983. escaped_source = html_escape(source_data["source_name"])
  1984. titles_count = len(source_data["titles"])
  1985. html += f"""
  1986. <div class="new-source-group">
  1987. <div class="new-source-title">{escaped_source} · {titles_count}条</div>"""
  1988. # 为新增新闻也添加序号
  1989. for idx, title_data in enumerate(source_data["titles"], 1):
  1990. ranks = title_data.get("ranks", [])
  1991. # 处理新增新闻的排名显示
  1992. rank_class = ""
  1993. if ranks:
  1994. min_rank = min(ranks)
  1995. if min_rank <= 3:
  1996. rank_class = "top"
  1997. elif min_rank <= title_data.get("rank_threshold", 10):
  1998. rank_class = "high"
  1999. if len(ranks) == 1:
  2000. rank_text = str(ranks[0])
  2001. else:
  2002. rank_text = f"{min(ranks)}-{max(ranks)}"
  2003. else:
  2004. rank_text = "?"
  2005. html += f"""
  2006. <div class="new-item">
  2007. <div class="new-item-number">{idx}</div>
  2008. <div class="new-item-rank {rank_class}">{rank_text}</div>
  2009. <div class="new-item-content">
  2010. <div class="new-item-title">"""
  2011. # 处理新增新闻的链接
  2012. escaped_title = html_escape(title_data["title"])
  2013. link_url = title_data.get("mobile_url") or title_data.get("url", "")
  2014. if link_url:
  2015. escaped_url = html_escape(link_url)
  2016. html += f'<a href="{escaped_url}" target="_blank" class="news-link">{escaped_title}</a>'
  2017. else:
  2018. html += escaped_title
  2019. html += """
  2020. </div>
  2021. </div>
  2022. </div>"""
  2023. html += """
  2024. </div>"""
  2025. html += """
  2026. </div>"""
  2027. html += """
  2028. </div>
  2029. <div class="footer">
  2030. <div class="footer-content">
  2031. 由 <span class="project-name">TrendRadar</span> 生成 ·
  2032. <a href="https://github.com/sansan0/TrendRadar" target="_blank" class="footer-link">
  2033. GitHub 开源项目
  2034. </a>"""
  2035. if update_info:
  2036. html += f"""
  2037. <br>
  2038. <span style="color: #ea580c; font-weight: 500;">
  2039. 发现新版本 {update_info['remote_version']},当前版本 {update_info['current_version']}
  2040. </span>"""
  2041. html += """
  2042. </div>
  2043. </div>
  2044. </div>
  2045. <script>
  2046. async function saveAsImage() {
  2047. const button = event.target;
  2048. const originalText = button.textContent;
  2049. try {
  2050. button.textContent = '生成中...';
  2051. button.disabled = true;
  2052. window.scrollTo(0, 0);
  2053. // 等待页面稳定
  2054. await new Promise(resolve => setTimeout(resolve, 200));
  2055. // 截图前隐藏按钮
  2056. const buttons = document.querySelector('.save-buttons');
  2057. buttons.style.visibility = 'hidden';
  2058. // 再次等待确保按钮完全隐藏
  2059. await new Promise(resolve => setTimeout(resolve, 100));
  2060. const container = document.querySelector('.container');
  2061. const canvas = await html2canvas(container, {
  2062. backgroundColor: '#ffffff',
  2063. scale: 1.5,
  2064. useCORS: true,
  2065. allowTaint: false,
  2066. imageTimeout: 10000,
  2067. removeContainer: false,
  2068. foreignObjectRendering: false,
  2069. logging: false,
  2070. width: container.offsetWidth,
  2071. height: container.offsetHeight,
  2072. x: 0,
  2073. y: 0,
  2074. scrollX: 0,
  2075. scrollY: 0,
  2076. windowWidth: window.innerWidth,
  2077. windowHeight: window.innerHeight
  2078. });
  2079. buttons.style.visibility = 'visible';
  2080. const link = document.createElement('a');
  2081. const now = new Date();
  2082. const filename = `TrendRadar_热点新闻分析_${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}_${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}.png`;
  2083. link.download = filename;
  2084. link.href = canvas.toDataURL('image/png', 1.0);
  2085. // 触发下载
  2086. document.body.appendChild(link);
  2087. link.click();
  2088. document.body.removeChild(link);
  2089. button.textContent = '保存成功!';
  2090. setTimeout(() => {
  2091. button.textContent = originalText;
  2092. button.disabled = false;
  2093. }, 2000);
  2094. } catch (error) {
  2095. const buttons = document.querySelector('.save-buttons');
  2096. buttons.style.visibility = 'visible';
  2097. button.textContent = '保存失败';
  2098. setTimeout(() => {
  2099. button.textContent = originalText;
  2100. button.disabled = false;
  2101. }, 2000);
  2102. }
  2103. }
  2104. async function saveAsMultipleImages() {
  2105. const button = event.target;
  2106. const originalText = button.textContent;
  2107. const container = document.querySelector('.container');
  2108. const scale = 1.5;
  2109. const maxHeight = 5000 / scale;
  2110. try {
  2111. button.textContent = '分析中...';
  2112. button.disabled = true;
  2113. // 获取所有可能的分割元素
  2114. const newsItems = Array.from(container.querySelectorAll('.news-item'));
  2115. const wordGroups = Array.from(container.querySelectorAll('.word-group'));
  2116. const newSection = container.querySelector('.new-section');
  2117. const errorSection = container.querySelector('.error-section');
  2118. const header = container.querySelector('.header');
  2119. const footer = container.querySelector('.footer');
  2120. // 计算元素位置和高度
  2121. const containerRect = container.getBoundingClientRect();
  2122. const elements = [];
  2123. // 添加header作为必须包含的元素
  2124. elements.push({
  2125. type: 'header',
  2126. element: header,
  2127. top: 0,
  2128. bottom: header.offsetHeight,
  2129. height: header.offsetHeight
  2130. });
  2131. // 添加错误信息(如果存在)
  2132. if (errorSection) {
  2133. const rect = errorSection.getBoundingClientRect();
  2134. elements.push({
  2135. type: 'error',
  2136. element: errorSection,
  2137. top: rect.top - containerRect.top,
  2138. bottom: rect.bottom - containerRect.top,
  2139. height: rect.height
  2140. });
  2141. }
  2142. // 按word-group分组处理news-item
  2143. wordGroups.forEach(group => {
  2144. const groupRect = group.getBoundingClientRect();
  2145. const groupNewsItems = group.querySelectorAll('.news-item');
  2146. // 添加word-group的header部分
  2147. const wordHeader = group.querySelector('.word-header');
  2148. if (wordHeader) {
  2149. const headerRect = wordHeader.getBoundingClientRect();
  2150. elements.push({
  2151. type: 'word-header',
  2152. element: wordHeader,
  2153. parent: group,
  2154. top: groupRect.top - containerRect.top,
  2155. bottom: headerRect.bottom - containerRect.top,
  2156. height: headerRect.height
  2157. });
  2158. }
  2159. // 添加每个news-item
  2160. groupNewsItems.forEach(item => {
  2161. const rect = item.getBoundingClientRect();
  2162. elements.push({
  2163. type: 'news-item',
  2164. element: item,
  2165. parent: group,
  2166. top: rect.top - containerRect.top,
  2167. bottom: rect.bottom - containerRect.top,
  2168. height: rect.height
  2169. });
  2170. });
  2171. });
  2172. // 添加新增新闻部分
  2173. if (newSection) {
  2174. const rect = newSection.getBoundingClientRect();
  2175. elements.push({
  2176. type: 'new-section',
  2177. element: newSection,
  2178. top: rect.top - containerRect.top,
  2179. bottom: rect.bottom - containerRect.top,
  2180. height: rect.height
  2181. });
  2182. }
  2183. // 添加footer
  2184. const footerRect = footer.getBoundingClientRect();
  2185. elements.push({
  2186. type: 'footer',
  2187. element: footer,
  2188. top: footerRect.top - containerRect.top,
  2189. bottom: footerRect.bottom - containerRect.top,
  2190. height: footer.offsetHeight
  2191. });
  2192. // 计算分割点
  2193. const segments = [];
  2194. let currentSegment = { start: 0, end: 0, height: 0, includeHeader: true };
  2195. let headerHeight = header.offsetHeight;
  2196. currentSegment.height = headerHeight;
  2197. for (let i = 1; i < elements.length; i++) {
  2198. const element = elements[i];
  2199. const potentialHeight = element.bottom - currentSegment.start;
  2200. // 检查是否需要创建新分段
  2201. if (potentialHeight > maxHeight && currentSegment.height > headerHeight) {
  2202. // 在前一个元素结束处分割
  2203. currentSegment.end = elements[i - 1].bottom;
  2204. segments.push(currentSegment);
  2205. // 开始新分段
  2206. currentSegment = {
  2207. start: currentSegment.end,
  2208. end: 0,
  2209. height: element.bottom - currentSegment.end,
  2210. includeHeader: false
  2211. };
  2212. } else {
  2213. currentSegment.height = potentialHeight;
  2214. currentSegment.end = element.bottom;
  2215. }
  2216. }
  2217. // 添加最后一个分段
  2218. if (currentSegment.height > 0) {
  2219. currentSegment.end = container.offsetHeight;
  2220. segments.push(currentSegment);
  2221. }
  2222. button.textContent = `生成中 (0/${segments.length})...`;
  2223. // 隐藏保存按钮
  2224. const buttons = document.querySelector('.save-buttons');
  2225. buttons.style.visibility = 'hidden';
  2226. // 为每个分段生成图片
  2227. const images = [];
  2228. for (let i = 0; i < segments.length; i++) {
  2229. const segment = segments[i];
  2230. button.textContent = `生成中 (${i + 1}/${segments.length})...`;
  2231. // 创建临时容器用于截图
  2232. const tempContainer = document.createElement('div');
  2233. tempContainer.style.cssText = `
  2234. position: absolute;
  2235. left: -9999px;
  2236. top: 0;
  2237. width: ${container.offsetWidth}px;
  2238. background: white;
  2239. `;
  2240. tempContainer.className = 'container';
  2241. // 克隆容器内容
  2242. const clonedContainer = container.cloneNode(true);
  2243. // 移除克隆内容中的保存按钮
  2244. const clonedButtons = clonedContainer.querySelector('.save-buttons');
  2245. if (clonedButtons) {
  2246. clonedButtons.style.display = 'none';
  2247. }
  2248. tempContainer.appendChild(clonedContainer);
  2249. document.body.appendChild(tempContainer);
  2250. // 等待DOM更新
  2251. await new Promise(resolve => setTimeout(resolve, 100));
  2252. // 使用html2canvas截取特定区域
  2253. const canvas = await html2canvas(clonedContainer, {
  2254. backgroundColor: '#ffffff',
  2255. scale: scale,
  2256. useCORS: true,
  2257. allowTaint: false,
  2258. imageTimeout: 10000,
  2259. logging: false,
  2260. width: container.offsetWidth,
  2261. height: segment.end - segment.start,
  2262. x: 0,
  2263. y: segment.start,
  2264. windowWidth: window.innerWidth,
  2265. windowHeight: window.innerHeight
  2266. });
  2267. images.push(canvas.toDataURL('image/png', 1.0));
  2268. // 清理临时容器
  2269. document.body.removeChild(tempContainer);
  2270. }
  2271. // 恢复按钮显示
  2272. buttons.style.visibility = 'visible';
  2273. // 下载所有图片
  2274. const now = new Date();
  2275. const baseFilename = `TrendRadar_热点新闻分析_${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}_${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}`;
  2276. for (let i = 0; i < images.length; i++) {
  2277. const link = document.createElement('a');
  2278. link.download = `${baseFilename}_part${i + 1}.png`;
  2279. link.href = images[i];
  2280. document.body.appendChild(link);
  2281. link.click();
  2282. document.body.removeChild(link);
  2283. // 延迟一下避免浏览器阻止多个下载
  2284. await new Promise(resolve => setTimeout(resolve, 100));
  2285. }
  2286. button.textContent = `已保存 ${segments.length} 张图片!`;
  2287. setTimeout(() => {
  2288. button.textContent = originalText;
  2289. button.disabled = false;
  2290. }, 2000);
  2291. } catch (error) {
  2292. console.error('分段保存失败:', error);
  2293. const buttons = document.querySelector('.save-buttons');
  2294. buttons.style.visibility = 'visible';
  2295. button.textContent = '保存失败';
  2296. setTimeout(() => {
  2297. button.textContent = originalText;
  2298. button.disabled = false;
  2299. }, 2000);
  2300. }
  2301. }
  2302. document.addEventListener('DOMContentLoaded', function() {
  2303. window.scrollTo(0, 0);
  2304. });
  2305. </script>
  2306. </body>
  2307. </html>
  2308. """
  2309. return html
  2310. def render_feishu_content(
  2311. report_data: Dict, update_info: Optional[Dict] = None, mode: str = "daily"
  2312. ) -> str:
  2313. """渲染飞书内容"""
  2314. text_content = ""
  2315. if report_data["stats"]:
  2316. text_content += f"📊 **热点词汇统计**\n\n"
  2317. total_count = len(report_data["stats"])
  2318. for i, stat in enumerate(report_data["stats"]):
  2319. word = stat["word"]
  2320. count = stat["count"]
  2321. sequence_display = f"<font color='grey'>[{i + 1}/{total_count}]</font>"
  2322. if count >= 10:
  2323. text_content += f"🔥 {sequence_display} **{word}** : <font color='red'>{count}</font> 条\n\n"
  2324. elif count >= 5:
  2325. text_content += f"📈 {sequence_display} **{word}** : <font color='orange'>{count}</font> 条\n\n"
  2326. else:
  2327. text_content += f"📌 {sequence_display} **{word}** : {count} 条\n\n"
  2328. for j, title_data in enumerate(stat["titles"], 1):
  2329. formatted_title = format_title_for_platform(
  2330. "feishu", title_data, show_source=True
  2331. )
  2332. text_content += f" {j}. {formatted_title}\n"
  2333. if j < len(stat["titles"]):
  2334. text_content += "\n"
  2335. if i < len(report_data["stats"]) - 1:
  2336. text_content += f"\n{CONFIG['FEISHU_MESSAGE_SEPARATOR']}\n\n"
  2337. if not text_content:
  2338. if mode == "incremental":
  2339. mode_text = "增量模式下暂无新增匹配的热点词汇"
  2340. elif mode == "current":
  2341. mode_text = "当前榜单模式下暂无匹配的热点词汇"
  2342. else:
  2343. mode_text = "暂无匹配的热点词汇"
  2344. text_content = f"📭 {mode_text}\n\n"
  2345. if report_data["new_titles"]:
  2346. if text_content and "暂无匹配" not in text_content:
  2347. text_content += f"\n{CONFIG['FEISHU_MESSAGE_SEPARATOR']}\n\n"
  2348. text_content += (
  2349. f"🆕 **本次新增热点新闻** (共 {report_data['total_new_count']} 条)\n\n"
  2350. )
  2351. for source_data in report_data["new_titles"]:
  2352. text_content += (
  2353. f"**{source_data['source_name']}** ({len(source_data['titles'])} 条):\n"
  2354. )
  2355. for j, title_data in enumerate(source_data["titles"], 1):
  2356. title_data_copy = title_data.copy()
  2357. title_data_copy["is_new"] = False
  2358. formatted_title = format_title_for_platform(
  2359. "feishu", title_data_copy, show_source=False
  2360. )
  2361. text_content += f" {j}. {formatted_title}\n"
  2362. text_content += "\n"
  2363. if report_data["failed_ids"]:
  2364. if text_content and "暂无匹配" not in text_content:
  2365. text_content += f"\n{CONFIG['FEISHU_MESSAGE_SEPARATOR']}\n\n"
  2366. text_content += "⚠️ **数据获取失败的平台:**\n\n"
  2367. for i, id_value in enumerate(report_data["failed_ids"], 1):
  2368. text_content += f" • <font color='red'>{id_value}</font>\n"
  2369. now = get_beijing_time()
  2370. text_content += (
  2371. f"\n\n<font color='grey'>更新时间:{now.strftime('%Y-%m-%d %H:%M:%S')}</font>"
  2372. )
  2373. if update_info:
  2374. text_content += f"\n<font color='grey'>TrendRadar 发现新版本 {update_info['remote_version']},当前 {update_info['current_version']}</font>"
  2375. return text_content
  2376. def render_dingtalk_content(
  2377. report_data: Dict, update_info: Optional[Dict] = None, mode: str = "daily"
  2378. ) -> str:
  2379. """渲染钉钉内容"""
  2380. text_content = ""
  2381. total_titles = sum(
  2382. len(stat["titles"]) for stat in report_data["stats"] if stat["count"] > 0
  2383. )
  2384. now = get_beijing_time()
  2385. text_content += f"**总新闻数:** {total_titles}\n\n"
  2386. text_content += f"**时间:** {now.strftime('%Y-%m-%d %H:%M:%S')}\n\n"
  2387. text_content += f"**类型:** 热点分析报告\n\n"
  2388. text_content += "---\n\n"
  2389. if report_data["stats"]:
  2390. text_content += f"📊 **热点词汇统计**\n\n"
  2391. total_count = len(report_data["stats"])
  2392. for i, stat in enumerate(report_data["stats"]):
  2393. word = stat["word"]
  2394. count = stat["count"]
  2395. sequence_display = f"[{i + 1}/{total_count}]"
  2396. if count >= 10:
  2397. text_content += f"🔥 {sequence_display} **{word}** : **{count}** 条\n\n"
  2398. elif count >= 5:
  2399. text_content += f"📈 {sequence_display} **{word}** : **{count}** 条\n\n"
  2400. else:
  2401. text_content += f"📌 {sequence_display} **{word}** : {count} 条\n\n"
  2402. for j, title_data in enumerate(stat["titles"], 1):
  2403. formatted_title = format_title_for_platform(
  2404. "dingtalk", title_data, show_source=True
  2405. )
  2406. text_content += f" {j}. {formatted_title}\n"
  2407. if j < len(stat["titles"]):
  2408. text_content += "\n"
  2409. if i < len(report_data["stats"]) - 1:
  2410. text_content += f"\n---\n\n"
  2411. if not report_data["stats"]:
  2412. if mode == "incremental":
  2413. mode_text = "增量模式下暂无新增匹配的热点词汇"
  2414. elif mode == "current":
  2415. mode_text = "当前榜单模式下暂无匹配的热点词汇"
  2416. else:
  2417. mode_text = "暂无匹配的热点词汇"
  2418. text_content += f"📭 {mode_text}\n\n"
  2419. if report_data["new_titles"]:
  2420. if text_content and "暂无匹配" not in text_content:
  2421. text_content += f"\n---\n\n"
  2422. text_content += (
  2423. f"🆕 **本次新增热点新闻** (共 {report_data['total_new_count']} 条)\n\n"
  2424. )
  2425. for source_data in report_data["new_titles"]:
  2426. text_content += f"**{source_data['source_name']}** ({len(source_data['titles'])} 条):\n\n"
  2427. for j, title_data in enumerate(source_data["titles"], 1):
  2428. title_data_copy = title_data.copy()
  2429. title_data_copy["is_new"] = False
  2430. formatted_title = format_title_for_platform(
  2431. "dingtalk", title_data_copy, show_source=False
  2432. )
  2433. text_content += f" {j}. {formatted_title}\n"
  2434. text_content += "\n"
  2435. if report_data["failed_ids"]:
  2436. if text_content and "暂无匹配" not in text_content:
  2437. text_content += f"\n---\n\n"
  2438. text_content += "⚠️ **数据获取失败的平台:**\n\n"
  2439. for i, id_value in enumerate(report_data["failed_ids"], 1):
  2440. text_content += f" • **{id_value}**\n"
  2441. text_content += f"\n\n> 更新时间:{now.strftime('%Y-%m-%d %H:%M:%S')}"
  2442. if update_info:
  2443. text_content += f"\n> TrendRadar 发现新版本 **{update_info['remote_version']}**,当前 **{update_info['current_version']}**"
  2444. return text_content
  2445. def _get_batch_header(format_type: str, batch_num: int, total_batches: int) -> str:
  2446. """根据 format_type 生成对应格式的批次头部"""
  2447. if format_type == "telegram":
  2448. return f"<b>[第 {batch_num}/{total_batches} 批次]</b>\n\n"
  2449. elif format_type == "slack":
  2450. return f"*[第 {batch_num}/{total_batches} 批次]*\n\n"
  2451. elif format_type in ("wework_text", "bark"):
  2452. # 企业微信文本模式和 Bark 使用纯文本格式
  2453. return f"[第 {batch_num}/{total_batches} 批次]\n\n"
  2454. else:
  2455. # 飞书、钉钉、ntfy、企业微信 markdown 模式
  2456. return f"**[第 {batch_num}/{total_batches} 批次]**\n\n"
  2457. def _get_max_batch_header_size(format_type: str) -> int:
  2458. """估算批次头部的最大字节数(假设最多 99 批次)
  2459. 用于在分批时预留空间,避免事后截断破坏内容完整性。
  2460. """
  2461. # 生成最坏情况的头部(99/99 批次)
  2462. max_header = _get_batch_header(format_type, 99, 99)
  2463. return len(max_header.encode("utf-8"))
  2464. def _truncate_to_bytes(text: str, max_bytes: int) -> str:
  2465. """安全截断字符串到指定字节数,避免截断多字节字符"""
  2466. text_bytes = text.encode("utf-8")
  2467. if len(text_bytes) <= max_bytes:
  2468. return text
  2469. # 截断到指定字节数
  2470. truncated = text_bytes[:max_bytes]
  2471. # 处理可能的不完整 UTF-8 字符
  2472. for i in range(min(4, len(truncated))):
  2473. try:
  2474. return truncated[: len(truncated) - i].decode("utf-8")
  2475. except UnicodeDecodeError:
  2476. continue
  2477. # 极端情况:返回空字符串
  2478. return ""
  2479. def add_batch_headers(
  2480. batches: List[str], format_type: str, max_bytes: int
  2481. ) -> List[str]:
  2482. """为批次添加头部,动态计算确保总大小不超过限制
  2483. Args:
  2484. batches: 原始批次列表
  2485. format_type: 推送类型(bark, telegram, feishu 等)
  2486. max_bytes: 该推送类型的最大字节限制
  2487. Returns:
  2488. 添加头部后的批次列表
  2489. """
  2490. if len(batches) <= 1:
  2491. return batches
  2492. total = len(batches)
  2493. result = []
  2494. for i, content in enumerate(batches, 1):
  2495. # 生成批次头部
  2496. header = _get_batch_header(format_type, i, total)
  2497. header_size = len(header.encode("utf-8"))
  2498. # 动态计算允许的最大内容大小
  2499. max_content_size = max_bytes - header_size
  2500. content_size = len(content.encode("utf-8"))
  2501. # 如果超出,截断到安全大小
  2502. if content_size > max_content_size:
  2503. print(
  2504. f"警告:{format_type} 第 {i}/{total} 批次内容({content_size}字节) + 头部({header_size}字节) 超出限制({max_bytes}字节),截断到 {max_content_size} 字节"
  2505. )
  2506. content = _truncate_to_bytes(content, max_content_size)
  2507. result.append(header + content)
  2508. return result
  2509. def split_content_into_batches(
  2510. report_data: Dict,
  2511. format_type: str,
  2512. update_info: Optional[Dict] = None,
  2513. max_bytes: int = None,
  2514. mode: str = "daily",
  2515. ) -> List[str]:
  2516. """分批处理消息内容,确保词组标题+至少第一条新闻的完整性"""
  2517. if max_bytes is None:
  2518. if format_type == "dingtalk":
  2519. max_bytes = CONFIG.get("DINGTALK_BATCH_SIZE", 20000)
  2520. elif format_type == "feishu":
  2521. max_bytes = CONFIG.get("FEISHU_BATCH_SIZE", 29000)
  2522. elif format_type == "ntfy":
  2523. max_bytes = 3800
  2524. else:
  2525. max_bytes = CONFIG.get("MESSAGE_BATCH_SIZE", 4000)
  2526. batches = []
  2527. total_titles = sum(
  2528. len(stat["titles"]) for stat in report_data["stats"] if stat["count"] > 0
  2529. )
  2530. now = get_beijing_time()
  2531. base_header = ""
  2532. if format_type in ("wework", "bark"):
  2533. base_header = f"**总新闻数:** {total_titles}\n\n\n\n"
  2534. elif format_type == "telegram":
  2535. base_header = f"总新闻数: {total_titles}\n\n"
  2536. elif format_type == "ntfy":
  2537. base_header = f"**总新闻数:** {total_titles}\n\n"
  2538. elif format_type == "feishu":
  2539. base_header = ""
  2540. elif format_type == "dingtalk":
  2541. base_header = f"**总新闻数:** {total_titles}\n\n"
  2542. base_header += f"**时间:** {now.strftime('%Y-%m-%d %H:%M:%S')}\n\n"
  2543. base_header += f"**类型:** 热点分析报告\n\n"
  2544. base_header += "---\n\n"
  2545. elif format_type == "slack":
  2546. base_header = f"*总新闻数:* {total_titles}\n\n"
  2547. base_footer = ""
  2548. if format_type in ("wework", "bark"):
  2549. base_footer = f"\n\n\n> 更新时间:{now.strftime('%Y-%m-%d %H:%M:%S')}"
  2550. if update_info:
  2551. base_footer += f"\n> TrendRadar 发现新版本 **{update_info['remote_version']}**,当前 **{update_info['current_version']}**"
  2552. elif format_type == "telegram":
  2553. base_footer = f"\n\n更新时间:{now.strftime('%Y-%m-%d %H:%M:%S')}"
  2554. if update_info:
  2555. base_footer += f"\nTrendRadar 发现新版本 {update_info['remote_version']},当前 {update_info['current_version']}"
  2556. elif format_type == "ntfy":
  2557. base_footer = f"\n\n> 更新时间:{now.strftime('%Y-%m-%d %H:%M:%S')}"
  2558. if update_info:
  2559. base_footer += f"\n> TrendRadar 发现新版本 **{update_info['remote_version']}**,当前 **{update_info['current_version']}**"
  2560. elif format_type == "feishu":
  2561. base_footer = f"\n\n<font color='grey'>更新时间:{now.strftime('%Y-%m-%d %H:%M:%S')}</font>"
  2562. if update_info:
  2563. base_footer += f"\n<font color='grey'>TrendRadar 发现新版本 {update_info['remote_version']},当前 {update_info['current_version']}</font>"
  2564. elif format_type == "dingtalk":
  2565. base_footer = f"\n\n> 更新时间:{now.strftime('%Y-%m-%d %H:%M:%S')}"
  2566. if update_info:
  2567. base_footer += f"\n> TrendRadar 发现新版本 **{update_info['remote_version']}**,当前 **{update_info['current_version']}**"
  2568. elif format_type == "slack":
  2569. base_footer = f"\n\n_更新时间:{now.strftime('%Y-%m-%d %H:%M:%S')}_"
  2570. if update_info:
  2571. base_footer += f"\n_TrendRadar 发现新版本 *{update_info['remote_version']}*,当前 *{update_info['current_version']}_"
  2572. stats_header = ""
  2573. if report_data["stats"]:
  2574. if format_type in ("wework", "bark"):
  2575. stats_header = f"📊 **热点词汇统计**\n\n"
  2576. elif format_type == "telegram":
  2577. stats_header = f"📊 热点词汇统计\n\n"
  2578. elif format_type == "ntfy":
  2579. stats_header = f"📊 **热点词汇统计**\n\n"
  2580. elif format_type == "feishu":
  2581. stats_header = f"📊 **热点词汇统计**\n\n"
  2582. elif format_type == "dingtalk":
  2583. stats_header = f"📊 **热点词汇统计**\n\n"
  2584. elif format_type == "slack":
  2585. stats_header = f"📊 *热点词汇统计*\n\n"
  2586. current_batch = base_header
  2587. current_batch_has_content = False
  2588. if (
  2589. not report_data["stats"]
  2590. and not report_data["new_titles"]
  2591. and not report_data["failed_ids"]
  2592. ):
  2593. if mode == "incremental":
  2594. mode_text = "增量模式下暂无新增匹配的热点词汇"
  2595. elif mode == "current":
  2596. mode_text = "当前榜单模式下暂无匹配的热点词汇"
  2597. else:
  2598. mode_text = "暂无匹配的热点词汇"
  2599. simple_content = f"📭 {mode_text}\n\n"
  2600. final_content = base_header + simple_content + base_footer
  2601. batches.append(final_content)
  2602. return batches
  2603. # 处理热点词汇统计
  2604. if report_data["stats"]:
  2605. total_count = len(report_data["stats"])
  2606. # 添加统计标题
  2607. test_content = current_batch + stats_header
  2608. if (
  2609. len(test_content.encode("utf-8")) + len(base_footer.encode("utf-8"))
  2610. < max_bytes
  2611. ):
  2612. current_batch = test_content
  2613. current_batch_has_content = True
  2614. else:
  2615. if current_batch_has_content:
  2616. batches.append(current_batch + base_footer)
  2617. current_batch = base_header + stats_header
  2618. current_batch_has_content = True
  2619. # 逐个处理词组(确保词组标题+第一条新闻的原子性)
  2620. for i, stat in enumerate(report_data["stats"]):
  2621. word = stat["word"]
  2622. count = stat["count"]
  2623. sequence_display = f"[{i + 1}/{total_count}]"
  2624. # 构建词组标题
  2625. word_header = ""
  2626. if format_type in ("wework", "bark"):
  2627. if count >= 10:
  2628. word_header = (
  2629. f"🔥 {sequence_display} **{word}** : **{count}** 条\n\n"
  2630. )
  2631. elif count >= 5:
  2632. word_header = (
  2633. f"📈 {sequence_display} **{word}** : **{count}** 条\n\n"
  2634. )
  2635. else:
  2636. word_header = f"📌 {sequence_display} **{word}** : {count} 条\n\n"
  2637. elif format_type == "telegram":
  2638. if count >= 10:
  2639. word_header = f"🔥 {sequence_display} {word} : {count} 条\n\n"
  2640. elif count >= 5:
  2641. word_header = f"📈 {sequence_display} {word} : {count} 条\n\n"
  2642. else:
  2643. word_header = f"📌 {sequence_display} {word} : {count} 条\n\n"
  2644. elif format_type == "ntfy":
  2645. if count >= 10:
  2646. word_header = (
  2647. f"🔥 {sequence_display} **{word}** : **{count}** 条\n\n"
  2648. )
  2649. elif count >= 5:
  2650. word_header = (
  2651. f"📈 {sequence_display} **{word}** : **{count}** 条\n\n"
  2652. )
  2653. else:
  2654. word_header = f"📌 {sequence_display} **{word}** : {count} 条\n\n"
  2655. elif format_type == "feishu":
  2656. if count >= 10:
  2657. word_header = f"🔥 <font color='grey'>{sequence_display}</font> **{word}** : <font color='red'>{count}</font> 条\n\n"
  2658. elif count >= 5:
  2659. word_header = f"📈 <font color='grey'>{sequence_display}</font> **{word}** : <font color='orange'>{count}</font> 条\n\n"
  2660. else:
  2661. word_header = f"📌 <font color='grey'>{sequence_display}</font> **{word}** : {count} 条\n\n"
  2662. elif format_type == "dingtalk":
  2663. if count >= 10:
  2664. word_header = (
  2665. f"🔥 {sequence_display} **{word}** : **{count}** 条\n\n"
  2666. )
  2667. elif count >= 5:
  2668. word_header = (
  2669. f"📈 {sequence_display} **{word}** : **{count}** 条\n\n"
  2670. )
  2671. else:
  2672. word_header = f"📌 {sequence_display} **{word}** : {count} 条\n\n"
  2673. elif format_type == "slack":
  2674. if count >= 10:
  2675. word_header = (
  2676. f"🔥 {sequence_display} *{word}* : *{count}* 条\n\n"
  2677. )
  2678. elif count >= 5:
  2679. word_header = (
  2680. f"📈 {sequence_display} *{word}* : *{count}* 条\n\n"
  2681. )
  2682. else:
  2683. word_header = f"📌 {sequence_display} *{word}* : {count} 条\n\n"
  2684. # 构建第一条新闻
  2685. first_news_line = ""
  2686. if stat["titles"]:
  2687. first_title_data = stat["titles"][0]
  2688. if format_type in ("wework", "bark"):
  2689. formatted_title = format_title_for_platform(
  2690. "wework", first_title_data, show_source=True
  2691. )
  2692. elif format_type == "telegram":
  2693. formatted_title = format_title_for_platform(
  2694. "telegram", first_title_data, show_source=True
  2695. )
  2696. elif format_type == "ntfy":
  2697. formatted_title = format_title_for_platform(
  2698. "ntfy", first_title_data, show_source=True
  2699. )
  2700. elif format_type == "feishu":
  2701. formatted_title = format_title_for_platform(
  2702. "feishu", first_title_data, show_source=True
  2703. )
  2704. elif format_type == "dingtalk":
  2705. formatted_title = format_title_for_platform(
  2706. "dingtalk", first_title_data, show_source=True
  2707. )
  2708. elif format_type == "slack":
  2709. formatted_title = format_title_for_platform(
  2710. "slack", first_title_data, show_source=True
  2711. )
  2712. else:
  2713. formatted_title = f"{first_title_data['title']}"
  2714. first_news_line = f" 1. {formatted_title}\n"
  2715. if len(stat["titles"]) > 1:
  2716. first_news_line += "\n"
  2717. # 原子性检查:词组标题+第一条新闻必须一起处理
  2718. word_with_first_news = word_header + first_news_line
  2719. test_content = current_batch + word_with_first_news
  2720. if (
  2721. len(test_content.encode("utf-8")) + len(base_footer.encode("utf-8"))
  2722. >= max_bytes
  2723. ):
  2724. # 当前批次容纳不下,开启新批次
  2725. if current_batch_has_content:
  2726. batches.append(current_batch + base_footer)
  2727. current_batch = base_header + stats_header + word_with_first_news
  2728. current_batch_has_content = True
  2729. start_index = 1
  2730. else:
  2731. current_batch = test_content
  2732. current_batch_has_content = True
  2733. start_index = 1
  2734. # 处理剩余新闻条目
  2735. for j in range(start_index, len(stat["titles"])):
  2736. title_data = stat["titles"][j]
  2737. if format_type in ("wework", "bark"):
  2738. formatted_title = format_title_for_platform(
  2739. "wework", title_data, show_source=True
  2740. )
  2741. elif format_type == "telegram":
  2742. formatted_title = format_title_for_platform(
  2743. "telegram", title_data, show_source=True
  2744. )
  2745. elif format_type == "ntfy":
  2746. formatted_title = format_title_for_platform(
  2747. "ntfy", title_data, show_source=True
  2748. )
  2749. elif format_type == "feishu":
  2750. formatted_title = format_title_for_platform(
  2751. "feishu", title_data, show_source=True
  2752. )
  2753. elif format_type == "dingtalk":
  2754. formatted_title = format_title_for_platform(
  2755. "dingtalk", title_data, show_source=True
  2756. )
  2757. elif format_type == "slack":
  2758. formatted_title = format_title_for_platform(
  2759. "slack", title_data, show_source=True
  2760. )
  2761. else:
  2762. formatted_title = f"{title_data['title']}"
  2763. news_line = f" {j + 1}. {formatted_title}\n"
  2764. if j < len(stat["titles"]) - 1:
  2765. news_line += "\n"
  2766. test_content = current_batch + news_line
  2767. if (
  2768. len(test_content.encode("utf-8")) + len(base_footer.encode("utf-8"))
  2769. >= max_bytes
  2770. ):
  2771. if current_batch_has_content:
  2772. batches.append(current_batch + base_footer)
  2773. current_batch = base_header + stats_header + word_header + news_line
  2774. current_batch_has_content = True
  2775. else:
  2776. current_batch = test_content
  2777. current_batch_has_content = True
  2778. # 词组间分隔符
  2779. if i < len(report_data["stats"]) - 1:
  2780. separator = ""
  2781. if format_type in ("wework", "bark"):
  2782. separator = f"\n\n\n\n"
  2783. elif format_type == "telegram":
  2784. separator = f"\n\n"
  2785. elif format_type == "ntfy":
  2786. separator = f"\n\n"
  2787. elif format_type == "feishu":
  2788. separator = f"\n{CONFIG['FEISHU_MESSAGE_SEPARATOR']}\n\n"
  2789. elif format_type == "dingtalk":
  2790. separator = f"\n---\n\n"
  2791. elif format_type == "slack":
  2792. separator = f"\n\n"
  2793. test_content = current_batch + separator
  2794. if (
  2795. len(test_content.encode("utf-8")) + len(base_footer.encode("utf-8"))
  2796. < max_bytes
  2797. ):
  2798. current_batch = test_content
  2799. # 处理新增新闻(同样确保来源标题+第一条新闻的原子性)
  2800. if report_data["new_titles"]:
  2801. new_header = ""
  2802. if format_type in ("wework", "bark"):
  2803. new_header = f"\n\n\n\n🆕 **本次新增热点新闻** (共 {report_data['total_new_count']} 条)\n\n"
  2804. elif format_type == "telegram":
  2805. new_header = (
  2806. f"\n\n🆕 本次新增热点新闻 (共 {report_data['total_new_count']} 条)\n\n"
  2807. )
  2808. elif format_type == "ntfy":
  2809. new_header = f"\n\n🆕 **本次新增热点新闻** (共 {report_data['total_new_count']} 条)\n\n"
  2810. elif format_type == "feishu":
  2811. new_header = f"\n{CONFIG['FEISHU_MESSAGE_SEPARATOR']}\n\n🆕 **本次新增热点新闻** (共 {report_data['total_new_count']} 条)\n\n"
  2812. elif format_type == "dingtalk":
  2813. new_header = f"\n---\n\n🆕 **本次新增热点新闻** (共 {report_data['total_new_count']} 条)\n\n"
  2814. elif format_type == "slack":
  2815. new_header = f"\n\n🆕 *本次新增热点新闻* (共 {report_data['total_new_count']} 条)\n\n"
  2816. test_content = current_batch + new_header
  2817. if (
  2818. len(test_content.encode("utf-8")) + len(base_footer.encode("utf-8"))
  2819. >= max_bytes
  2820. ):
  2821. if current_batch_has_content:
  2822. batches.append(current_batch + base_footer)
  2823. current_batch = base_header + new_header
  2824. current_batch_has_content = True
  2825. else:
  2826. current_batch = test_content
  2827. current_batch_has_content = True
  2828. # 逐个处理新增新闻来源
  2829. for source_data in report_data["new_titles"]:
  2830. source_header = ""
  2831. if format_type in ("wework", "bark"):
  2832. source_header = f"**{source_data['source_name']}** ({len(source_data['titles'])} 条):\n\n"
  2833. elif format_type == "telegram":
  2834. source_header = f"{source_data['source_name']} ({len(source_data['titles'])} 条):\n\n"
  2835. elif format_type == "ntfy":
  2836. source_header = f"**{source_data['source_name']}** ({len(source_data['titles'])} 条):\n\n"
  2837. elif format_type == "feishu":
  2838. source_header = f"**{source_data['source_name']}** ({len(source_data['titles'])} 条):\n\n"
  2839. elif format_type == "dingtalk":
  2840. source_header = f"**{source_data['source_name']}** ({len(source_data['titles'])} 条):\n\n"
  2841. elif format_type == "slack":
  2842. source_header = f"*{source_data['source_name']}* ({len(source_data['titles'])} 条):\n\n"
  2843. # 构建第一条新增新闻
  2844. first_news_line = ""
  2845. if source_data["titles"]:
  2846. first_title_data = source_data["titles"][0]
  2847. title_data_copy = first_title_data.copy()
  2848. title_data_copy["is_new"] = False
  2849. if format_type in ("wework", "bark"):
  2850. formatted_title = format_title_for_platform(
  2851. "wework", title_data_copy, show_source=False
  2852. )
  2853. elif format_type == "telegram":
  2854. formatted_title = format_title_for_platform(
  2855. "telegram", title_data_copy, show_source=False
  2856. )
  2857. elif format_type == "feishu":
  2858. formatted_title = format_title_for_platform(
  2859. "feishu", title_data_copy, show_source=False
  2860. )
  2861. elif format_type == "dingtalk":
  2862. formatted_title = format_title_for_platform(
  2863. "dingtalk", title_data_copy, show_source=False
  2864. )
  2865. elif format_type == "slack":
  2866. formatted_title = format_title_for_platform(
  2867. "slack", title_data_copy, show_source=False
  2868. )
  2869. else:
  2870. formatted_title = f"{title_data_copy['title']}"
  2871. first_news_line = f" 1. {formatted_title}\n"
  2872. # 原子性检查:来源标题+第一条新闻
  2873. source_with_first_news = source_header + first_news_line
  2874. test_content = current_batch + source_with_first_news
  2875. if (
  2876. len(test_content.encode("utf-8")) + len(base_footer.encode("utf-8"))
  2877. >= max_bytes
  2878. ):
  2879. if current_batch_has_content:
  2880. batches.append(current_batch + base_footer)
  2881. current_batch = base_header + new_header + source_with_first_news
  2882. current_batch_has_content = True
  2883. start_index = 1
  2884. else:
  2885. current_batch = test_content
  2886. current_batch_has_content = True
  2887. start_index = 1
  2888. # 处理剩余新增新闻
  2889. for j in range(start_index, len(source_data["titles"])):
  2890. title_data = source_data["titles"][j]
  2891. title_data_copy = title_data.copy()
  2892. title_data_copy["is_new"] = False
  2893. if format_type == "wework":
  2894. formatted_title = format_title_for_platform(
  2895. "wework", title_data_copy, show_source=False
  2896. )
  2897. elif format_type == "telegram":
  2898. formatted_title = format_title_for_platform(
  2899. "telegram", title_data_copy, show_source=False
  2900. )
  2901. elif format_type == "feishu":
  2902. formatted_title = format_title_for_platform(
  2903. "feishu", title_data_copy, show_source=False
  2904. )
  2905. elif format_type == "dingtalk":
  2906. formatted_title = format_title_for_platform(
  2907. "dingtalk", title_data_copy, show_source=False
  2908. )
  2909. elif format_type == "slack":
  2910. formatted_title = format_title_for_platform(
  2911. "slack", title_data_copy, show_source=False
  2912. )
  2913. else:
  2914. formatted_title = f"{title_data_copy['title']}"
  2915. news_line = f" {j + 1}. {formatted_title}\n"
  2916. test_content = current_batch + news_line
  2917. if (
  2918. len(test_content.encode("utf-8")) + len(base_footer.encode("utf-8"))
  2919. >= max_bytes
  2920. ):
  2921. if current_batch_has_content:
  2922. batches.append(current_batch + base_footer)
  2923. current_batch = base_header + new_header + source_header + news_line
  2924. current_batch_has_content = True
  2925. else:
  2926. current_batch = test_content
  2927. current_batch_has_content = True
  2928. current_batch += "\n"
  2929. if report_data["failed_ids"]:
  2930. failed_header = ""
  2931. if format_type == "wework":
  2932. failed_header = f"\n\n\n\n⚠️ **数据获取失败的平台:**\n\n"
  2933. elif format_type == "telegram":
  2934. failed_header = f"\n\n⚠️ 数据获取失败的平台:\n\n"
  2935. elif format_type == "ntfy":
  2936. failed_header = f"\n\n⚠️ **数据获取失败的平台:**\n\n"
  2937. elif format_type == "feishu":
  2938. failed_header = f"\n{CONFIG['FEISHU_MESSAGE_SEPARATOR']}\n\n⚠️ **数据获取失败的平台:**\n\n"
  2939. elif format_type == "dingtalk":
  2940. failed_header = f"\n---\n\n⚠️ **数据获取失败的平台:**\n\n"
  2941. test_content = current_batch + failed_header
  2942. if (
  2943. len(test_content.encode("utf-8")) + len(base_footer.encode("utf-8"))
  2944. >= max_bytes
  2945. ):
  2946. if current_batch_has_content:
  2947. batches.append(current_batch + base_footer)
  2948. current_batch = base_header + failed_header
  2949. current_batch_has_content = True
  2950. else:
  2951. current_batch = test_content
  2952. current_batch_has_content = True
  2953. for i, id_value in enumerate(report_data["failed_ids"], 1):
  2954. if format_type == "feishu":
  2955. failed_line = f" • <font color='red'>{id_value}</font>\n"
  2956. elif format_type == "dingtalk":
  2957. failed_line = f" • **{id_value}**\n"
  2958. else:
  2959. failed_line = f" • {id_value}\n"
  2960. test_content = current_batch + failed_line
  2961. if (
  2962. len(test_content.encode("utf-8")) + len(base_footer.encode("utf-8"))
  2963. >= max_bytes
  2964. ):
  2965. if current_batch_has_content:
  2966. batches.append(current_batch + base_footer)
  2967. current_batch = base_header + failed_header + failed_line
  2968. current_batch_has_content = True
  2969. else:
  2970. current_batch = test_content
  2971. current_batch_has_content = True
  2972. # 完成最后批次
  2973. if current_batch_has_content:
  2974. batches.append(current_batch + base_footer)
  2975. return batches
  2976. def send_to_notifications(
  2977. stats: List[Dict],
  2978. failed_ids: Optional[List] = None,
  2979. report_type: str = "当日汇总",
  2980. new_titles: Optional[Dict] = None,
  2981. id_to_name: Optional[Dict] = None,
  2982. update_info: Optional[Dict] = None,
  2983. proxy_url: Optional[str] = None,
  2984. mode: str = "daily",
  2985. html_file_path: Optional[str] = None,
  2986. ) -> Dict[str, bool]:
  2987. """发送数据到多个通知平台"""
  2988. results = {}
  2989. if CONFIG["PUSH_WINDOW"]["ENABLED"]:
  2990. push_manager = PushRecordManager()
  2991. time_range_start = CONFIG["PUSH_WINDOW"]["TIME_RANGE"]["START"]
  2992. time_range_end = CONFIG["PUSH_WINDOW"]["TIME_RANGE"]["END"]
  2993. if not push_manager.is_in_time_range(time_range_start, time_range_end):
  2994. now = get_beijing_time()
  2995. print(
  2996. f"推送窗口控制:当前时间 {now.strftime('%H:%M')} 不在推送时间窗口 {time_range_start}-{time_range_end} 内,跳过推送"
  2997. )
  2998. return results
  2999. if CONFIG["PUSH_WINDOW"]["ONCE_PER_DAY"]:
  3000. if push_manager.has_pushed_today():
  3001. print(f"推送窗口控制:今天已推送过,跳过本次推送")
  3002. return results
  3003. else:
  3004. print(f"推送窗口控制:今天首次推送")
  3005. report_data = prepare_report_data(stats, failed_ids, new_titles, id_to_name, mode)
  3006. feishu_url = CONFIG["FEISHU_WEBHOOK_URL"]
  3007. dingtalk_url = CONFIG["DINGTALK_WEBHOOK_URL"]
  3008. wework_url = CONFIG["WEWORK_WEBHOOK_URL"]
  3009. telegram_token = CONFIG["TELEGRAM_BOT_TOKEN"]
  3010. telegram_chat_id = CONFIG["TELEGRAM_CHAT_ID"]
  3011. email_from = CONFIG["EMAIL_FROM"]
  3012. email_password = CONFIG["EMAIL_PASSWORD"]
  3013. email_to = CONFIG["EMAIL_TO"]
  3014. email_smtp_server = CONFIG.get("EMAIL_SMTP_SERVER", "")
  3015. email_smtp_port = CONFIG.get("EMAIL_SMTP_PORT", "")
  3016. ntfy_server_url = CONFIG["NTFY_SERVER_URL"]
  3017. ntfy_topic = CONFIG["NTFY_TOPIC"]
  3018. ntfy_token = CONFIG.get("NTFY_TOKEN", "")
  3019. bark_url = CONFIG["BARK_URL"]
  3020. slack_webhook_url = CONFIG["SLACK_WEBHOOK_URL"]
  3021. update_info_to_send = update_info if CONFIG["SHOW_VERSION_UPDATE"] else None
  3022. # 发送到飞书
  3023. if feishu_url:
  3024. results["feishu"] = send_to_feishu(
  3025. feishu_url, report_data, report_type, update_info_to_send, proxy_url, mode
  3026. )
  3027. # 发送到钉钉
  3028. if dingtalk_url:
  3029. results["dingtalk"] = send_to_dingtalk(
  3030. dingtalk_url, report_data, report_type, update_info_to_send, proxy_url, mode
  3031. )
  3032. # 发送到企业微信
  3033. if wework_url:
  3034. results["wework"] = send_to_wework(
  3035. wework_url, report_data, report_type, update_info_to_send, proxy_url, mode
  3036. )
  3037. # 发送到 Telegram
  3038. if telegram_token and telegram_chat_id:
  3039. results["telegram"] = send_to_telegram(
  3040. telegram_token,
  3041. telegram_chat_id,
  3042. report_data,
  3043. report_type,
  3044. update_info_to_send,
  3045. proxy_url,
  3046. mode,
  3047. )
  3048. # 发送到 ntfy
  3049. if ntfy_server_url and ntfy_topic:
  3050. results["ntfy"] = send_to_ntfy(
  3051. ntfy_server_url,
  3052. ntfy_topic,
  3053. ntfy_token,
  3054. report_data,
  3055. report_type,
  3056. update_info_to_send,
  3057. proxy_url,
  3058. mode,
  3059. )
  3060. # 发送到 Bark
  3061. if bark_url:
  3062. results["bark"] = send_to_bark(
  3063. bark_url,
  3064. report_data,
  3065. report_type,
  3066. update_info_to_send,
  3067. proxy_url,
  3068. mode,
  3069. )
  3070. # 发送到 Slack
  3071. if slack_webhook_url:
  3072. results["slack"] = send_to_slack(
  3073. slack_webhook_url,
  3074. report_data,
  3075. report_type,
  3076. update_info_to_send,
  3077. proxy_url,
  3078. mode,
  3079. )
  3080. # 发送邮件
  3081. if email_from and email_password and email_to:
  3082. results["email"] = send_to_email(
  3083. email_from,
  3084. email_password,
  3085. email_to,
  3086. report_type,
  3087. html_file_path,
  3088. email_smtp_server,
  3089. email_smtp_port,
  3090. )
  3091. if not results:
  3092. print("未配置任何通知渠道,跳过通知发送")
  3093. # 如果成功发送了任何通知,且启用了每天只推一次,则记录推送
  3094. if (
  3095. CONFIG["PUSH_WINDOW"]["ENABLED"]
  3096. and CONFIG["PUSH_WINDOW"]["ONCE_PER_DAY"]
  3097. and any(results.values())
  3098. ):
  3099. push_manager = PushRecordManager()
  3100. push_manager.record_push(report_type)
  3101. return results
  3102. def send_to_feishu(
  3103. webhook_url: str,
  3104. report_data: Dict,
  3105. report_type: str,
  3106. update_info: Optional[Dict] = None,
  3107. proxy_url: Optional[str] = None,
  3108. mode: str = "daily",
  3109. ) -> bool:
  3110. """发送到飞书(支持分批发送)"""
  3111. headers = {"Content-Type": "application/json"}
  3112. proxies = None
  3113. if proxy_url:
  3114. proxies = {"http": proxy_url, "https": proxy_url}
  3115. # 获取分批内容,使用飞书专用的批次大小
  3116. feishu_batch_size = CONFIG.get("FEISHU_BATCH_SIZE", 29000)
  3117. # 预留批次头部空间,避免添加头部后超限
  3118. header_reserve = _get_max_batch_header_size("feishu")
  3119. batches = split_content_into_batches(
  3120. report_data,
  3121. "feishu",
  3122. update_info,
  3123. max_bytes=feishu_batch_size - header_reserve,
  3124. mode=mode,
  3125. )
  3126. # 统一添加批次头部(已预留空间,不会超限)
  3127. batches = add_batch_headers(batches, "feishu", feishu_batch_size)
  3128. print(f"飞书消息分为 {len(batches)} 批次发送 [{report_type}]")
  3129. # 逐批发送
  3130. for i, batch_content in enumerate(batches, 1):
  3131. batch_size = len(batch_content.encode("utf-8"))
  3132. print(
  3133. f"发送飞书第 {i}/{len(batches)} 批次,大小:{batch_size} 字节 [{report_type}]"
  3134. )
  3135. total_titles = sum(
  3136. len(stat["titles"]) for stat in report_data["stats"] if stat["count"] > 0
  3137. )
  3138. now = get_beijing_time()
  3139. payload = {
  3140. "msg_type": "text",
  3141. "content": {
  3142. "total_titles": total_titles,
  3143. "timestamp": now.strftime("%Y-%m-%d %H:%M:%S"),
  3144. "report_type": report_type,
  3145. "text": batch_content,
  3146. },
  3147. }
  3148. try:
  3149. response = requests.post(
  3150. webhook_url, headers=headers, json=payload, proxies=proxies, timeout=30
  3151. )
  3152. if response.status_code == 200:
  3153. result = response.json()
  3154. # 检查飞书的响应状态
  3155. if result.get("StatusCode") == 0 or result.get("code") == 0:
  3156. print(f"飞书第 {i}/{len(batches)} 批次发送成功 [{report_type}]")
  3157. # 批次间间隔
  3158. if i < len(batches):
  3159. time.sleep(CONFIG["BATCH_SEND_INTERVAL"])
  3160. else:
  3161. error_msg = result.get("msg") or result.get("StatusMessage", "未知错误")
  3162. print(
  3163. f"飞书第 {i}/{len(batches)} 批次发送失败 [{report_type}],错误:{error_msg}"
  3164. )
  3165. return False
  3166. else:
  3167. print(
  3168. f"飞书第 {i}/{len(batches)} 批次发送失败 [{report_type}],状态码:{response.status_code}"
  3169. )
  3170. return False
  3171. except Exception as e:
  3172. print(f"飞书第 {i}/{len(batches)} 批次发送出错 [{report_type}]:{e}")
  3173. return False
  3174. print(f"飞书所有 {len(batches)} 批次发送完成 [{report_type}]")
  3175. return True
  3176. def send_to_dingtalk(
  3177. webhook_url: str,
  3178. report_data: Dict,
  3179. report_type: str,
  3180. update_info: Optional[Dict] = None,
  3181. proxy_url: Optional[str] = None,
  3182. mode: str = "daily",
  3183. ) -> bool:
  3184. """发送到钉钉(支持分批发送)"""
  3185. headers = {"Content-Type": "application/json"}
  3186. proxies = None
  3187. if proxy_url:
  3188. proxies = {"http": proxy_url, "https": proxy_url}
  3189. # 获取分批内容,使用钉钉专用的批次大小
  3190. dingtalk_batch_size = CONFIG.get("DINGTALK_BATCH_SIZE", 20000)
  3191. # 预留批次头部空间,避免添加头部后超限
  3192. header_reserve = _get_max_batch_header_size("dingtalk")
  3193. batches = split_content_into_batches(
  3194. report_data,
  3195. "dingtalk",
  3196. update_info,
  3197. max_bytes=dingtalk_batch_size - header_reserve,
  3198. mode=mode,
  3199. )
  3200. # 统一添加批次头部(已预留空间,不会超限)
  3201. batches = add_batch_headers(batches, "dingtalk", dingtalk_batch_size)
  3202. print(f"钉钉消息分为 {len(batches)} 批次发送 [{report_type}]")
  3203. # 逐批发送
  3204. for i, batch_content in enumerate(batches, 1):
  3205. batch_size = len(batch_content.encode("utf-8"))
  3206. print(
  3207. f"发送钉钉第 {i}/{len(batches)} 批次,大小:{batch_size} 字节 [{report_type}]"
  3208. )
  3209. payload = {
  3210. "msgtype": "markdown",
  3211. "markdown": {
  3212. "title": f"TrendRadar 热点分析报告 - {report_type}",
  3213. "text": batch_content,
  3214. },
  3215. }
  3216. try:
  3217. response = requests.post(
  3218. webhook_url, headers=headers, json=payload, proxies=proxies, timeout=30
  3219. )
  3220. if response.status_code == 200:
  3221. result = response.json()
  3222. if result.get("errcode") == 0:
  3223. print(f"钉钉第 {i}/{len(batches)} 批次发送成功 [{report_type}]")
  3224. # 批次间间隔
  3225. if i < len(batches):
  3226. time.sleep(CONFIG["BATCH_SEND_INTERVAL"])
  3227. else:
  3228. print(
  3229. f"钉钉第 {i}/{len(batches)} 批次发送失败 [{report_type}],错误:{result.get('errmsg')}"
  3230. )
  3231. return False
  3232. else:
  3233. print(
  3234. f"钉钉第 {i}/{len(batches)} 批次发送失败 [{report_type}],状态码:{response.status_code}"
  3235. )
  3236. return False
  3237. except Exception as e:
  3238. print(f"钉钉第 {i}/{len(batches)} 批次发送出错 [{report_type}]:{e}")
  3239. return False
  3240. print(f"钉钉所有 {len(batches)} 批次发送完成 [{report_type}]")
  3241. return True
  3242. def strip_markdown(text: str) -> str:
  3243. """去除文本中的 markdown 语法格式,用于个人微信推送"""
  3244. # 去除粗体 **text** 或 __text__
  3245. text = re.sub(r'\*\*(.+?)\*\*', r'\1', text)
  3246. text = re.sub(r'__(.+?)__', r'\1', text)
  3247. # 去除斜体 *text* 或 _text_
  3248. text = re.sub(r'\*(.+?)\*', r'\1', text)
  3249. text = re.sub(r'_(.+?)_', r'\1', text)
  3250. # 去除删除线 ~~text~~
  3251. text = re.sub(r'~~(.+?)~~', r'\1', text)
  3252. # 转换链接 [text](url) -> text url(保留 URL)
  3253. text = re.sub(r'\[([^\]]+)\]\(([^)]+)\)', r'\1 \2', text)
  3254. # 如果不需要保留 URL,可以使用下面这行(只保留标题文本):
  3255. # text = re.sub(r'\[([^\]]+)\]\([^)]+\)', r'\1', text)
  3256. # 去除图片 ![alt](url) -> alt
  3257. text = re.sub(r'!\[(.+?)\]\(.+?\)', r'\1', text)
  3258. # 去除行内代码 `code`
  3259. text = re.sub(r'`(.+?)`', r'\1', text)
  3260. # 去除引用符号 >
  3261. text = re.sub(r'^>\s*', '', text, flags=re.MULTILINE)
  3262. # 去除标题符号 # ## ### 等
  3263. text = re.sub(r'^#+\s*', '', text, flags=re.MULTILINE)
  3264. # 去除水平分割线 --- 或 ***
  3265. text = re.sub(r'^[\-\*]{3,}\s*$', '', text, flags=re.MULTILINE)
  3266. # 去除 HTML 标签 <font color='xxx'>text</font> -> text
  3267. text = re.sub(r'<font[^>]*>(.+?)</font>', r'\1', text)
  3268. text = re.sub(r'<[^>]+>', '', text)
  3269. # 清理多余的空行(保留最多两个连续空行)
  3270. text = re.sub(r'\n{3,}', '\n\n', text)
  3271. return text.strip()
  3272. def send_to_wework(
  3273. webhook_url: str,
  3274. report_data: Dict,
  3275. report_type: str,
  3276. update_info: Optional[Dict] = None,
  3277. proxy_url: Optional[str] = None,
  3278. mode: str = "daily",
  3279. ) -> bool:
  3280. """发送到企业微信(支持分批发送,支持 markdown 和 text 两种格式)"""
  3281. headers = {"Content-Type": "application/json"}
  3282. proxies = None
  3283. if proxy_url:
  3284. proxies = {"http": proxy_url, "https": proxy_url}
  3285. # 获取消息类型配置(markdown 或 text)
  3286. msg_type = CONFIG.get("WEWORK_MSG_TYPE", "markdown").lower()
  3287. is_text_mode = msg_type == "text"
  3288. if is_text_mode:
  3289. print(f"企业微信使用 text 格式(个人微信模式)[{report_type}]")
  3290. else:
  3291. print(f"企业微信使用 markdown 格式(群机器人模式)[{report_type}]")
  3292. # text 模式使用 wework_text,markdown 模式使用 wework
  3293. header_format_type = "wework_text" if is_text_mode else "wework"
  3294. # 获取分批内容,预留批次头部空间
  3295. wework_batch_size = CONFIG.get("MESSAGE_BATCH_SIZE", 4000)
  3296. header_reserve = _get_max_batch_header_size(header_format_type)
  3297. batches = split_content_into_batches(
  3298. report_data, "wework", update_info, max_bytes=wework_batch_size - header_reserve, mode=mode
  3299. )
  3300. # 统一添加批次头部(已预留空间,不会超限)
  3301. batches = add_batch_headers(batches, header_format_type, wework_batch_size)
  3302. print(f"企业微信消息分为 {len(batches)} 批次发送 [{report_type}]")
  3303. # 逐批发送
  3304. for i, batch_content in enumerate(batches, 1):
  3305. # 根据消息类型构建 payload
  3306. if is_text_mode:
  3307. # text 格式:去除 markdown 语法
  3308. plain_content = strip_markdown(batch_content)
  3309. payload = {"msgtype": "text", "text": {"content": plain_content}}
  3310. batch_size = len(plain_content.encode("utf-8"))
  3311. else:
  3312. # markdown 格式:保持原样
  3313. payload = {"msgtype": "markdown", "markdown": {"content": batch_content}}
  3314. batch_size = len(batch_content.encode("utf-8"))
  3315. print(
  3316. f"发送企业微信第 {i}/{len(batches)} 批次,大小:{batch_size} 字节 [{report_type}]"
  3317. )
  3318. try:
  3319. response = requests.post(
  3320. webhook_url, headers=headers, json=payload, proxies=proxies, timeout=30
  3321. )
  3322. if response.status_code == 200:
  3323. result = response.json()
  3324. if result.get("errcode") == 0:
  3325. print(f"企业微信第 {i}/{len(batches)} 批次发送成功 [{report_type}]")
  3326. # 批次间间隔
  3327. if i < len(batches):
  3328. time.sleep(CONFIG["BATCH_SEND_INTERVAL"])
  3329. else:
  3330. print(
  3331. f"企业微信第 {i}/{len(batches)} 批次发送失败 [{report_type}],错误:{result.get('errmsg')}"
  3332. )
  3333. return False
  3334. else:
  3335. print(
  3336. f"企业微信第 {i}/{len(batches)} 批次发送失败 [{report_type}],状态码:{response.status_code}"
  3337. )
  3338. return False
  3339. except Exception as e:
  3340. print(f"企业微信第 {i}/{len(batches)} 批次发送出错 [{report_type}]:{e}")
  3341. return False
  3342. print(f"企业微信所有 {len(batches)} 批次发送完成 [{report_type}]")
  3343. return True
  3344. def send_to_telegram(
  3345. bot_token: str,
  3346. chat_id: str,
  3347. report_data: Dict,
  3348. report_type: str,
  3349. update_info: Optional[Dict] = None,
  3350. proxy_url: Optional[str] = None,
  3351. mode: str = "daily",
  3352. ) -> bool:
  3353. """发送到Telegram(支持分批发送)"""
  3354. headers = {"Content-Type": "application/json"}
  3355. url = f"https://api.telegram.org/bot{bot_token}/sendMessage"
  3356. proxies = None
  3357. if proxy_url:
  3358. proxies = {"http": proxy_url, "https": proxy_url}
  3359. # 获取分批内容,预留批次头部空间
  3360. telegram_batch_size = CONFIG.get("MESSAGE_BATCH_SIZE", 4000)
  3361. header_reserve = _get_max_batch_header_size("telegram")
  3362. batches = split_content_into_batches(
  3363. report_data, "telegram", update_info, max_bytes=telegram_batch_size - header_reserve, mode=mode
  3364. )
  3365. # 统一添加批次头部(已预留空间,不会超限)
  3366. batches = add_batch_headers(batches, "telegram", telegram_batch_size)
  3367. print(f"Telegram消息分为 {len(batches)} 批次发送 [{report_type}]")
  3368. # 逐批发送
  3369. for i, batch_content in enumerate(batches, 1):
  3370. batch_size = len(batch_content.encode("utf-8"))
  3371. print(
  3372. f"发送Telegram第 {i}/{len(batches)} 批次,大小:{batch_size} 字节 [{report_type}]"
  3373. )
  3374. payload = {
  3375. "chat_id": chat_id,
  3376. "text": batch_content,
  3377. "parse_mode": "HTML",
  3378. "disable_web_page_preview": True,
  3379. }
  3380. try:
  3381. response = requests.post(
  3382. url, headers=headers, json=payload, proxies=proxies, timeout=30
  3383. )
  3384. if response.status_code == 200:
  3385. result = response.json()
  3386. if result.get("ok"):
  3387. print(f"Telegram第 {i}/{len(batches)} 批次发送成功 [{report_type}]")
  3388. # 批次间间隔
  3389. if i < len(batches):
  3390. time.sleep(CONFIG["BATCH_SEND_INTERVAL"])
  3391. else:
  3392. print(
  3393. f"Telegram第 {i}/{len(batches)} 批次发送失败 [{report_type}],错误:{result.get('description')}"
  3394. )
  3395. return False
  3396. else:
  3397. print(
  3398. f"Telegram第 {i}/{len(batches)} 批次发送失败 [{report_type}],状态码:{response.status_code}"
  3399. )
  3400. return False
  3401. except Exception as e:
  3402. print(f"Telegram第 {i}/{len(batches)} 批次发送出错 [{report_type}]:{e}")
  3403. return False
  3404. print(f"Telegram所有 {len(batches)} 批次发送完成 [{report_type}]")
  3405. return True
  3406. def send_to_email(
  3407. from_email: str,
  3408. password: str,
  3409. to_email: str,
  3410. report_type: str,
  3411. html_file_path: str,
  3412. custom_smtp_server: Optional[str] = None,
  3413. custom_smtp_port: Optional[int] = None,
  3414. ) -> bool:
  3415. """发送邮件通知"""
  3416. try:
  3417. if not html_file_path or not Path(html_file_path).exists():
  3418. print(f"错误:HTML文件不存在或未提供: {html_file_path}")
  3419. return False
  3420. print(f"使用HTML文件: {html_file_path}")
  3421. with open(html_file_path, "r", encoding="utf-8") as f:
  3422. html_content = f.read()
  3423. domain = from_email.split("@")[-1].lower()
  3424. if custom_smtp_server and custom_smtp_port:
  3425. # 使用自定义 SMTP 配置
  3426. smtp_server = custom_smtp_server
  3427. smtp_port = int(custom_smtp_port)
  3428. # 根据端口判断加密方式:465=SSL, 587=TLS
  3429. if smtp_port == 465:
  3430. use_tls = False # SSL 模式(SMTP_SSL)
  3431. elif smtp_port == 587:
  3432. use_tls = True # TLS 模式(STARTTLS)
  3433. else:
  3434. # 其他端口优先尝试 TLS(更安全,更广泛支持)
  3435. use_tls = True
  3436. elif domain in SMTP_CONFIGS:
  3437. # 使用预设配置
  3438. config = SMTP_CONFIGS[domain]
  3439. smtp_server = config["server"]
  3440. smtp_port = config["port"]
  3441. use_tls = config["encryption"] == "TLS"
  3442. else:
  3443. print(f"未识别的邮箱服务商: {domain},使用通用 SMTP 配置")
  3444. smtp_server = f"smtp.{domain}"
  3445. smtp_port = 587
  3446. use_tls = True
  3447. msg = MIMEMultipart("alternative")
  3448. # 严格按照 RFC 标准设置 From header
  3449. sender_name = "TrendRadar"
  3450. msg["From"] = formataddr((sender_name, from_email))
  3451. # 设置收件人
  3452. recipients = [addr.strip() for addr in to_email.split(",")]
  3453. if len(recipients) == 1:
  3454. msg["To"] = recipients[0]
  3455. else:
  3456. msg["To"] = ", ".join(recipients)
  3457. # 设置邮件主题
  3458. now = get_beijing_time()
  3459. subject = f"TrendRadar 热点分析报告 - {report_type} - {now.strftime('%m月%d日 %H:%M')}"
  3460. msg["Subject"] = Header(subject, "utf-8")
  3461. # 设置其他标准 header
  3462. msg["MIME-Version"] = "1.0"
  3463. msg["Date"] = formatdate(localtime=True)
  3464. msg["Message-ID"] = make_msgid()
  3465. # 添加纯文本部分(作为备选)
  3466. text_content = f"""
  3467. TrendRadar 热点分析报告
  3468. ========================
  3469. 报告类型:{report_type}
  3470. 生成时间:{now.strftime('%Y-%m-%d %H:%M:%S')}
  3471. 请使用支持HTML的邮件客户端查看完整报告内容。
  3472. """
  3473. text_part = MIMEText(text_content, "plain", "utf-8")
  3474. msg.attach(text_part)
  3475. html_part = MIMEText(html_content, "html", "utf-8")
  3476. msg.attach(html_part)
  3477. print(f"正在发送邮件到 {to_email}...")
  3478. print(f"SMTP 服务器: {smtp_server}:{smtp_port}")
  3479. print(f"发件人: {from_email}")
  3480. try:
  3481. if use_tls:
  3482. # TLS 模式
  3483. server = smtplib.SMTP(smtp_server, smtp_port, timeout=30)
  3484. server.set_debuglevel(0) # 设为1可以查看详细调试信息
  3485. server.ehlo()
  3486. server.starttls()
  3487. server.ehlo()
  3488. else:
  3489. # SSL 模式
  3490. server = smtplib.SMTP_SSL(smtp_server, smtp_port, timeout=30)
  3491. server.set_debuglevel(0)
  3492. server.ehlo()
  3493. # 登录
  3494. server.login(from_email, password)
  3495. # 发送邮件
  3496. server.send_message(msg)
  3497. server.quit()
  3498. print(f"邮件发送成功 [{report_type}] -> {to_email}")
  3499. return True
  3500. except smtplib.SMTPServerDisconnected:
  3501. print(f"邮件发送失败:服务器意外断开连接,请检查网络或稍后重试")
  3502. return False
  3503. except smtplib.SMTPAuthenticationError as e:
  3504. print(f"邮件发送失败:认证错误,请检查邮箱和密码/授权码")
  3505. print(f"详细错误: {str(e)}")
  3506. return False
  3507. except smtplib.SMTPRecipientsRefused as e:
  3508. print(f"邮件发送失败:收件人地址被拒绝 {e}")
  3509. return False
  3510. except smtplib.SMTPSenderRefused as e:
  3511. print(f"邮件发送失败:发件人地址被拒绝 {e}")
  3512. return False
  3513. except smtplib.SMTPDataError as e:
  3514. print(f"邮件发送失败:邮件数据错误 {e}")
  3515. return False
  3516. except smtplib.SMTPConnectError as e:
  3517. print(f"邮件发送失败:无法连接到 SMTP 服务器 {smtp_server}:{smtp_port}")
  3518. print(f"详细错误: {str(e)}")
  3519. return False
  3520. except Exception as e:
  3521. print(f"邮件发送失败 [{report_type}]:{e}")
  3522. import traceback
  3523. traceback.print_exc()
  3524. return False
  3525. def send_to_ntfy(
  3526. server_url: str,
  3527. topic: str,
  3528. token: Optional[str],
  3529. report_data: Dict,
  3530. report_type: str,
  3531. update_info: Optional[Dict] = None,
  3532. proxy_url: Optional[str] = None,
  3533. mode: str = "daily",
  3534. ) -> bool:
  3535. """发送到ntfy(支持分批发送,严格遵守4KB限制)"""
  3536. # 避免 HTTP header 编码问题
  3537. report_type_en_map = {
  3538. "当日汇总": "Daily Summary",
  3539. "当前榜单汇总": "Current Ranking",
  3540. "增量更新": "Incremental Update",
  3541. "实时增量": "Realtime Incremental",
  3542. "实时当前榜单": "Realtime Current Ranking",
  3543. }
  3544. report_type_en = report_type_en_map.get(report_type, "News Report")
  3545. headers = {
  3546. "Content-Type": "text/plain; charset=utf-8",
  3547. "Markdown": "yes",
  3548. "Title": report_type_en,
  3549. "Priority": "default",
  3550. "Tags": "news",
  3551. }
  3552. if token:
  3553. headers["Authorization"] = f"Bearer {token}"
  3554. # 构建完整URL,确保格式正确
  3555. base_url = server_url.rstrip("/")
  3556. if not base_url.startswith(("http://", "https://")):
  3557. base_url = f"https://{base_url}"
  3558. url = f"{base_url}/{topic}"
  3559. proxies = None
  3560. if proxy_url:
  3561. proxies = {"http": proxy_url, "https": proxy_url}
  3562. # 获取分批内容,使用ntfy专用的4KB限制,预留批次头部空间
  3563. ntfy_batch_size = 3800
  3564. header_reserve = _get_max_batch_header_size("ntfy")
  3565. batches = split_content_into_batches(
  3566. report_data, "ntfy", update_info, max_bytes=ntfy_batch_size - header_reserve, mode=mode
  3567. )
  3568. # 统一添加批次头部(已预留空间,不会超限)
  3569. batches = add_batch_headers(batches, "ntfy", ntfy_batch_size)
  3570. total_batches = len(batches)
  3571. print(f"ntfy消息分为 {total_batches} 批次发送 [{report_type}]")
  3572. # 反转批次顺序,使得在ntfy客户端显示时顺序正确
  3573. # ntfy显示最新消息在上面,所以我们从最后一批开始推送
  3574. reversed_batches = list(reversed(batches))
  3575. print(f"ntfy将按反向顺序推送(最后批次先推送),确保客户端显示顺序正确")
  3576. # 逐批发送(反向顺序)
  3577. success_count = 0
  3578. for idx, batch_content in enumerate(reversed_batches, 1):
  3579. # 计算正确的批次编号(用户视角的编号)
  3580. actual_batch_num = total_batches - idx + 1
  3581. batch_size = len(batch_content.encode("utf-8"))
  3582. print(
  3583. f"发送ntfy第 {actual_batch_num}/{total_batches} 批次(推送顺序: {idx}/{total_batches}),大小:{batch_size} 字节 [{report_type}]"
  3584. )
  3585. # 检查消息大小,确保不超过4KB
  3586. if batch_size > 4096:
  3587. print(f"警告:ntfy第 {actual_batch_num} 批次消息过大({batch_size} 字节),可能被拒绝")
  3588. # 更新 headers 的批次标识
  3589. current_headers = headers.copy()
  3590. if total_batches > 1:
  3591. current_headers["Title"] = (
  3592. f"{report_type_en} ({actual_batch_num}/{total_batches})"
  3593. )
  3594. try:
  3595. response = requests.post(
  3596. url,
  3597. headers=current_headers,
  3598. data=batch_content.encode("utf-8"),
  3599. proxies=proxies,
  3600. timeout=30,
  3601. )
  3602. if response.status_code == 200:
  3603. print(f"ntfy第 {actual_batch_num}/{total_batches} 批次发送成功 [{report_type}]")
  3604. success_count += 1
  3605. if idx < total_batches:
  3606. # 公共服务器建议 2-3 秒,自托管可以更短
  3607. interval = 2 if "ntfy.sh" in server_url else 1
  3608. time.sleep(interval)
  3609. elif response.status_code == 429:
  3610. print(
  3611. f"ntfy第 {actual_batch_num}/{total_batches} 批次速率限制 [{report_type}],等待后重试"
  3612. )
  3613. time.sleep(10) # 等待10秒后重试
  3614. # 重试一次
  3615. retry_response = requests.post(
  3616. url,
  3617. headers=current_headers,
  3618. data=batch_content.encode("utf-8"),
  3619. proxies=proxies,
  3620. timeout=30,
  3621. )
  3622. if retry_response.status_code == 200:
  3623. print(f"ntfy第 {actual_batch_num}/{total_batches} 批次重试成功 [{report_type}]")
  3624. success_count += 1
  3625. else:
  3626. print(
  3627. f"ntfy第 {actual_batch_num}/{total_batches} 批次重试失败,状态码:{retry_response.status_code}"
  3628. )
  3629. elif response.status_code == 413:
  3630. print(
  3631. f"ntfy第 {actual_batch_num}/{total_batches} 批次消息过大被拒绝 [{report_type}],消息大小:{batch_size} 字节"
  3632. )
  3633. else:
  3634. print(
  3635. f"ntfy第 {actual_batch_num}/{total_batches} 批次发送失败 [{report_type}],状态码:{response.status_code}"
  3636. )
  3637. try:
  3638. print(f"错误详情:{response.text}")
  3639. except:
  3640. pass
  3641. except requests.exceptions.ConnectTimeout:
  3642. print(f"ntfy第 {actual_batch_num}/{total_batches} 批次连接超时 [{report_type}]")
  3643. except requests.exceptions.ReadTimeout:
  3644. print(f"ntfy第 {actual_batch_num}/{total_batches} 批次读取超时 [{report_type}]")
  3645. except requests.exceptions.ConnectionError as e:
  3646. print(f"ntfy第 {actual_batch_num}/{total_batches} 批次连接错误 [{report_type}]:{e}")
  3647. except Exception as e:
  3648. print(f"ntfy第 {actual_batch_num}/{total_batches} 批次发送异常 [{report_type}]:{e}")
  3649. # 判断整体发送是否成功
  3650. if success_count == total_batches:
  3651. print(f"ntfy所有 {total_batches} 批次发送完成 [{report_type}]")
  3652. return True
  3653. elif success_count > 0:
  3654. print(f"ntfy部分发送成功:{success_count}/{total_batches} 批次 [{report_type}]")
  3655. return True # 部分成功也视为成功
  3656. else:
  3657. print(f"ntfy发送完全失败 [{report_type}]")
  3658. return False
  3659. def send_to_bark(
  3660. bark_url: str,
  3661. report_data: Dict,
  3662. report_type: str,
  3663. update_info: Optional[Dict] = None,
  3664. proxy_url: Optional[str] = None,
  3665. mode: str = "daily",
  3666. ) -> bool:
  3667. """发送到Bark(支持分批发送,使用 markdown 格式)"""
  3668. proxies = None
  3669. if proxy_url:
  3670. proxies = {"http": proxy_url, "https": proxy_url}
  3671. # 解析 Bark URL,提取 device_key 和 API 端点
  3672. # Bark URL 格式: https://api.day.app/device_key 或 https://bark.day.app/device_key
  3673. from urllib.parse import urlparse
  3674. parsed_url = urlparse(bark_url)
  3675. device_key = parsed_url.path.strip('/').split('/')[0] if parsed_url.path else None
  3676. if not device_key:
  3677. print(f"Bark URL 格式错误,无法提取 device_key: {bark_url}")
  3678. return False
  3679. # 构建正确的 API 端点
  3680. api_endpoint = f"{parsed_url.scheme}://{parsed_url.netloc}/push"
  3681. # 获取分批内容(Bark 限制为 3600 字节以避免 413 错误),预留批次头部空间
  3682. bark_batch_size = CONFIG["BARK_BATCH_SIZE"]
  3683. header_reserve = _get_max_batch_header_size("bark")
  3684. batches = split_content_into_batches(
  3685. report_data, "bark", update_info, max_bytes=bark_batch_size - header_reserve, mode=mode
  3686. )
  3687. # 统一添加批次头部(已预留空间,不会超限)
  3688. batches = add_batch_headers(batches, "bark", bark_batch_size)
  3689. total_batches = len(batches)
  3690. print(f"Bark消息分为 {total_batches} 批次发送 [{report_type}]")
  3691. # 反转批次顺序,使得在Bark客户端显示时顺序正确
  3692. # Bark显示最新消息在上面,所以我们从最后一批开始推送
  3693. reversed_batches = list(reversed(batches))
  3694. print(f"Bark将按反向顺序推送(最后批次先推送),确保客户端显示顺序正确")
  3695. # 逐批发送(反向顺序)
  3696. success_count = 0
  3697. for idx, batch_content in enumerate(reversed_batches, 1):
  3698. # 计算正确的批次编号(用户视角的编号)
  3699. actual_batch_num = total_batches - idx + 1
  3700. batch_size = len(batch_content.encode("utf-8"))
  3701. print(
  3702. f"发送Bark第 {actual_batch_num}/{total_batches} 批次(推送顺序: {idx}/{total_batches}),大小:{batch_size} 字节 [{report_type}]"
  3703. )
  3704. # 检查消息大小(Bark使用APNs,限制4KB)
  3705. if batch_size > 4096:
  3706. print(
  3707. f"警告:Bark第 {actual_batch_num}/{total_batches} 批次消息过大({batch_size} 字节),可能被拒绝"
  3708. )
  3709. # 构建JSON payload
  3710. payload = {
  3711. "title": report_type,
  3712. "markdown": batch_content,
  3713. "device_key": device_key,
  3714. "sound": "default",
  3715. "group": "TrendRadar",
  3716. "action": "none", # 点击推送跳到 APP 不弹出弹框,方便阅读
  3717. }
  3718. try:
  3719. response = requests.post(
  3720. api_endpoint,
  3721. json=payload,
  3722. proxies=proxies,
  3723. timeout=30,
  3724. )
  3725. if response.status_code == 200:
  3726. result = response.json()
  3727. if result.get("code") == 200:
  3728. print(f"Bark第 {actual_batch_num}/{total_batches} 批次发送成功 [{report_type}]")
  3729. success_count += 1
  3730. # 批次间间隔
  3731. if idx < total_batches:
  3732. time.sleep(CONFIG["BATCH_SEND_INTERVAL"])
  3733. else:
  3734. print(
  3735. f"Bark第 {actual_batch_num}/{total_batches} 批次发送失败 [{report_type}],错误:{result.get('message', '未知错误')}"
  3736. )
  3737. else:
  3738. print(
  3739. f"Bark第 {actual_batch_num}/{total_batches} 批次发送失败 [{report_type}],状态码:{response.status_code}"
  3740. )
  3741. try:
  3742. print(f"错误详情:{response.text}")
  3743. except:
  3744. pass
  3745. except requests.exceptions.ConnectTimeout:
  3746. print(f"Bark第 {actual_batch_num}/{total_batches} 批次连接超时 [{report_type}]")
  3747. except requests.exceptions.ReadTimeout:
  3748. print(f"Bark第 {actual_batch_num}/{total_batches} 批次读取超时 [{report_type}]")
  3749. except requests.exceptions.ConnectionError as e:
  3750. print(f"Bark第 {actual_batch_num}/{total_batches} 批次连接错误 [{report_type}]:{e}")
  3751. except Exception as e:
  3752. print(f"Bark第 {actual_batch_num}/{total_batches} 批次发送异常 [{report_type}]:{e}")
  3753. # 判断整体发送是否成功
  3754. if success_count == total_batches:
  3755. print(f"Bark所有 {total_batches} 批次发送完成 [{report_type}]")
  3756. return True
  3757. elif success_count > 0:
  3758. print(f"Bark部分发送成功:{success_count}/{total_batches} 批次 [{report_type}]")
  3759. return True # 部分成功也视为成功
  3760. else:
  3761. print(f"Bark发送完全失败 [{report_type}]")
  3762. return False
  3763. def convert_markdown_to_mrkdwn(content: str) -> str:
  3764. """
  3765. 将标准 Markdown 转换为 Slack 的 mrkdwn 格式
  3766. 转换规则:
  3767. - **粗体** → *粗体*
  3768. - [文本](url) → <url|文本>
  3769. - 保留其他格式(代码块、列表等)
  3770. """
  3771. # 1. 转换链接格式: [文本](url) → <url|文本>
  3772. content = re.sub(r'\[([^\]]+)\]\(([^)]+)\)', r'<\2|\1>', content)
  3773. # 2. 转换粗体: **文本** → *文本*
  3774. content = re.sub(r'\*\*([^*]+)\*\*', r'*\1*', content)
  3775. return content
  3776. def send_to_slack(
  3777. webhook_url: str,
  3778. report_data: Dict,
  3779. report_type: str,
  3780. update_info: Optional[Dict] = None,
  3781. proxy_url: Optional[str] = None,
  3782. mode: str = "daily",
  3783. ) -> bool:
  3784. """发送到Slack(支持分批发送,使用 mrkdwn 格式)"""
  3785. headers = {"Content-Type": "application/json"}
  3786. proxies = None
  3787. if proxy_url:
  3788. proxies = {"http": proxy_url, "https": proxy_url}
  3789. # 获取分批内容(使用 Slack 批次大小),预留批次头部空间
  3790. slack_batch_size = CONFIG["SLACK_BATCH_SIZE"]
  3791. header_reserve = _get_max_batch_header_size("slack")
  3792. batches = split_content_into_batches(
  3793. report_data, "slack", update_info, max_bytes=slack_batch_size - header_reserve, mode=mode
  3794. )
  3795. # 统一添加批次头部(已预留空间,不会超限)
  3796. batches = add_batch_headers(batches, "slack", slack_batch_size)
  3797. print(f"Slack消息分为 {len(batches)} 批次发送 [{report_type}]")
  3798. # 逐批发送
  3799. for i, batch_content in enumerate(batches, 1):
  3800. # 转换 Markdown 到 mrkdwn 格式
  3801. mrkdwn_content = convert_markdown_to_mrkdwn(batch_content)
  3802. batch_size = len(mrkdwn_content.encode("utf-8"))
  3803. print(
  3804. f"发送Slack第 {i}/{len(batches)} 批次,大小:{batch_size} 字节 [{report_type}]"
  3805. )
  3806. # 构建 Slack payload(使用简单的 text 字段,支持 mrkdwn)
  3807. payload = {
  3808. "text": mrkdwn_content
  3809. }
  3810. try:
  3811. response = requests.post(
  3812. webhook_url, headers=headers, json=payload, proxies=proxies, timeout=30
  3813. )
  3814. # Slack Incoming Webhooks 成功时返回 "ok" 文本
  3815. if response.status_code == 200 and response.text == "ok":
  3816. print(f"Slack第 {i}/{len(batches)} 批次发送成功 [{report_type}]")
  3817. # 批次间间隔
  3818. if i < len(batches):
  3819. time.sleep(CONFIG["BATCH_SEND_INTERVAL"])
  3820. else:
  3821. error_msg = response.text if response.text else f"状态码:{response.status_code}"
  3822. print(
  3823. f"Slack第 {i}/{len(batches)} 批次发送失败 [{report_type}],错误:{error_msg}"
  3824. )
  3825. return False
  3826. except Exception as e:
  3827. print(f"Slack第 {i}/{len(batches)} 批次发送出错 [{report_type}]:{e}")
  3828. return False
  3829. print(f"Slack所有 {len(batches)} 批次发送完成 [{report_type}]")
  3830. return True
  3831. # === 主分析器 ===
  3832. class NewsAnalyzer:
  3833. """新闻分析器"""
  3834. # 模式策略定义
  3835. MODE_STRATEGIES = {
  3836. "incremental": {
  3837. "mode_name": "增量模式",
  3838. "description": "增量模式(只关注新增新闻,无新增时不推送)",
  3839. "realtime_report_type": "实时增量",
  3840. "summary_report_type": "当日汇总",
  3841. "should_send_realtime": True,
  3842. "should_generate_summary": True,
  3843. "summary_mode": "daily",
  3844. },
  3845. "current": {
  3846. "mode_name": "当前榜单模式",
  3847. "description": "当前榜单模式(当前榜单匹配新闻 + 新增新闻区域 + 按时推送)",
  3848. "realtime_report_type": "实时当前榜单",
  3849. "summary_report_type": "当前榜单汇总",
  3850. "should_send_realtime": True,
  3851. "should_generate_summary": True,
  3852. "summary_mode": "current",
  3853. },
  3854. "daily": {
  3855. "mode_name": "当日汇总模式",
  3856. "description": "当日汇总模式(所有匹配新闻 + 新增新闻区域 + 按时推送)",
  3857. "realtime_report_type": "",
  3858. "summary_report_type": "当日汇总",
  3859. "should_send_realtime": False,
  3860. "should_generate_summary": True,
  3861. "summary_mode": "daily",
  3862. },
  3863. }
  3864. def __init__(self):
  3865. self.request_interval = CONFIG["REQUEST_INTERVAL"]
  3866. self.report_mode = CONFIG["REPORT_MODE"]
  3867. self.rank_threshold = CONFIG["RANK_THRESHOLD"]
  3868. self.is_github_actions = os.environ.get("GITHUB_ACTIONS") == "true"
  3869. self.is_docker_container = self._detect_docker_environment()
  3870. self.update_info = None
  3871. self.proxy_url = None
  3872. self._setup_proxy()
  3873. self.data_fetcher = DataFetcher(self.proxy_url)
  3874. if self.is_github_actions:
  3875. self._check_version_update()
  3876. def _detect_docker_environment(self) -> bool:
  3877. """检测是否运行在 Docker 容器中"""
  3878. try:
  3879. if os.environ.get("DOCKER_CONTAINER") == "true":
  3880. return True
  3881. if os.path.exists("/.dockerenv"):
  3882. return True
  3883. return False
  3884. except Exception:
  3885. return False
  3886. def _should_open_browser(self) -> bool:
  3887. """判断是否应该打开浏览器"""
  3888. return not self.is_github_actions and not self.is_docker_container
  3889. def _setup_proxy(self) -> None:
  3890. """设置代理配置"""
  3891. if not self.is_github_actions and CONFIG["USE_PROXY"]:
  3892. self.proxy_url = CONFIG["DEFAULT_PROXY"]
  3893. print("本地环境,使用代理")
  3894. elif not self.is_github_actions and not CONFIG["USE_PROXY"]:
  3895. print("本地环境,未启用代理")
  3896. else:
  3897. print("GitHub Actions环境,不使用代理")
  3898. def _check_version_update(self) -> None:
  3899. """检查版本更新"""
  3900. try:
  3901. need_update, remote_version = check_version_update(
  3902. VERSION, CONFIG["VERSION_CHECK_URL"], self.proxy_url
  3903. )
  3904. if need_update and remote_version:
  3905. self.update_info = {
  3906. "current_version": VERSION,
  3907. "remote_version": remote_version,
  3908. }
  3909. print(f"发现新版本: {remote_version} (当前: {VERSION})")
  3910. else:
  3911. print("版本检查完成,当前为最新版本")
  3912. except Exception as e:
  3913. print(f"版本检查出错: {e}")
  3914. def _get_mode_strategy(self) -> Dict:
  3915. """获取当前模式的策略配置"""
  3916. return self.MODE_STRATEGIES.get(self.report_mode, self.MODE_STRATEGIES["daily"])
  3917. def _has_notification_configured(self) -> bool:
  3918. """检查是否配置了任何通知渠道"""
  3919. return any(
  3920. [
  3921. CONFIG["FEISHU_WEBHOOK_URL"],
  3922. CONFIG["DINGTALK_WEBHOOK_URL"],
  3923. CONFIG["WEWORK_WEBHOOK_URL"],
  3924. (CONFIG["TELEGRAM_BOT_TOKEN"] and CONFIG["TELEGRAM_CHAT_ID"]),
  3925. (
  3926. CONFIG["EMAIL_FROM"]
  3927. and CONFIG["EMAIL_PASSWORD"]
  3928. and CONFIG["EMAIL_TO"]
  3929. ),
  3930. (CONFIG["NTFY_SERVER_URL"] and CONFIG["NTFY_TOPIC"]),
  3931. CONFIG["BARK_URL"],
  3932. CONFIG["SLACK_WEBHOOK_URL"],
  3933. ]
  3934. )
  3935. def _has_valid_content(
  3936. self, stats: List[Dict], new_titles: Optional[Dict] = None
  3937. ) -> bool:
  3938. """检查是否有有效的新闻内容"""
  3939. if self.report_mode in ["incremental", "current"]:
  3940. # 增量模式和current模式下,只要stats有内容就说明有匹配的新闻
  3941. return any(stat["count"] > 0 for stat in stats)
  3942. else:
  3943. # 当日汇总模式下,检查是否有匹配的频率词新闻或新增新闻
  3944. has_matched_news = any(stat["count"] > 0 for stat in stats)
  3945. has_new_news = bool(
  3946. new_titles and any(len(titles) > 0 for titles in new_titles.values())
  3947. )
  3948. return has_matched_news or has_new_news
  3949. def _load_analysis_data(
  3950. self,
  3951. ) -> Optional[Tuple[Dict, Dict, Dict, Dict, List, List]]:
  3952. """统一的数据加载和预处理,使用当前监控平台列表过滤历史数据"""
  3953. try:
  3954. # 获取当前配置的监控平台ID列表
  3955. current_platform_ids = []
  3956. for platform in CONFIG["PLATFORMS"]:
  3957. current_platform_ids.append(platform["id"])
  3958. print(f"当前监控平台: {current_platform_ids}")
  3959. all_results, id_to_name, title_info = read_all_today_titles(
  3960. current_platform_ids
  3961. )
  3962. if not all_results:
  3963. print("没有找到当天的数据")
  3964. return None
  3965. total_titles = sum(len(titles) for titles in all_results.values())
  3966. print(f"读取到 {total_titles} 个标题(已按当前监控平台过滤)")
  3967. new_titles = detect_latest_new_titles(current_platform_ids)
  3968. word_groups, filter_words = load_frequency_words()
  3969. return (
  3970. all_results,
  3971. id_to_name,
  3972. title_info,
  3973. new_titles,
  3974. word_groups,
  3975. filter_words,
  3976. )
  3977. except Exception as e:
  3978. print(f"数据加载失败: {e}")
  3979. return None
  3980. def _prepare_current_title_info(self, results: Dict, time_info: str) -> Dict:
  3981. """从当前抓取结果构建标题信息"""
  3982. title_info = {}
  3983. for source_id, titles_data in results.items():
  3984. title_info[source_id] = {}
  3985. for title, title_data in titles_data.items():
  3986. ranks = title_data.get("ranks", [])
  3987. url = title_data.get("url", "")
  3988. mobile_url = title_data.get("mobileUrl", "")
  3989. title_info[source_id][title] = {
  3990. "first_time": time_info,
  3991. "last_time": time_info,
  3992. "count": 1,
  3993. "ranks": ranks,
  3994. "url": url,
  3995. "mobileUrl": mobile_url,
  3996. }
  3997. return title_info
  3998. def _run_analysis_pipeline(
  3999. self,
  4000. data_source: Dict,
  4001. mode: str,
  4002. title_info: Dict,
  4003. new_titles: Dict,
  4004. word_groups: List[Dict],
  4005. filter_words: List[str],
  4006. id_to_name: Dict,
  4007. failed_ids: Optional[List] = None,
  4008. is_daily_summary: bool = False,
  4009. ) -> Tuple[List[Dict], str]:
  4010. """统一的分析流水线:数据处理 → 统计计算 → HTML生成"""
  4011. # 统计计算
  4012. stats, total_titles = count_word_frequency(
  4013. data_source,
  4014. word_groups,
  4015. filter_words,
  4016. id_to_name,
  4017. title_info,
  4018. self.rank_threshold,
  4019. new_titles,
  4020. mode=mode,
  4021. )
  4022. # HTML生成
  4023. html_file = generate_html_report(
  4024. stats,
  4025. total_titles,
  4026. failed_ids=failed_ids,
  4027. new_titles=new_titles,
  4028. id_to_name=id_to_name,
  4029. mode=mode,
  4030. is_daily_summary=is_daily_summary,
  4031. update_info=self.update_info if CONFIG["SHOW_VERSION_UPDATE"] else None,
  4032. )
  4033. return stats, html_file
  4034. def _send_notification_if_needed(
  4035. self,
  4036. stats: List[Dict],
  4037. report_type: str,
  4038. mode: str,
  4039. failed_ids: Optional[List] = None,
  4040. new_titles: Optional[Dict] = None,
  4041. id_to_name: Optional[Dict] = None,
  4042. html_file_path: Optional[str] = None,
  4043. ) -> bool:
  4044. """统一的通知发送逻辑,包含所有判断条件"""
  4045. has_notification = self._has_notification_configured()
  4046. if (
  4047. CONFIG["ENABLE_NOTIFICATION"]
  4048. and has_notification
  4049. and self._has_valid_content(stats, new_titles)
  4050. ):
  4051. send_to_notifications(
  4052. stats,
  4053. failed_ids or [],
  4054. report_type,
  4055. new_titles,
  4056. id_to_name,
  4057. self.update_info,
  4058. self.proxy_url,
  4059. mode=mode,
  4060. html_file_path=html_file_path,
  4061. )
  4062. return True
  4063. elif CONFIG["ENABLE_NOTIFICATION"] and not has_notification:
  4064. print("⚠️ 警告:通知功能已启用但未配置任何通知渠道,将跳过通知发送")
  4065. elif not CONFIG["ENABLE_NOTIFICATION"]:
  4066. print(f"跳过{report_type}通知:通知功能已禁用")
  4067. elif (
  4068. CONFIG["ENABLE_NOTIFICATION"]
  4069. and has_notification
  4070. and not self._has_valid_content(stats, new_titles)
  4071. ):
  4072. mode_strategy = self._get_mode_strategy()
  4073. if "实时" in report_type:
  4074. print(
  4075. f"跳过实时推送通知:{mode_strategy['mode_name']}下未检测到匹配的新闻"
  4076. )
  4077. else:
  4078. print(
  4079. f"跳过{mode_strategy['summary_report_type']}通知:未匹配到有效的新闻内容"
  4080. )
  4081. return False
  4082. def _generate_summary_report(self, mode_strategy: Dict) -> Optional[str]:
  4083. """生成汇总报告(带通知)"""
  4084. summary_type = (
  4085. "当前榜单汇总" if mode_strategy["summary_mode"] == "current" else "当日汇总"
  4086. )
  4087. print(f"生成{summary_type}报告...")
  4088. # 加载分析数据
  4089. analysis_data = self._load_analysis_data()
  4090. if not analysis_data:
  4091. return None
  4092. all_results, id_to_name, title_info, new_titles, word_groups, filter_words = (
  4093. analysis_data
  4094. )
  4095. # 运行分析流水线
  4096. stats, html_file = self._run_analysis_pipeline(
  4097. all_results,
  4098. mode_strategy["summary_mode"],
  4099. title_info,
  4100. new_titles,
  4101. word_groups,
  4102. filter_words,
  4103. id_to_name,
  4104. is_daily_summary=True,
  4105. )
  4106. print(f"{summary_type}报告已生成: {html_file}")
  4107. # 发送通知
  4108. self._send_notification_if_needed(
  4109. stats,
  4110. mode_strategy["summary_report_type"],
  4111. mode_strategy["summary_mode"],
  4112. failed_ids=[],
  4113. new_titles=new_titles,
  4114. id_to_name=id_to_name,
  4115. html_file_path=html_file,
  4116. )
  4117. return html_file
  4118. def _generate_summary_html(self, mode: str = "daily") -> Optional[str]:
  4119. """生成汇总HTML"""
  4120. summary_type = "当前榜单汇总" if mode == "current" else "当日汇总"
  4121. print(f"生成{summary_type}HTML...")
  4122. # 加载分析数据
  4123. analysis_data = self._load_analysis_data()
  4124. if not analysis_data:
  4125. return None
  4126. all_results, id_to_name, title_info, new_titles, word_groups, filter_words = (
  4127. analysis_data
  4128. )
  4129. # 运行分析流水线
  4130. _, html_file = self._run_analysis_pipeline(
  4131. all_results,
  4132. mode,
  4133. title_info,
  4134. new_titles,
  4135. word_groups,
  4136. filter_words,
  4137. id_to_name,
  4138. is_daily_summary=True,
  4139. )
  4140. print(f"{summary_type}HTML已生成: {html_file}")
  4141. return html_file
  4142. def _initialize_and_check_config(self) -> None:
  4143. """通用初始化和配置检查"""
  4144. now = get_beijing_time()
  4145. print(f"当前北京时间: {now.strftime('%Y-%m-%d %H:%M:%S')}")
  4146. if not CONFIG["ENABLE_CRAWLER"]:
  4147. print("爬虫功能已禁用(ENABLE_CRAWLER=False),程序退出")
  4148. return
  4149. has_notification = self._has_notification_configured()
  4150. if not CONFIG["ENABLE_NOTIFICATION"]:
  4151. print("通知功能已禁用(ENABLE_NOTIFICATION=False),将只进行数据抓取")
  4152. elif not has_notification:
  4153. print("未配置任何通知渠道,将只进行数据抓取,不发送通知")
  4154. else:
  4155. print("通知功能已启用,将发送通知")
  4156. mode_strategy = self._get_mode_strategy()
  4157. print(f"报告模式: {self.report_mode}")
  4158. print(f"运行模式: {mode_strategy['description']}")
  4159. def _crawl_data(self) -> Tuple[Dict, Dict, List]:
  4160. """执行数据爬取"""
  4161. ids = []
  4162. for platform in CONFIG["PLATFORMS"]:
  4163. if "name" in platform:
  4164. ids.append((platform["id"], platform["name"]))
  4165. else:
  4166. ids.append(platform["id"])
  4167. print(
  4168. f"配置的监控平台: {[p.get('name', p['id']) for p in CONFIG['PLATFORMS']]}"
  4169. )
  4170. print(f"开始爬取数据,请求间隔 {self.request_interval} 毫秒")
  4171. ensure_directory_exists("output")
  4172. results, id_to_name, failed_ids = self.data_fetcher.crawl_websites(
  4173. ids, self.request_interval
  4174. )
  4175. title_file = save_titles_to_file(results, id_to_name, failed_ids)
  4176. print(f"标题已保存到: {title_file}")
  4177. return results, id_to_name, failed_ids
  4178. def _execute_mode_strategy(
  4179. self, mode_strategy: Dict, results: Dict, id_to_name: Dict, failed_ids: List
  4180. ) -> Optional[str]:
  4181. """执行模式特定逻辑"""
  4182. # 获取当前监控平台ID列表
  4183. current_platform_ids = [platform["id"] for platform in CONFIG["PLATFORMS"]]
  4184. new_titles = detect_latest_new_titles(current_platform_ids)
  4185. time_info = Path(save_titles_to_file(results, id_to_name, failed_ids)).stem
  4186. word_groups, filter_words = load_frequency_words()
  4187. # current模式下,实时推送需要使用完整的历史数据来保证统计信息的完整性
  4188. if self.report_mode == "current":
  4189. # 加载完整的历史数据(已按当前平台过滤)
  4190. analysis_data = self._load_analysis_data()
  4191. if analysis_data:
  4192. (
  4193. all_results,
  4194. historical_id_to_name,
  4195. historical_title_info,
  4196. historical_new_titles,
  4197. _,
  4198. _,
  4199. ) = analysis_data
  4200. print(
  4201. f"current模式:使用过滤后的历史数据,包含平台:{list(all_results.keys())}"
  4202. )
  4203. stats, html_file = self._run_analysis_pipeline(
  4204. all_results,
  4205. self.report_mode,
  4206. historical_title_info,
  4207. historical_new_titles,
  4208. word_groups,
  4209. filter_words,
  4210. historical_id_to_name,
  4211. failed_ids=failed_ids,
  4212. )
  4213. combined_id_to_name = {**historical_id_to_name, **id_to_name}
  4214. print(f"HTML报告已生成: {html_file}")
  4215. # 发送实时通知(使用完整历史数据的统计结果)
  4216. summary_html = None
  4217. if mode_strategy["should_send_realtime"]:
  4218. self._send_notification_if_needed(
  4219. stats,
  4220. mode_strategy["realtime_report_type"],
  4221. self.report_mode,
  4222. failed_ids=failed_ids,
  4223. new_titles=historical_new_titles,
  4224. id_to_name=combined_id_to_name,
  4225. html_file_path=html_file,
  4226. )
  4227. else:
  4228. print("❌ 严重错误:无法读取刚保存的数据文件")
  4229. raise RuntimeError("数据一致性检查失败:保存后立即读取失败")
  4230. else:
  4231. title_info = self._prepare_current_title_info(results, time_info)
  4232. stats, html_file = self._run_analysis_pipeline(
  4233. results,
  4234. self.report_mode,
  4235. title_info,
  4236. new_titles,
  4237. word_groups,
  4238. filter_words,
  4239. id_to_name,
  4240. failed_ids=failed_ids,
  4241. )
  4242. print(f"HTML报告已生成: {html_file}")
  4243. # 发送实时通知(如果需要)
  4244. summary_html = None
  4245. if mode_strategy["should_send_realtime"]:
  4246. self._send_notification_if_needed(
  4247. stats,
  4248. mode_strategy["realtime_report_type"],
  4249. self.report_mode,
  4250. failed_ids=failed_ids,
  4251. new_titles=new_titles,
  4252. id_to_name=id_to_name,
  4253. html_file_path=html_file,
  4254. )
  4255. # 生成汇总报告(如果需要)
  4256. summary_html = None
  4257. if mode_strategy["should_generate_summary"]:
  4258. if mode_strategy["should_send_realtime"]:
  4259. # 如果已经发送了实时通知,汇总只生成HTML不发送通知
  4260. summary_html = self._generate_summary_html(
  4261. mode_strategy["summary_mode"]
  4262. )
  4263. else:
  4264. # daily模式:直接生成汇总报告并发送通知
  4265. summary_html = self._generate_summary_report(mode_strategy)
  4266. # 打开浏览器(仅在非容器环境)
  4267. if self._should_open_browser() and html_file:
  4268. if summary_html:
  4269. summary_url = "file://" + str(Path(summary_html).resolve())
  4270. print(f"正在打开汇总报告: {summary_url}")
  4271. webbrowser.open(summary_url)
  4272. else:
  4273. file_url = "file://" + str(Path(html_file).resolve())
  4274. print(f"正在打开HTML报告: {file_url}")
  4275. webbrowser.open(file_url)
  4276. elif self.is_docker_container and html_file:
  4277. if summary_html:
  4278. print(f"汇总报告已生成(Docker环境): {summary_html}")
  4279. else:
  4280. print(f"HTML报告已生成(Docker环境): {html_file}")
  4281. return summary_html
  4282. def run(self) -> None:
  4283. """执行分析流程"""
  4284. try:
  4285. self._initialize_and_check_config()
  4286. mode_strategy = self._get_mode_strategy()
  4287. results, id_to_name, failed_ids = self._crawl_data()
  4288. self._execute_mode_strategy(mode_strategy, results, id_to_name, failed_ids)
  4289. except Exception as e:
  4290. print(f"分析流程执行出错: {e}")
  4291. raise
  4292. def main():
  4293. try:
  4294. analyzer = NewsAnalyzer()
  4295. analyzer.run()
  4296. except FileNotFoundError as e:
  4297. print(f"❌ 配置文件错误: {e}")
  4298. print("\n请确保以下文件存在:")
  4299. print(" • config/config.yaml")
  4300. print(" • config/frequency_words.txt")
  4301. print("\n参考项目文档进行正确配置")
  4302. except Exception as e:
  4303. print(f"❌ 程序运行错误: {e}")
  4304. raise
  4305. if __name__ == "__main__":
  4306. main()