使用discord.py Cogs时出现CommandNotFound错误及协程未等待警告
问题解决:discord.py Cogs加载失败与命令找不到
问题根源
- 异步方法未被await:discord.py 2.0+ 中
load_extension和add_cog都是异步方法,你的代码直接调用未加await,导致Cogs根本没被加载,所以!hi命令不存在。 - Cog监听器缺少self参数:
on_member_join作为类成员方法,必须以self作为第一个参数,否则后续用户加入时会触发错误。
修复步骤
1. 修改主程序代码(正确加载Cogs)
将加载扩展的逻辑放到异步上下文里,比如在on_ready事件中执行:
import discord from discord.ext import commands import os TOKEN = 'my_token' intents = discord.Intents.default() intents.message_content = True intents.members = True client = commands.Bot(command_prefix='!', intents=intents) @client.event async def on_ready(): await client.change_presence(status=discord.Status.online, activity=discord.Activity(type=discord.ActivityType.watching, name='a server')) print('We have Logged in as {0.user}'.format(client)) # 异步加载所有Cogs for filename in os.listdir('./cogs'): if filename.endswith('.py'): await client.load_extension(f"cogs.{filename[:-3]}") client.run(TOKEN)
2. 修复Cogs代码
- 给
on_member_join添加self参数 setup函数里的add_cog加上await- 移除过时的
pass_context=True
import discord from discord.ext import commands rules = ['Users must obey the discord community guidelines.', 'No racism/homophobia/bullying/etc of any kind Bullying of any kind will end in a mute and possibly a ban.', 'Everyone Can Report', 'No Server Raiding', 'No Chatting In welcome channel', 'No robbing and bankrob is illegal', 'No impersonating'] class Greetings(commands.Cog): def __init__(self, client): self.client = client @commands.Cog.listener() async def on_member_join(self, member): await member.send("Hi there, welcome to the server.") await member.send("These are the rules:") # 用enumerate简化遍历 for idx, rule in enumerate(rules): await member.send(f'RULE {idx+1}: {rule}') @commands.command() async def hi(self, ctx): await ctx.send("hi!") async def setup(client): await client.add_cog(Greetings(client))
额外提示
- 新版本discord.py中,
pass_context=True已经被废弃,无需再声明 - 使用
enumerate遍历序列比range(len())更符合Python风格 - 确保你的discord.py版本是2.x,可通过
pip install -U discord.py更新
内容的提问来源于stack exchange,提问作者SanjaySK
相关产品推荐
相关产品推荐

