Discord.py Bot服务器部署报错:Bot对象不支持异步上下文管理器协议
Discord机器人部署时异步上下文管理器报错解决方案
问题场景
本地VSCode开发Discord机器人,新增Cog模块后本地运行正常,但通过huguitis nodes面板部署到服务器时出现报错:
TypeError: 'Bot' object does not support the asynchronous context manager protocol
完整报错堆栈:
warn(message, DistributionWarning, stacklevel=0) Traceback (most recent call last): File "/home/container/main.py", line 93, in <module> asyncio.run(main()) File "/usr/local/lib/python3.11/asyncio/runners.py", line 190, in run return runner.run(main) ^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/asyncio/runners.py", line 118, in run return self._loop.run_until_complete(task) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/asyncio/base_events.py", line 653, in run_until_complete return future.result() ^^^^^^^^^^^^^^^ File "/home/container/main.py", line 89, in main async with bot: TypeError: 'Bot' object does not support the asynchronous context manager protocol
当前核心代码:
- main.py加载Cog部分:
async def load(): for filename in os.listdir("./cogs"): if filename.endswith(".py"): await bot.load_extension(f"cogs.{filename[:-3]}") async def main(): async with bot: await load() await bot.start('ODY3MzIyMDMwMzIzOTI1MDIz.GyYxqx.628pkxcehVTwEqKK55rsVPtAPaAP00Vu26iyJs') asyncio.run(main())
- Cog注册代码:
async def setup(bot): await bot.add_cog(example(bot))
已尝试在机器人就绪时加载Cog,未解决问题。
解决方案
核心原因
报错本质是服务器环境的discord.py版本过低——Bot对象支持async with bot:异步上下文管理器语法,是discord.py v2.0及以上版本新增的特性,本地运行正常说明本地安装的是v2.0+版本,但服务器环境装的是旧版。
具体修复步骤
- 升级服务器的discord.py版本
在服务器终端执行升级命令:
pip install -U discord.py
如果使用虚拟环境,需先激活虚拟环境再执行该命令。
- 无法升级版本时,修改代码适配旧版
移除async with bot:语法,改用传统的先加载Cog再启动的逻辑:
async def load(): for filename in os.listdir("./cogs"): if filename.endswith(".py"): await bot.load_extension(f"cogs.{filename[:-3]}") async def main(): await load() await bot.start('ODY3MzIyMDMwMzIzOTI1MDIz.GyYxqx.628pkxcehVTwEqKK55rsVPtAPaAP00Vu26iyJs') asyncio.run(main())
或者使用同步的bot.run()写法:
def main(): for filename in os.listdir("./cogs"): if filename.endswith(".py"): bot.load_extension(f"cogs.{filename[:-3]}") bot.run('ODY3MzIyMDMwMzIzOTI1MDIz.GyYxqx.628pkxcehVTwEqKK55rsVPtAPaAP00Vu26iyJs') if __name__ == "__main__": main()
- 验证Cog类定义正确性
确保Cog类的基础定义无错误,示例如下:
from discord.ext import commands class example(commands.Cog): def __init__(self, bot): self.bot = bot async def setup(bot): await bot.add_cog(example(bot))
内容的提问来源于stack exchange,提问作者Ömer AKBULUT
相关产品推荐
相关产品推荐

