diff --git a/main.py b/main.py index c3ab8f0..f2cbb9a 100644 --- a/main.py +++ b/main.py @@ -55,7 +55,7 @@ async def start_tg_bot(): from telegram.request import HTTPXRequest - proxy_request = HTTPXRequest(proxy=PROXY_URL) + proxy_request = HTTPXRequest(proxy=PROXY_URL, connect_timeout=20.0, read_timeout=20.0, write_timeout=20.0, pool_timeout=5.0) tg_app = ( Application.builder() .token(config.TG_BOT_TOKEN) @@ -86,10 +86,17 @@ async def start_tg_bot(): async def stop_tg_bot(): global tg_app if tg_app: - await tg_app.updater.stop() - await tg_app.stop() - await tg_app.shutdown() - logger.info("🛑 TG Bot 已停止") + try: + if tg_app.updater and tg_app.updater.running: + await tg_app.updater.stop() + if tg_app.running: + await tg_app.stop() + await tg_app.shutdown() + logger.info("🛑 TG Bot 已停止") + except Exception as e: + logger.warning(f"⚠️ TG Bot 停止/清理异常: {type(e).__name__}: {e}") + finally: + tg_app = None # ============ FastAPI ============ @@ -98,12 +105,22 @@ from web.api import app as web_app async def start_tg_bot_safe(): - """启动 TG Bot,并确保异常能进日志。""" - try: - await start_tg_bot() - except Exception: - logger.exception("❌ TG Bot 启动失败") - raise + """启动 TG Bot;初始化阶段网络失败时压缩日志并自动重试。""" + delay = 10 + while True: + try: + await start_tg_bot() + return + except asyncio.CancelledError: + raise + except Exception as e: + logger.error(f"❌ TG Bot 启动失败,将在 {delay}s 后重试: {type(e).__name__}: {e}") + try: + await stop_tg_bot() + except Exception: + pass + await asyncio.sleep(delay) + delay = min(120, delay * 2) @asynccontextmanager