使用aiogram开发定时通知Telegram机器人遇Bad Gateway错误求助
解决Telegram机器人Polling模式下的Bad Gateway错误
Bad Gateway错误确实大概率是Telegram服务端临时故障或网络波动导致的,以下是无需切换到Webhook的解决方案:
1. 添加自动重试机制
针对get_updates调用实现异常捕获与重试,采用指数退避策略避免频繁请求加重服务端负载:
from aiogram.utils.exceptions import TelegramAPIError import asyncio from functools import wraps def retry_on_api_error(max_retries=3, initial_delay=1): def decorator(func): @wraps(func) async def wrapper(*args, **kwargs): for attempt in range(max_retries): try: return await func(*args, **kwargs) except TelegramAPIError as e: if "Bad Gateway" in str(e) and attempt < max_retries - 1: delay = initial_delay * (2 ** attempt) await asyncio.sleep(delay) continue raise return wrapper return decorator # 给更新获取逻辑添加重试装饰器 @retry_on_api_error(max_retries=5) async def safe_get_updates(bot, offset, timeout): return await bot.get_updates(offset=offset, timeout=timeout)
2. 调整Polling参数优化请求
- 增大
timeout值:将默认超时设置为30-60秒,减少请求频率 - 限制
limit参数:每次仅获取必要数量的更新(最大可设为100,Telegram允许的上限) - 启用
allowed_updates:只订阅机器人需要的更新类型,降低数据传输量
修改启动Polling的代码:
await dp.start_polling( bot, timeout=60, limit=100, allowed_updates=["message", "callback_query"] )
3. 优化网络连接配置
- 配置async兼容代理:若服务器与Telegram网络连通性差,使用支持aiohttp的代理服务
- 调整服务器区域:选择离Telegram服务器更近的机房(如新加坡、荷兰节点)
- 启用TCP长连接:自定义aiohttp会话参数,保持连接存活减少建立开销
4. 全局异常捕获与Polling自动恢复
在主循环中捕获Bad Gateway异常,暂停后自动重启Polling:
async def main(): while True: try: await dp.start_polling( bot, timeout=60, allowed_updates=dp.resolve_used_update_types() ) except TelegramAPIError as e: if "Bad Gateway" in str(e): print("检测到Bad Gateway错误,10秒后重启Polling...") await asyncio.sleep(10) else: raise if __name__ == "__main__": asyncio.run(main())
5. 自定义稳定会话配置
为aiohttp会话设置更宽松的超时与连接参数:
from aiohttp import ClientTimeout, TCPConnector # 配置会话超时与长连接 timeout = ClientTimeout(total=60, connect=10) connector = TCPConnector(keepalive_timeout=30, limit=10) bot = Bot(token="你的机器人Token", session=aiohttp.ClientSession(timeout=timeout, connector=connector))
内容的提问来源于stack exchange,提问作者Dmitry
相关产品推荐
相关产品推荐

