-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhourly_bot.py
More file actions
193 lines (163 loc) · 5.53 KB
/
Copy pathhourly_bot.py
File metadata and controls
193 lines (163 loc) · 5.53 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
"""按平台节奏执行推送。
用法:
# 直接运行(按配置决定当前小时需要发哪些平台)
python hourly_bot.py
# 只抓 X
python hourly_bot.py --only x
# 忽略节奏限制,当前小时强制检查全部平台
python hourly_bot.py --force
Windows 定时任务设置:
schtasks /create /tn "AI-Daily-Hourly" /tr "python D:\\code\\self-project\\feishu-feed-test\\hourly_bot.py" /sc hourly
"""
import argparse
import json
import sys
import time
from datetime import datetime, timedelta, timezone
from config import load_config
from delivery import (
due_platform_keys,
filter_recent_articles,
get_delivery_config,
load_delivery_state,
mark_sent_articles,
save_delivery_state,
)
from fetcher import fetch_hn, fetch_reddit, fetch_x
from logger import get_logger, init_logging
from sender import build_ai_daily_card, send_card
from summarizer import summarize
log = get_logger("hourly_bot")
PLATFORM_FETCHERS = {
"x": fetch_x,
"reddit": fetch_reddit,
"hn": fetch_hn,
}
def run_platform(
platform_key: str,
now_utc: datetime,
state: dict[str, dict[str, str]],
dry_run: bool,
webhook_url: str,
) -> None:
dconfig = get_delivery_config(platform_key)
fetch_fn = PLATFORM_FETCHERS[platform_key]
cn_tz = timezone(timedelta(hours=8))
plog = log.bind(platform=platform_key)
plog.info(
"Fetcher start: platform={}, fetch_hours={}, cadence_hours={}",
dconfig.platform, dconfig.fetch_hours, dconfig.cadence_hours,
)
t0 = time.time()
articles = fetch_fn(hours=dconfig.fetch_hours)
plog.info("Fetched {} articles in {:.1f}s", len(articles), time.time() - t0)
filtered_articles = filter_recent_articles(
state=state,
platform_key=platform_key,
articles=articles,
now=now_utc,
dedupe_hours=dconfig.dedupe_hours,
)
plog.info(
"After dedupe filter: {} articles (raw={})",
len(filtered_articles), len(articles),
)
if len(filtered_articles) < dconfig.min_articles:
plog.warning(
"Too few articles ({} < {}), skipping",
len(filtered_articles), dconfig.min_articles,
)
return
plog.info("Summarizer start")
t0 = time.time()
categories = summarize(filtered_articles, platform=dconfig.platform)
item_total = sum(len(c.get("items", [])) for c in categories)
plog.info(
"Generated {} categories, {} items in {:.1f}s",
len(categories), item_total, time.time() - t0,
)
if item_total == 0:
plog.warning("No items generated by summarizer, skipping")
return
plog.info("Card builder start")
start_time_utc = now_utc - timedelta(hours=dconfig.fetch_hours)
payload = build_ai_daily_card(
categories,
platform=dconfig.platform,
start_time=start_time_utc.astimezone(cn_tz),
end_time=now_utc.astimezone(cn_tz),
)
preview_path = f"tmp/hourly_bot_{platform_key}_preview.json"
with open(preview_path, "w", encoding="utf-8") as f:
json.dump(payload, f, ensure_ascii=False, indent=2)
plog.info("Preview saved to: {}", preview_path)
if dry_run:
plog.info("Dry run mode — card NOT sent")
return
if not webhook_url:
plog.error("FEISHU_WEBHOOK_URL not configured")
return
plog.info("Sending card to Feishu")
try:
result = send_card(webhook_url, payload)
plog.info("Card sent: {}", result)
mark_sent_articles(state, platform_key, filtered_articles, now_utc)
except Exception:
plog.exception("Failed to send card")
def main():
parser = argparse.ArgumentParser(description="AI 资讯按平台节奏推送")
parser.add_argument(
"--only",
choices=["x", "reddit", "hn", "all"],
default="all",
help="只抓某个平台 (默认 all)",
)
parser.add_argument(
"--force",
action="store_true",
help="忽略平台节奏限制,当前小时强制运行选中的平台",
)
parser.add_argument(
"--dry-run",
action="store_true",
help="只生成预览,不发 Feishu",
)
args = parser.parse_args()
sys.stdout.reconfigure(encoding="utf-8")
cfg = load_config()
init_logging(level=cfg.log_level, log_file=cfg.log_file)
utc_now = datetime.now(timezone.utc)
cn_tz = timezone(timedelta(hours=8))
now_cn = utc_now.astimezone(cn_tz)
log.info("AI hourly bot started")
if args.only == "all":
selected_keys = list(PLATFORM_FETCHERS.keys())
if not args.force:
due_keys = set(due_platform_keys(now_cn))
selected_keys = [key for key in selected_keys if key in due_keys]
log.info(
"Current CN hour: {}, due platforms: {}",
now_cn.strftime("%Y-%m-%d %H:%M"),
", ".join(selected_keys) or "none",
)
else:
selected_keys = [args.only]
if not selected_keys:
log.info("No platforms due in this run, exiting")
return
state = load_delivery_state()
for platform_key in selected_keys:
try:
run_platform(
platform_key=platform_key,
now_utc=utc_now,
state=state,
dry_run=args.dry_run,
webhook_url=cfg.feishu_webhook_url,
)
except Exception:
log.exception("Platform {} run failed", platform_key)
save_delivery_state(state)
log.info("AI hourly bot finished")
if __name__ == "__main__":
main()