You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

运行多个Telegram Bot时遇Asyncio未关闭会话及授权错误的解决

Telegram Bot 授权错误及未关闭会话问题解决

我编写了一个Telegram Bot,其main.py代码如下:

import asyncio
import logging

from aiogram import Bot, Dispatcher
from aiogram.enums.parse_mode import ParseMode
from aiogram.fsm.storage.memory import MemoryStorage

import config
from handlers import router


async def main():
    bot = Bot(token=config.BOT_TOKEN, parse_mode=ParseMode.HTML)
    dp = Dispatcher(storage=MemoryStorage())
    dp.include_router(router)
    await bot.delete_webhook(drop_pending_updates=True)
    await dp.start_polling(bot, allowed_updates=dp.resolve_used_update_types())


if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO)
    asyncio.run(main())

当尝试在另一个项目中运行该Bot时,出现以下错误:

aiogram.exceptions.TelegramUnauthorizedError: Telegram server says Unauthorized
ERROR:asyncio:Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0x105c55130>
ERROR:asyncio:Unclosed connector
connections: ['[(<aiohttp.client_proto.ResponseHandler object at 0x105c66be0>, 0.718218208)]']
connector: <aiohttp.connector.TCPConnector object at 0x105c55040>

解决步骤

1. 优先处理授权失败问题

TelegramUnauthorizedError是核心问题,后续的未关闭会话警告是授权失败导致资源未正常释放引发的:

  • 检查新项目config.py中的BOT_TOKEN,确保是从@BotFather获取的有效令牌,无拼写错误、空格或特殊字符。
  • 若Bot长时间未使用或令牌被重置,需重新在@BotFather处生成新令牌替换。
  • 确认运行环境可正常访问Telegram API,部分地区需配置代理。

2. 修复未关闭会话警告

授权问题解决后,警告通常会自动消失。若仍存在,可通过async with语法自动管理Bot资源,确保会话正确关闭:
修改main()函数如下:

async def main():
    async with Bot(token=config.BOT_TOKEN, parse_mode=ParseMode.HTML) as bot:
        dp = Dispatcher(storage=MemoryStorage())
        dp.include_router(router)
        await bot.delete_webhook(drop_pending_updates=True)
        await dp.start_polling(bot, allowed_updates=dp.resolve_used_update_types())

内容的提问来源于stack exchange,提问作者Tim Che

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 21:06:17