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

在python-telegram-bot中正确使用aiohttp的ClientSession对象

在python-telegram-bot中复用ClientSession的正确实现

想要在python-telegram-bot中避免为每个HTTP请求创建新的ClientSession对象,原先在main()函数中直接创建ClientSession的写法会触发警告,且无法妥善关闭会话。

错误示例代码:

from aiohttp import ClientSession
from telegram.ext import Application, CommandHandler

app_storage = {}

if __name__ == '__main__':
    app_storage['session'] = ClientSession()
    application = Application.builder().token(some_token).build()
    application.add_handler(CommandHandler('start', wake_up))
    application.run_polling()

已解决(感谢CallMeStag)

正确的实现方式是利用python-telegram-bot提供的post_init和post_shutdown钩子,分别在应用初始化完成后创建会话,在应用关闭前关闭会话,并将会话存储在application.bot_data中供处理器调用:

正确实现代码:

from aiohttp import ClientSession
from telegram.ext import Application, CommandHandler


async def some_name(update, context):
    async with context.bot_data['client'].get(some_url) as response:
        data = await response.json()
        # 其他业务代码


async def post_init(application: Application) -> None:
    application.bot_data['client'] = ClientSession()


async def post_shutdown(application: Application) -> None:
    await application.bot_data['client'].close()


if __name__ == '__main__':
    application = Application.builder().token(some_token).post_init(
        post_init).post_shutdown(post_shutdown).build()
    application.add_handler(CommandHandler('some_command', some_name))    
    application.run_polling()

关键说明:

  • post_init钩子会在应用初始化完成后执行,在这里创建ClientSession并存入bot_data,确保全局复用一个会话
  • post_shutdown钩子会在应用关闭前执行,负责关闭ClientSession,避免资源泄漏
  • 在命令处理器中,通过context.bot_data['client']获取全局会话,发起HTTP请求

内容的提问来源于stack exchange,提问作者Vitaliy Pavlov

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 04:34:59