forked from sansan0/TrendRadar
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
5431 lines (4615 loc) · 204 KB
/
main.py
File metadata and controls
5431 lines (4615 loc) · 204 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# coding=utf-8
import json
import os
import random
import re
import time
import webbrowser
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
from email.utils import formataddr, formatdate, make_msgid
from datetime import datetime
from pathlib import Path
from typing import Dict, List, Tuple, Optional, Union
import pytz
import requests
import yaml
VERSION = "3.5.0"
# === SMTP邮件配置 ===
SMTP_CONFIGS = {
# Gmail(使用 STARTTLS)
"gmail.com": {"server": "smtp.gmail.com", "port": 587, "encryption": "TLS"},
# QQ邮箱(使用 SSL,更稳定)
"qq.com": {"server": "smtp.qq.com", "port": 465, "encryption": "SSL"},
# Outlook(使用 STARTTLS)
"outlook.com": {
"server": "smtp-mail.outlook.com",
"port": 587,
"encryption": "TLS",
},
"hotmail.com": {
"server": "smtp-mail.outlook.com",
"port": 587,
"encryption": "TLS",
},
"live.com": {"server": "smtp-mail.outlook.com", "port": 587, "encryption": "TLS"},
# 网易邮箱(使用 SSL,更稳定)
"163.com": {"server": "smtp.163.com", "port": 465, "encryption": "SSL"},
"126.com": {"server": "smtp.126.com", "port": 465, "encryption": "SSL"},
# 新浪邮箱(使用 SSL)
"sina.com": {"server": "smtp.sina.com", "port": 465, "encryption": "SSL"},
# 搜狐邮箱(使用 SSL)
"sohu.com": {"server": "smtp.sohu.com", "port": 465, "encryption": "SSL"},
# 天翼邮箱(使用 SSL)
"189.cn": {"server": "smtp.189.cn", "port": 465, "encryption": "SSL"},
# 阿里云邮箱(使用 TLS)
"aliyun.com": {"server": "smtp.aliyun.com", "port": 465, "encryption": "TLS"},
}
# === 多账号推送工具函数 ===
def parse_multi_account_config(config_value: str, separator: str = ";") -> List[str]:
"""
解析多账号配置,返回账号列表
Args:
config_value: 配置值字符串,多个账号用分隔符分隔
separator: 分隔符,默认为 ;
Returns:
账号列表,空字符串会被保留(用于占位)
"""
if not config_value:
return []
# 保留空字符串用于占位(如 ";token2" 表示第一个账号无token)
accounts = [acc.strip() for acc in config_value.split(separator)]
# 过滤掉全部为空的情况
if all(not acc for acc in accounts):
return []
return accounts
def validate_paired_configs(
configs: Dict[str, List[str]],
channel_name: str,
required_keys: Optional[List[str]] = None
) -> Tuple[bool, int]:
"""
验证配对配置的数量是否一致
Args:
configs: 配置字典,key 为配置名,value 为账号列表
channel_name: 渠道名称,用于日志输出
required_keys: 必须有值的配置项列表
Returns:
(是否验证通过, 账号数量)
"""
# 过滤掉空列表
non_empty_configs = {k: v for k, v in configs.items() if v}
if not non_empty_configs:
return True, 0
# 检查必须项
if required_keys:
for key in required_keys:
if key not in non_empty_configs or not non_empty_configs[key]:
return True, 0 # 必须项为空,视为未配置
# 获取所有非空配置的长度
lengths = {k: len(v) for k, v in non_empty_configs.items()}
unique_lengths = set(lengths.values())
if len(unique_lengths) > 1:
print(f"❌ {channel_name} 配置错误:配对配置数量不一致,将跳过该渠道推送")
for key, length in lengths.items():
print(f" - {key}: {length} 个")
return False, 0
return True, list(unique_lengths)[0] if unique_lengths else 0
def limit_accounts(
accounts: List[str],
max_count: int,
channel_name: str
) -> List[str]:
"""
限制账号数量
Args:
accounts: 账号列表
max_count: 最大账号数量
channel_name: 渠道名称,用于日志输出
Returns:
限制后的账号列表
"""
if len(accounts) > max_count:
print(f"⚠️ {channel_name} 配置了 {len(accounts)} 个账号,超过最大限制 {max_count},只使用前 {max_count} 个")
print(f" ⚠️ 警告:如果您是 fork 用户,过多账号可能导致 GitHub Actions 运行时间过长,存在账号风险")
return accounts[:max_count]
return accounts
def get_account_at_index(accounts: List[str], index: int, default: str = "") -> str:
"""
安全获取指定索引的账号值
Args:
accounts: 账号列表
index: 索引
default: 默认值
Returns:
账号值或默认值
"""
if index < len(accounts):
return accounts[index] if accounts[index] else default
return default
# === 配置管理 ===
def load_config():
"""加载配置文件"""
config_path = os.environ.get("CONFIG_PATH", "config/config.yaml")
if not Path(config_path).exists():
raise FileNotFoundError(f"配置文件 {config_path} 不存在")
with open(config_path, "r", encoding="utf-8") as f:
config_data = yaml.safe_load(f)
print(f"配置文件加载成功: {config_path}")
# 构建配置
config = {
"VERSION_CHECK_URL": config_data["app"]["version_check_url"],
"SHOW_VERSION_UPDATE": config_data["app"]["show_version_update"],
"REQUEST_INTERVAL": config_data["crawler"]["request_interval"],
"REPORT_MODE": os.environ.get("REPORT_MODE", "").strip()
or config_data["report"]["mode"],
"RANK_THRESHOLD": config_data["report"]["rank_threshold"],
"SORT_BY_POSITION_FIRST": os.environ.get("SORT_BY_POSITION_FIRST", "").strip().lower()
in ("true", "1")
if os.environ.get("SORT_BY_POSITION_FIRST", "").strip()
else config_data["report"].get("sort_by_position_first", False),
"MAX_NEWS_PER_KEYWORD": int(
os.environ.get("MAX_NEWS_PER_KEYWORD", "").strip() or "0"
)
or config_data["report"].get("max_news_per_keyword", 0),
"REVERSE_CONTENT_ORDER": os.environ.get("REVERSE_CONTENT_ORDER", "").strip().lower()
in ("true", "1")
if os.environ.get("REVERSE_CONTENT_ORDER", "").strip()
else config_data["report"].get("reverse_content_order", False),
"USE_PROXY": config_data["crawler"]["use_proxy"],
"DEFAULT_PROXY": config_data["crawler"]["default_proxy"],
"ENABLE_CRAWLER": os.environ.get("ENABLE_CRAWLER", "").strip().lower()
in ("true", "1")
if os.environ.get("ENABLE_CRAWLER", "").strip()
else config_data["crawler"]["enable_crawler"],
"ENABLE_NOTIFICATION": os.environ.get("ENABLE_NOTIFICATION", "").strip().lower()
in ("true", "1")
if os.environ.get("ENABLE_NOTIFICATION", "").strip()
else config_data["notification"]["enable_notification"],
"MESSAGE_BATCH_SIZE": config_data["notification"]["message_batch_size"],
"DINGTALK_BATCH_SIZE": config_data["notification"].get(
"dingtalk_batch_size", 20000
),
"FEISHU_BATCH_SIZE": config_data["notification"].get("feishu_batch_size", 29000),
"BARK_BATCH_SIZE": config_data["notification"].get("bark_batch_size", 3600),
"SLACK_BATCH_SIZE": config_data["notification"].get("slack_batch_size", 4000),
"BATCH_SEND_INTERVAL": config_data["notification"]["batch_send_interval"],
"FEISHU_MESSAGE_SEPARATOR": config_data["notification"][
"feishu_message_separator"
],
# 多账号配置
"MAX_ACCOUNTS_PER_CHANNEL": int(
os.environ.get("MAX_ACCOUNTS_PER_CHANNEL", "").strip() or "0"
)
or config_data["notification"].get("max_accounts_per_channel", 3),
"PUSH_WINDOW": {
"ENABLED": os.environ.get("PUSH_WINDOW_ENABLED", "").strip().lower()
in ("true", "1")
if os.environ.get("PUSH_WINDOW_ENABLED", "").strip()
else config_data["notification"]
.get("push_window", {})
.get("enabled", False),
"TIME_RANGE": {
"START": os.environ.get("PUSH_WINDOW_START", "").strip()
or config_data["notification"]
.get("push_window", {})
.get("time_range", {})
.get("start", "08:00"),
"END": os.environ.get("PUSH_WINDOW_END", "").strip()
or config_data["notification"]
.get("push_window", {})
.get("time_range", {})
.get("end", "22:00"),
},
"ONCE_PER_DAY": os.environ.get("PUSH_WINDOW_ONCE_PER_DAY", "").strip().lower()
in ("true", "1")
if os.environ.get("PUSH_WINDOW_ONCE_PER_DAY", "").strip()
else config_data["notification"]
.get("push_window", {})
.get("once_per_day", True),
"RECORD_RETENTION_DAYS": int(
os.environ.get("PUSH_WINDOW_RETENTION_DAYS", "").strip() or "0"
)
or config_data["notification"]
.get("push_window", {})
.get("push_record_retention_days", 7),
},
"WEIGHT_CONFIG": {
"RANK_WEIGHT": config_data["weight"]["rank_weight"],
"FREQUENCY_WEIGHT": config_data["weight"]["frequency_weight"],
"HOTNESS_WEIGHT": config_data["weight"]["hotness_weight"],
},
"PLATFORMS": config_data["platforms"],
}
# 通知渠道配置(环境变量优先)
notification = config_data.get("notification", {})
webhooks = notification.get("webhooks", {})
config["FEISHU_WEBHOOK_URL"] = os.environ.get(
"FEISHU_WEBHOOK_URL", ""
).strip() or webhooks.get("feishu_url", "")
config["DINGTALK_WEBHOOK_URL"] = os.environ.get(
"DINGTALK_WEBHOOK_URL", ""
).strip() or webhooks.get("dingtalk_url", "")
config["WEWORK_WEBHOOK_URL"] = os.environ.get(
"WEWORK_WEBHOOK_URL", ""
).strip() or webhooks.get("wework_url", "")
config["WEWORK_MSG_TYPE"] = os.environ.get(
"WEWORK_MSG_TYPE", ""
).strip() or webhooks.get("wework_msg_type", "markdown")
config["TELEGRAM_BOT_TOKEN"] = os.environ.get(
"TELEGRAM_BOT_TOKEN", ""
).strip() or webhooks.get("telegram_bot_token", "")
config["TELEGRAM_CHAT_ID"] = os.environ.get(
"TELEGRAM_CHAT_ID", ""
).strip() or webhooks.get("telegram_chat_id", "")
# 邮件配置
config["EMAIL_FROM"] = os.environ.get("EMAIL_FROM", "").strip() or webhooks.get(
"email_from", ""
)
config["EMAIL_PASSWORD"] = os.environ.get(
"EMAIL_PASSWORD", ""
).strip() or webhooks.get("email_password", "")
config["EMAIL_TO"] = os.environ.get("EMAIL_TO", "").strip() or webhooks.get(
"email_to", ""
)
config["EMAIL_SMTP_SERVER"] = os.environ.get(
"EMAIL_SMTP_SERVER", ""
).strip() or webhooks.get("email_smtp_server", "")
config["EMAIL_SMTP_PORT"] = os.environ.get(
"EMAIL_SMTP_PORT", ""
).strip() or webhooks.get("email_smtp_port", "")
# ntfy配置
config["NTFY_SERVER_URL"] = (
os.environ.get("NTFY_SERVER_URL", "").strip()
or webhooks.get("ntfy_server_url")
or "https://ntfy.sh"
)
config["NTFY_TOPIC"] = os.environ.get("NTFY_TOPIC", "").strip() or webhooks.get(
"ntfy_topic", ""
)
config["NTFY_TOKEN"] = os.environ.get("NTFY_TOKEN", "").strip() or webhooks.get(
"ntfy_token", ""
)
# Bark配置
config["BARK_URL"] = os.environ.get("BARK_URL", "").strip() or webhooks.get(
"bark_url", ""
)
# Slack配置
config["SLACK_WEBHOOK_URL"] = os.environ.get("SLACK_WEBHOOK_URL", "").strip() or webhooks.get(
"slack_webhook_url", ""
)
# 输出配置来源信息
notification_sources = []
max_accounts = config["MAX_ACCOUNTS_PER_CHANNEL"]
if config["FEISHU_WEBHOOK_URL"]:
accounts = parse_multi_account_config(config["FEISHU_WEBHOOK_URL"])
count = min(len(accounts), max_accounts)
source = "环境变量" if os.environ.get("FEISHU_WEBHOOK_URL") else "配置文件"
notification_sources.append(f"飞书({source}, {count}个账号)")
if config["DINGTALK_WEBHOOK_URL"]:
accounts = parse_multi_account_config(config["DINGTALK_WEBHOOK_URL"])
count = min(len(accounts), max_accounts)
source = "环境变量" if os.environ.get("DINGTALK_WEBHOOK_URL") else "配置文件"
notification_sources.append(f"钉钉({source}, {count}个账号)")
if config["WEWORK_WEBHOOK_URL"]:
accounts = parse_multi_account_config(config["WEWORK_WEBHOOK_URL"])
count = min(len(accounts), max_accounts)
source = "环境变量" if os.environ.get("WEWORK_WEBHOOK_URL") else "配置文件"
notification_sources.append(f"企业微信({source}, {count}个账号)")
if config["TELEGRAM_BOT_TOKEN"] and config["TELEGRAM_CHAT_ID"]:
tokens = parse_multi_account_config(config["TELEGRAM_BOT_TOKEN"])
chat_ids = parse_multi_account_config(config["TELEGRAM_CHAT_ID"])
# 验证数量一致性
valid, count = validate_paired_configs(
{"bot_token": tokens, "chat_id": chat_ids},
"Telegram",
required_keys=["bot_token", "chat_id"]
)
if valid and count > 0:
count = min(count, max_accounts)
token_source = "环境变量" if os.environ.get("TELEGRAM_BOT_TOKEN") else "配置文件"
notification_sources.append(f"Telegram({token_source}, {count}个账号)")
if config["EMAIL_FROM"] and config["EMAIL_PASSWORD"] and config["EMAIL_TO"]:
from_source = "环境变量" if os.environ.get("EMAIL_FROM") else "配置文件"
notification_sources.append(f"邮件({from_source})")
if config["NTFY_SERVER_URL"] and config["NTFY_TOPIC"]:
topics = parse_multi_account_config(config["NTFY_TOPIC"])
tokens = parse_multi_account_config(config["NTFY_TOKEN"])
# ntfy 的 token 是可选的,但如果配置了,数量必须与 topic 一致
if tokens:
valid, count = validate_paired_configs(
{"topic": topics, "token": tokens},
"ntfy"
)
if valid and count > 0:
count = min(count, max_accounts)
server_source = "环境变量" if os.environ.get("NTFY_SERVER_URL") else "配置文件"
notification_sources.append(f"ntfy({server_source}, {count}个账号)")
else:
count = min(len(topics), max_accounts)
server_source = "环境变量" if os.environ.get("NTFY_SERVER_URL") else "配置文件"
notification_sources.append(f"ntfy({server_source}, {count}个账号)")
if config["BARK_URL"]:
accounts = parse_multi_account_config(config["BARK_URL"])
count = min(len(accounts), max_accounts)
bark_source = "环境变量" if os.environ.get("BARK_URL") else "配置文件"
notification_sources.append(f"Bark({bark_source}, {count}个账号)")
if config["SLACK_WEBHOOK_URL"]:
accounts = parse_multi_account_config(config["SLACK_WEBHOOK_URL"])
count = min(len(accounts), max_accounts)
slack_source = "环境变量" if os.environ.get("SLACK_WEBHOOK_URL") else "配置文件"
notification_sources.append(f"Slack({slack_source}, {count}个账号)")
if notification_sources:
print(f"通知渠道配置来源: {', '.join(notification_sources)}")
print(f"每个渠道最大账号数: {max_accounts}")
else:
print("未配置任何通知渠道")
return config
print("正在加载配置...")
CONFIG = load_config()
print(f"TrendRadar v{VERSION} 配置加载完成")
print(f"监控平台数量: {len(CONFIG['PLATFORMS'])}")
# === 工具函数 ===
def get_beijing_time():
"""获取北京时间"""
return datetime.now(pytz.timezone("Asia/Shanghai"))
def format_date_folder():
"""格式化日期文件夹"""
return get_beijing_time().strftime("%Y年%m月%d日")
def format_time_filename():
"""格式化时间文件名"""
return get_beijing_time().strftime("%H时%M分")
def clean_title(title: str) -> str:
"""清理标题中的特殊字符"""
if not isinstance(title, str):
title = str(title)
cleaned_title = title.replace("\n", " ").replace("\r", " ")
cleaned_title = re.sub(r"\s+", " ", cleaned_title)
cleaned_title = cleaned_title.strip()
return cleaned_title
def ensure_directory_exists(directory: str):
"""确保目录存在"""
Path(directory).mkdir(parents=True, exist_ok=True)
def get_output_path(subfolder: str, filename: str) -> str:
"""获取输出路径"""
date_folder = format_date_folder()
output_dir = Path("output") / date_folder / subfolder
ensure_directory_exists(str(output_dir))
return str(output_dir / filename)
def check_version_update(
current_version: str, version_url: str, proxy_url: Optional[str] = None
) -> Tuple[bool, Optional[str]]:
"""检查版本更新"""
try:
proxies = None
if proxy_url:
proxies = {"http": proxy_url, "https": proxy_url}
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
"Accept": "text/plain, */*",
"Cache-Control": "no-cache",
}
response = requests.get(
version_url, proxies=proxies, headers=headers, timeout=10
)
response.raise_for_status()
remote_version = response.text.strip()
print(f"当前版本: {current_version}, 远程版本: {remote_version}")
# 比较版本
def parse_version(version_str):
try:
parts = version_str.strip().split(".")
if len(parts) != 3:
raise ValueError("版本号格式不正确")
return int(parts[0]), int(parts[1]), int(parts[2])
except:
return 0, 0, 0
current_tuple = parse_version(current_version)
remote_tuple = parse_version(remote_version)
need_update = current_tuple < remote_tuple
return need_update, remote_version if need_update else None
except Exception as e:
print(f"版本检查失败: {e}")
return False, None
def is_first_crawl_today() -> bool:
"""检测是否是当天第一次爬取"""
date_folder = format_date_folder()
txt_dir = Path("output") / date_folder / "txt"
if not txt_dir.exists():
return True
files = sorted([f for f in txt_dir.iterdir() if f.suffix == ".txt"])
return len(files) <= 1
def html_escape(text: str) -> str:
"""HTML转义"""
if not isinstance(text, str):
text = str(text)
return (
text.replace("&", "&")
.replace("<", "<")
.replace(">", ">")
.replace('"', """)
.replace("'", "'")
)
# === 推送记录管理 ===
class PushRecordManager:
"""推送记录管理器"""
def __init__(self):
self.record_dir = Path("output") / ".push_records"
self.ensure_record_dir()
self.cleanup_old_records()
def ensure_record_dir(self):
"""确保记录目录存在"""
self.record_dir.mkdir(parents=True, exist_ok=True)
def get_today_record_file(self) -> Path:
"""获取今天的记录文件路径"""
today = get_beijing_time().strftime("%Y%m%d")
return self.record_dir / f"push_record_{today}.json"
def cleanup_old_records(self):
"""清理过期的推送记录"""
retention_days = CONFIG["PUSH_WINDOW"]["RECORD_RETENTION_DAYS"]
current_time = get_beijing_time()
for record_file in self.record_dir.glob("push_record_*.json"):
try:
date_str = record_file.stem.replace("push_record_", "")
file_date = datetime.strptime(date_str, "%Y%m%d")
file_date = pytz.timezone("Asia/Shanghai").localize(file_date)
if (current_time - file_date).days > retention_days:
record_file.unlink()
print(f"清理过期推送记录: {record_file.name}")
except Exception as e:
print(f"清理记录文件失败 {record_file}: {e}")
def has_pushed_today(self) -> bool:
"""检查今天是否已经推送过"""
record_file = self.get_today_record_file()
if not record_file.exists():
return False
try:
with open(record_file, "r", encoding="utf-8") as f:
record = json.load(f)
return record.get("pushed", False)
except Exception as e:
print(f"读取推送记录失败: {e}")
return False
def record_push(self, report_type: str):
"""记录推送"""
record_file = self.get_today_record_file()
now = get_beijing_time()
record = {
"pushed": True,
"push_time": now.strftime("%Y-%m-%d %H:%M:%S"),
"report_type": report_type,
}
try:
with open(record_file, "w", encoding="utf-8") as f:
json.dump(record, f, ensure_ascii=False, indent=2)
print(f"推送记录已保存: {report_type} at {now.strftime('%H:%M:%S')}")
except Exception as e:
print(f"保存推送记录失败: {e}")
def is_in_time_range(self, start_time: str, end_time: str) -> bool:
"""检查当前时间是否在指定时间范围内"""
now = get_beijing_time()
current_time = now.strftime("%H:%M")
def normalize_time(time_str: str) -> str:
"""将时间字符串标准化为 HH:MM 格式"""
try:
parts = time_str.strip().split(":")
if len(parts) != 2:
raise ValueError(f"时间格式错误: {time_str}")
hour = int(parts[0])
minute = int(parts[1])
if not (0 <= hour <= 23 and 0 <= minute <= 59):
raise ValueError(f"时间范围错误: {time_str}")
return f"{hour:02d}:{minute:02d}"
except Exception as e:
print(f"时间格式化错误 '{time_str}': {e}")
return time_str
normalized_start = normalize_time(start_time)
normalized_end = normalize_time(end_time)
normalized_current = normalize_time(current_time)
result = normalized_start <= normalized_current <= normalized_end
if not result:
print(f"时间窗口判断:当前 {normalized_current},窗口 {normalized_start}-{normalized_end}")
return result
# === 数据获取 ===
class DataFetcher:
"""数据获取器"""
def __init__(self, proxy_url: Optional[str] = None):
self.proxy_url = proxy_url
def fetch_data(
self,
id_info: Union[str, Tuple[str, str]],
max_retries: int = 2,
min_retry_wait: int = 3,
max_retry_wait: int = 5,
) -> Tuple[Optional[str], str, str]:
"""获取指定ID数据,支持重试"""
if isinstance(id_info, tuple):
id_value, alias = id_info
else:
id_value = id_info
alias = id_value
url = f"https://newsnow.busiyi.world/api/s?id={id_value}&latest"
proxies = None
if self.proxy_url:
proxies = {"http": self.proxy_url, "https": self.proxy_url}
headers = {
"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",
"Accept": "application/json, text/plain, */*",
"Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
"Connection": "keep-alive",
"Cache-Control": "no-cache",
}
retries = 0
while retries <= max_retries:
try:
response = requests.get(
url, proxies=proxies, headers=headers, timeout=10
)
response.raise_for_status()
data_text = response.text
data_json = json.loads(data_text)
status = data_json.get("status", "未知")
if status not in ["success", "cache"]:
raise ValueError(f"响应状态异常: {status}")
status_info = "最新数据" if status == "success" else "缓存数据"
print(f"获取 {id_value} 成功({status_info})")
return data_text, id_value, alias
except Exception as e:
retries += 1
if retries <= max_retries:
base_wait = random.uniform(min_retry_wait, max_retry_wait)
additional_wait = (retries - 1) * random.uniform(1, 2)
wait_time = base_wait + additional_wait
print(f"请求 {id_value} 失败: {e}. {wait_time:.2f}秒后重试...")
time.sleep(wait_time)
else:
print(f"请求 {id_value} 失败: {e}")
return None, id_value, alias
return None, id_value, alias
def crawl_websites(
self,
ids_list: List[Union[str, Tuple[str, str]]],
request_interval: int = CONFIG["REQUEST_INTERVAL"],
) -> Tuple[Dict, Dict, List]:
"""爬取多个网站数据"""
results = {}
id_to_name = {}
failed_ids = []
for i, id_info in enumerate(ids_list):
if isinstance(id_info, tuple):
id_value, name = id_info
else:
id_value = id_info
name = id_value
id_to_name[id_value] = name
response, _, _ = self.fetch_data(id_info)
if response:
try:
data = json.loads(response)
results[id_value] = {}
for index, item in enumerate(data.get("items", []), 1):
title = item.get("title")
# 跳过无效标题(None、float、空字符串)
if title is None or isinstance(title, float) or not str(title).strip():
continue
title = str(title).strip()
url = item.get("url", "")
mobile_url = item.get("mobileUrl", "")
if title in results[id_value]:
results[id_value][title]["ranks"].append(index)
else:
results[id_value][title] = {
"ranks": [index],
"url": url,
"mobileUrl": mobile_url,
}
except json.JSONDecodeError:
print(f"解析 {id_value} 响应失败")
failed_ids.append(id_value)
except Exception as e:
print(f"处理 {id_value} 数据出错: {e}")
failed_ids.append(id_value)
else:
failed_ids.append(id_value)
if i < len(ids_list) - 1:
actual_interval = request_interval + random.randint(-10, 20)
actual_interval = max(50, actual_interval)
time.sleep(actual_interval / 1000)
print(f"成功: {list(results.keys())}, 失败: {failed_ids}")
return results, id_to_name, failed_ids
# === 数据处理 ===
def save_titles_to_file(results: Dict, id_to_name: Dict, failed_ids: List) -> str:
"""保存标题到文件"""
file_path = get_output_path("txt", f"{format_time_filename()}.txt")
with open(file_path, "w", encoding="utf-8") as f:
for id_value, title_data in results.items():
# id | name 或 id
name = id_to_name.get(id_value)
if name and name != id_value:
f.write(f"{id_value} | {name}\n")
else:
f.write(f"{id_value}\n")
# 按排名排序标题
sorted_titles = []
for title, info in title_data.items():
cleaned_title = clean_title(title)
if isinstance(info, dict):
ranks = info.get("ranks", [])
url = info.get("url", "")
mobile_url = info.get("mobileUrl", "")
else:
ranks = info if isinstance(info, list) else []
url = ""
mobile_url = ""
rank = ranks[0] if ranks else 1
sorted_titles.append((rank, cleaned_title, url, mobile_url))
sorted_titles.sort(key=lambda x: x[0])
for rank, cleaned_title, url, mobile_url in sorted_titles:
line = f"{rank}. {cleaned_title}"
if url:
line += f" [URL:{url}]"
if mobile_url:
line += f" [MOBILE:{mobile_url}]"
f.write(line + "\n")
f.write("\n")
if failed_ids:
f.write("==== 以下ID请求失败 ====\n")
for id_value in failed_ids:
f.write(f"{id_value}\n")
return file_path
def load_frequency_words(
frequency_file: Optional[str] = None,
) -> Tuple[List[Dict], List[str], List[str]]:
"""
加载频率词配置
Returns:
(词组列表, 词组内过滤词, 全局过滤词)
"""
if frequency_file is None:
frequency_file = os.environ.get(
"FREQUENCY_WORDS_PATH", "config/frequency_words.txt"
)
frequency_path = Path(frequency_file)
if not frequency_path.exists():
raise FileNotFoundError(f"频率词文件 {frequency_file} 不存在")
with open(frequency_path, "r", encoding="utf-8") as f:
content = f.read()
word_groups = [group.strip() for group in content.split("\n\n") if group.strip()]
processed_groups = []
filter_words = []
global_filters = [] # 新增:全局过滤词列表
# 默认区域(向后兼容)
current_section = "WORD_GROUPS"
for group in word_groups:
lines = [line.strip() for line in group.split("\n") if line.strip()]
if not lines:
continue
# 检查是否为区域标记
if lines[0].startswith("[") and lines[0].endswith("]"):
section_name = lines[0][1:-1].upper()
if section_name in ("GLOBAL_FILTER", "WORD_GROUPS"):
current_section = section_name
lines = lines[1:] # 移除标记行
# 处理全局过滤区域
if current_section == "GLOBAL_FILTER":
# 直接添加所有非空行到全局过滤列表
for line in lines:
# 忽略特殊语法前缀,只提取纯文本
if line.startswith(("!", "+", "@")):
continue # 全局过滤区不支持特殊语法
if line:
global_filters.append(line)
continue
# 处理词组区域(保持现有逻辑)
words = lines
group_required_words = []
group_normal_words = []
group_filter_words = []
group_max_count = 0 # 默认不限制
for word in words:
if word.startswith("@"):
# 解析最大显示数量(只接受正整数)
try:
count = int(word[1:])
if count > 0:
group_max_count = count
except (ValueError, IndexError):
pass # 忽略无效的@数字格式
elif word.startswith("!"):
filter_words.append(word[1:])
group_filter_words.append(word[1:])
elif word.startswith("+"):
group_required_words.append(word[1:])
else:
group_normal_words.append(word)
if group_required_words or group_normal_words:
if group_normal_words:
group_key = " ".join(group_normal_words)
else:
group_key = " ".join(group_required_words)
processed_groups.append(
{
"required": group_required_words,
"normal": group_normal_words,
"group_key": group_key,
"max_count": group_max_count, # 新增字段
}
)
return processed_groups, filter_words, global_filters
def parse_file_titles(file_path: Path) -> Tuple[Dict, Dict]:
"""解析单个txt文件的标题数据,返回(titles_by_id, id_to_name)"""
titles_by_id = {}
id_to_name = {}
with open(file_path, "r", encoding="utf-8") as f:
content = f.read()
sections = content.split("\n\n")
for section in sections:
if not section.strip() or "==== 以下ID请求失败 ====" in section:
continue
lines = section.strip().split("\n")
if len(lines) < 2:
continue
# id | name 或 id
header_line = lines[0].strip()
if " | " in header_line:
parts = header_line.split(" | ", 1)
source_id = parts[0].strip()
name = parts[1].strip()
id_to_name[source_id] = name
else:
source_id = header_line
id_to_name[source_id] = source_id
titles_by_id[source_id] = {}
for line in lines[1:]:
if line.strip():
try:
title_part = line.strip()
rank = None
# 提取排名
if ". " in title_part and title_part.split(". ")[0].isdigit():
rank_str, title_part = title_part.split(". ", 1)
rank = int(rank_str)
# 提取 MOBILE URL
mobile_url = ""
if " [MOBILE:" in title_part:
title_part, mobile_part = title_part.rsplit(" [MOBILE:", 1)
if mobile_part.endswith("]"):
mobile_url = mobile_part[:-1]
# 提取 URL
url = ""
if " [URL:" in title_part:
title_part, url_part = title_part.rsplit(" [URL:", 1)
if url_part.endswith("]"):
url = url_part[:-1]
title = clean_title(title_part.strip())
ranks = [rank] if rank is not None else [1]
titles_by_id[source_id][title] = {
"ranks": ranks,
"url": url,
"mobileUrl": mobile_url,
}
except Exception as e:
print(f"解析标题行出错: {line}, 错误: {e}")
return titles_by_id, id_to_name
def read_all_today_titles(
current_platform_ids: Optional[List[str]] = None,
) -> Tuple[Dict, Dict, Dict]:
"""读取当天所有标题文件,支持按当前监控平台过滤"""
date_folder = format_date_folder()
txt_dir = Path("output") / date_folder / "txt"
if not txt_dir.exists():
return {}, {}, {}
all_results = {}
final_id_to_name = {}
title_info = {}
files = sorted([f for f in txt_dir.iterdir() if f.suffix == ".txt"])
for file_path in files:
time_info = file_path.stem
titles_by_id, file_id_to_name = parse_file_titles(file_path)
if current_platform_ids is not None:
filtered_titles_by_id = {}
filtered_id_to_name = {}
for source_id, title_data in titles_by_id.items():
if source_id in current_platform_ids:
filtered_titles_by_id[source_id] = title_data
if source_id in file_id_to_name:
filtered_id_to_name[source_id] = file_id_to_name[source_id]
titles_by_id = filtered_titles_by_id
file_id_to_name = filtered_id_to_name
final_id_to_name.update(file_id_to_name)
for source_id, title_data in titles_by_id.items():
process_source_data(
source_id, title_data, time_info, all_results, title_info
)