Discord Bot命令未找到:@commands.command()配置问题排查求助
解决Discord Bot中CommandNotFound: Command "join" is not found的问题
问题场景
开发Discord音乐Bot时,已在music_cog.py中定义了join、play等命令,但触发!join时收到以下错误:
discord.ext.commands.errors.CommandNotFound: Command "join" is not found
错误原因
- Cog加载逻辑失效:
main.py中定义的async setup(bot)函数未被执行,音乐Cog未被添加到Bot实例中。 - 导入名称不匹配:
main.py中导入的music_cog与music_cog.py中实际的Cog类名music不一致。 - 命令代码存在潜在Bug:
join命令的else分支调用了错误属性,会导致后续运行报错。
修复步骤
方案1:在on_ready事件中手动加载Cog
修改main.py,在Bot就绪时手动添加Cog:
import discord from discord.ext import commands # 导入正确的Cog类 from music_cog import music bot = commands.Bot(command_prefix='!', intents=discord.Intents.all()) bot.remove_command('help') @bot.event async def on_ready(): # 将音乐Cog添加到Bot实例 await bot.add_cog(music(bot)) print(f"Bot已登录:{bot.user.name}") bot.run("YOUR_TOKEN_HERE")
方案2:使用load_extension自动加载Cog(官方推荐)
修改main.py,采用Discord.py标准扩展加载方式:
import discord from discord.ext import commands import asyncio bot = commands.Bot(command_prefix='!', intents=discord.Intents.all()) bot.remove_command('help') async def main(): # 加载music_cog.py作为Bot扩展 await bot.load_extension('music_cog') await bot.start("YOUR_TOKEN_HERE") asyncio.run(main())
此方案无需修改music_cog.py中的setup函数,Discord.py会自动调用该函数完成Cog加载。
修复join命令的潜在Bug
修改music_cog.py中join命令的else分支,修正属性调用错误:
@commands.command() async def join(self,ctx): if ctx.author.voice is None: await ctx.send("Flaco, no estas en ningun canal de voz. Despertate perro") voice_channel = ctx.author.voice.channel if ctx.voice_client is None: await voice_channel.connect() else: # 修复:使用voice_client而非voice_channel调用move_to await ctx.voice_client.move_to(voice_channel)
额外注意事项
- 确认已安装依赖:
discord.py、youtube-dl(或yt-dlp)、ffmpeg - 检查Bot权限:确保Bot拥有连接语音频道、发送消息的权限
- 验证命令前缀:触发命令时需使用正确的前缀
!
内容的提问来源于stack exchange,提问作者DOlfi
相关产品推荐
相关产品推荐

