refactor: split TG worker into poller (callbacks) and sender (email summaries) threads

This commit is contained in:
2026-07-15 18:35:01 +08:00
parent 2744d9dd77
commit 2822075f2f
2 changed files with 12 additions and 7 deletions

15
main.py
View File

@@ -98,16 +98,21 @@ def _ai_processor(cfg):
time.sleep(0.1 if pending_futures else 0.5) time.sleep(0.1 if pending_futures else 0.5)
def _tg_worker(cfg): def _tg_poller(cfg):
logger.info("TG 线程已启动") logger.info("TG 轮询线程已启动(按钮回调专用)")
last_update_id = 0 last_update_id = 0
while _running: while _running:
try: try:
last_update_id = poll_telegram(cfg.telegram, cfg, last_update_id) last_update_id = poll_telegram(cfg.telegram, cfg, last_update_id)
except Exception as e: except Exception as e:
logger.error(f"TG 轮询错误: {e}", exc_info=True) logger.error(f"TG 轮询错误: {e}", exc_info=True)
if _running:
_shutdown_event.wait(0.1)
# 每轮只处理一封待发邮件,然后立刻回去 poll Telegram
def _tg_sender(cfg):
logger.info("TG 发送线程已启动(邮件摘要专用)")
while _running:
try: try:
info = _tg_queue.get_nowait() info = _tg_queue.get_nowait()
tg_send_and_mark(cfg, info) tg_send_and_mark(cfg, info)
@@ -122,7 +127,6 @@ def _tg_worker(cfg):
mark_failed(uid_str) mark_failed(uid_str)
except Exception: except Exception:
pass pass
if _running: if _running:
_shutdown_event.wait(0.2) _shutdown_event.wait(0.2)
@@ -140,7 +144,8 @@ def main():
threads = [ threads = [
threading.Thread(target=_email_poller, args=(cfg,), daemon=True), threading.Thread(target=_email_poller, args=(cfg,), daemon=True),
threading.Thread(target=_ai_processor, args=(cfg,), daemon=True), threading.Thread(target=_ai_processor, args=(cfg,), daemon=True),
threading.Thread(target=_tg_worker, args=(cfg,), daemon=True), threading.Thread(target=_tg_poller, args=(cfg,), daemon=True),
threading.Thread(target=_tg_sender, args=(cfg,), daemon=True),
] ]
for t in threads: for t in threads:

View File

@@ -86,8 +86,8 @@ def poll_telegram(tg_cfg: TelegramConfig, cfg: Config, last_update_id: int) -> i
try: try:
resp = requests.get( resp = requests.get(
f"https://api.telegram.org/bot{tg_cfg.bot_token}/getUpdates", f"https://api.telegram.org/bot{tg_cfg.bot_token}/getUpdates",
params={"offset": last_update_id, "timeout": 10}, params={"offset": last_update_id, "timeout": 2, "allowed_updates": ["callback_query", "message"]},
timeout=15, timeout=5,
) )
resp.raise_for_status() resp.raise_for_status()
data = resp.json() data = resp.json()