- Three independent threads: email poller, AI processor, TG worker - Two queues: _email_queue (raw emails→AI), _tg_queue (AI results→TG) - summarizer.py split: ai_process() (AI only) + tg_send_and_mark() (TG only) - AI retries no longer affect TG polling or email polling
46 lines
1.6 KiB
Python
46 lines
1.6 KiB
Python
import logging
|
|
from typing import Generator, Optional
|
|
from src.config import Config
|
|
from src.email_client import fetch_unseen_emails, mark_as_seen, Email
|
|
from src.ai_client import summarize_email
|
|
from src.tg_bot import send_summary, format_summary
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
def poll_accounts(cfg: Config) -> Generator[tuple[int, Email], None, None]:
|
|
for idx, acct in enumerate(cfg.email_accounts):
|
|
try:
|
|
logger.info(f"检查邮箱: {acct.username}")
|
|
emails = fetch_unseen_emails(acct)
|
|
if emails:
|
|
logger.info(f" 发现 {len(emails)} 封新邮件")
|
|
for mail in emails:
|
|
yield idx, mail
|
|
except Exception as e:
|
|
logger.error(f"轮询 {acct.username} 失败: {e}", exc_info=True)
|
|
|
|
|
|
def ai_process(cfg: Config, acct_idx: int, mail: Email) -> Optional[dict]:
|
|
acct = cfg.email_accounts[acct_idx]
|
|
logger.info(f" 正在摘要: {mail.subject}")
|
|
summary = summarize_email(cfg.ai, acct.username, mail.subject, mail.sender, mail.body)
|
|
summary["recipient"] = acct.username
|
|
text = format_summary(summary)
|
|
return {
|
|
"text": text,
|
|
"data": summary,
|
|
"original_body": mail.body,
|
|
"acct_idx": acct_idx,
|
|
"uid": mail.uid,
|
|
}
|
|
|
|
|
|
def tg_send_and_mark(cfg: Config, info: dict):
|
|
acct = cfg.email_accounts[info["acct_idx"]]
|
|
send_summary(cfg.telegram, cfg.telegram.chat_id,
|
|
info["text"], info["data"],
|
|
info["original_body"], info["acct_idx"])
|
|
mark_as_seen(acct, [info["uid"]])
|
|
logger.info(f" 已发送并标记已读")
|