discord.py Cogs加载失败问题排查及已验证修复方案
使用discord.py Cogs拆分命令时的TypeError问题及解决方法
尝试将Discord机器人的命令拆分到不同文件中,使用discord.py的Cogs功能,但按照官方文档操作时出现了未在网上找到的错误。
官方提供的两种Cogs加载方式
方式1(来自迁移文档):
async def main(): async with bot: await bot.load_extension('my_extension') await bot.start(TOKEN) asyncio.run(main())
方式2(来自Cog注册文档):
await bot.add_cog(Greetings(bot))
我的代码实现
./server.py
import discord from discord.ext import commands import asyncio intents = discord.Intents.default() intents.message_content = True bot = commands.Bot(command_prefix="/", intents=intents, case_insensitive=False) async def main(): async with bot: await bot.load_extension('MyCog') # method 1 # await bot.add_cog(MyCog(bot)) # method 2 await bot.start('BOT_KEY') asyncio.run(main())
./MyCog.py
from discord.ext import commands class MyCog(commands.Cog): def __init__(self, bot: commands.Bot): self.bot = bot @commands.Cog.listener() async def on_ready(self): print('MyCog loaded!') async def setup(bot): await bot.add_cog(MyCog(bot))
报错信息
使用方式1时的报错:
Exception has occurred: TypeError object list can't be used in 'await' expression File "C:\bot\server.py", line 38, in main await bot.load_extension('MyCog') File "C:\bot\server.py", line 41, in <module> asyncio.run(main()) TypeError: object list can't be used in 'await' expression
使用方式2时的报错:
Exception has occurred: TypeError object NoneType can't be used in 'await' expression File "C:\bot\server.py", line 39, in main await bot.add_cog(MyCog(bot)) File "C:\bot\server.py", line 42, in <module> asyncio.run(main()) TypeError: object NoneType can't be used in 'await' expression
运行环境
- Python版本:3.12.0、3.13.2
- 依赖版本:discord 2.3.2、discord.py 2.5.2
解决方法
卸载discord.py和discord,使用--no-binary选项重新安装discord.py,无需修改代码即可正常运行。
安装命令:
pip install --no-binary :all: "discord.py==2.5.2"
内容的提问来源于stack exchange,提问作者Noah Myers
相关产品推荐
相关产品推荐

