From 2822075f2fe9f797f3f9faf6a81a338870c1727c Mon Sep 17 00:00:00 2001 From: Zichao Lin Date: Wed, 15 Jul 2026 18:35:01 +0800 Subject: [PATCH] refactor: split TG worker into poller (callbacks) and sender (email summaries) threads --- main.py | 15 ++++++++++----- src/tg_bot.py | 4 ++-- 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/main.py b/main.py index 12a2484..0483505 100644 --- a/main.py +++ b/main.py @@ -98,16 +98,21 @@ def _ai_processor(cfg): time.sleep(0.1 if pending_futures else 0.5) -def _tg_worker(cfg): - logger.info("TG 线程已启动") +def _tg_poller(cfg): + logger.info("TG 轮询线程已启动(按钮回调专用)") last_update_id = 0 while _running: try: last_update_id = poll_telegram(cfg.telegram, cfg, last_update_id) except Exception as e: 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: info = _tg_queue.get_nowait() tg_send_and_mark(cfg, info) @@ -122,7 +127,6 @@ def _tg_worker(cfg): mark_failed(uid_str) except Exception: pass - if _running: _shutdown_event.wait(0.2) @@ -140,7 +144,8 @@ def main(): threads = [ threading.Thread(target=_email_poller, 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: diff --git a/src/tg_bot.py b/src/tg_bot.py index 947ac90..33fcb00 100644 --- a/src/tg_bot.py +++ b/src/tg_bot.py @@ -86,8 +86,8 @@ def poll_telegram(tg_cfg: TelegramConfig, cfg: Config, last_update_id: int) -> i try: resp = requests.get( f"https://api.telegram.org/bot{tg_cfg.bot_token}/getUpdates", - params={"offset": last_update_id, "timeout": 10}, - timeout=15, + params={"offset": last_update_id, "timeout": 2, "allowed_updates": ["callback_query", "message"]}, + timeout=5, ) resp.raise_for_status() data = resp.json()