Discord机器人触发discord.ext.commands.errors.CommandNotFound错误求助
问题:Discord机器人Cog封装命令时出现CommandNotFound错误
我正在为自己的服务器开发Discord机器人,目标是将命令封装在类中实现,但运行代码时持续出现discord.ext.commands.errors.CommandNotFound错误。若将命令移出类并做调整后可正常运行,但我更希望保留类结构。请问我哪里出错了?
以下是我的代码:
import discord from discord.ext import commands class General_commands(commands.Cog): def __init__(self, bot): self.bot = bot @commands.command() async def message(self, ctx:commands.context, *, channel: discord.VoiceChannel): await ctx.channel.send('message') intents = discord.Intents.default() intents.members = True intents.message_content = True bot = commands.Bot(command_prefix='-', intents=intents) @bot.event async def on_ready(): print('Logged in as {0.user}'.format(bot)) bot.add_cog(General_commands(bot)) bot.run(token)
解答
你的问题核心是命令函数的类型注解错误,导致Cog中的命令未被正确注册,Bot因此无法识别该命令。
具体错误点
ctx:commands.context里的context是模块名称,正确的类型应该是commands.Context(首字母大写的类)。错误的注解会让Discord.py无法正确解析命令定义,直接导致命令未被注册,触发CommandNotFound错误。
修复步骤
- 修正类型注解:将
ctx:commands.context改为ctx:commands.Context - 验证命令调用格式:在Discord中使用正确的前缀+参数调用命令,比如输入
-message @目标语音频道(需指定服务器内有效的语音频道)
修复后的代码
import discord from discord.ext import commands class General_commands(commands.Cog): def __init__(self, bot): self.bot = bot @commands.command() async def message(self, ctx:commands.Context, *, channel: discord.VoiceChannel): await ctx.channel.send('message') intents = discord.Intents.default() intents.members = True intents.message_content = True bot = commands.Bot(command_prefix='-', intents=intents) @bot.event async def on_ready(): print('Logged in as {0.user}'.format(bot)) bot.add_cog(General_commands(bot)) bot.run(token)
额外检查项
- 确认
token变量已正确赋值为你的机器人令牌 - 确保机器人拥有发送消息、读取消息内容等必要权限
内容的提问来源于stack exchange,提问作者64Cromosomi
相关产品推荐
相关产品推荐

