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

使用python-telegram-bot时出现AttributeError __aexit__错误求助

解决python-telegram-bot异步脚本的AttributeError: __aexit__错误

问题根源

你使用的python-telegram-bot 13.11版本中,telegram.Bot类并未实现异步上下文管理器所需的__aexit__方法,因此无法用async with bot:这种语法。官方文档里的异步上下文管理器用法是v14及以上版本才支持的。

解决方案

方案1:移除异步上下文管理器,直接调用方法

修改异步脚本,去掉async with块,直接使用Bot实例调用异步方法:

import sys
import asyncio
import telegram

async def main():
    bot = telegram.Bot("TOKEN")
    chat_id = "CHANNEL"
    filename = sys.argv[1]
    caption = sys.argv[2]

    # 直接调用send_photo异步方法
    with open(filename, 'rb') as photo_file:
        await bot.send_photo(chat_id=chat_id, photo=photo_file, caption=caption)

if __name__ == '__main__':
    asyncio.run(main())

方案2:升级python-telegram-bot到v14+版本

如果想保留async with语法,可升级库到v14及以上版本:

pip install python-telegram-bot --upgrade

升级后,你原来的异步脚本即可正常运行,v14+版本的Bot类已支持异步上下文管理器。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 03:27:55