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

Discord.py v2本地报错:Bot对象不支持异步上下文管理器协议

问题:Discord Bot异步上下文管理器模式本地运行报错

我的Discord机器人原本使用client.run(token)运行正常,部署到服务器时改用asyncio.run的新循环方式,服务器运行正常,但本地运行相同代码时出现报错:'Bot' object does not support the asynchronous context manager protocol。已确认Discord模块已更新,相关代码如下:

import asyncio
import discord
import os
from decouple import config
from discord.ext import commands

client = commands.Bot(intents=discord.Intents.all(), command_prefix=".")
token = config("TOKEN")

async def load_extensions():
    for filename in os.listdir("./commands/events"):
        if filename.endswith(".py") and not filename.startswith("__"):
            await client.load_extension(f"commands.events.{filename[:-3]}")

    for filename in os.listdir("./commands/text_commands"):
        if filename.endswith(".py") and not filename.startswith("__"):
            await client.load_extension(f"commands.text_commands.{filename[:-3]}")

async def main():
    async with client:
        await load_extensions()
        await client.start(token)

asyncio.run(main())

解决方案

  • 验证本地discord.py版本:异步上下文管理器支持是discord.py 2.0.0及以上版本新增的特性。运行以下命令检查本地版本:

    pip show discord.py
    

    若版本低于2.0.0,执行升级命令:

    pip install --upgrade discord.py
    
  • 检查运行环境的包版本:如果已经升级但仍报错,可能是本地存在多个Python环境,运行代码时调用的是旧版本的discord.py。在代码开头添加版本打印语句,确认运行环境的实际版本:

    import discord
    print(discord.__version__)
    

    若输出低于2.0.0,切换到正确的Python虚拟环境后再运行代码。

  • 替代写法兼容环境:如果不想纠结环境问题,可以移除异步上下文管理器,直接调用client.start(),效果一致且兼容性更好:

    async def main():
        await load_extensions()
        await client.start(token)
    
    asyncio.run(main())
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 16:05:01