Discord音乐Bot无法识别play命令问题排查求助
问题排查与修复方案
你的核心问题是Cog未正确加载,同时代码存在几处语法/API使用错误,导致play命令无法被识别或执行。以下是具体修复点:
1. 修复Cog加载方式(主程序)
你当前使用bot.add_cog("cogs.music_player")的方式完全错误,add_cog需要传入Cog类的实例,而非字符串路径。推荐两种正确加载方式:
方式一:直接导入Cog类
修改主程序代码:
import discord from discord.ext import commands from cogs.music_player import music_player # 导入Cog类 intents = discord.Intents.default() intents.message_content = True bot = commands.Bot( command_prefix=commands.when_mentioned_or("!"), description='Relatively simple music bot example', intents=intents, ) @bot.event async def on_ready(): print(f'Logged in as {bot.user} (ID: {bot.user.id})') print('------') bot.add_cog(music_player(bot)) # 实例化Cog并传入bot对象
方式二:使用load_extension(更规范)
主程序代码改为:
import discord from discord.ext import commands intents = discord.Intents.default() intents.message_content = True bot = commands.Bot( command_prefix=commands.when_mentioned_or("!"), description='Relatively simple music bot example', intents=intents, ) @bot.event async def on_ready(): print(f'Logged in as {bot.user} (ID: {bot.user.id})') print('------') bot.load_extension("cogs.music_player") # 通过路径加载Cog文件
注意:使用此方式时,music_player.py必须放在cogs文件夹下,且文件夹内需要有一个空的__init__.py文件。
2. 修复music_player.py中的代码错误
(1)修复语音频道获取API
discord.py v1.5+版本后,ctx.author.voice_channel已被废弃,需改为ctx.author.voice.channel,同时增加空值判断避免报错:
# 原代码 voice_channel = ctx.author.voice_channel # 修改为 voice_channel = ctx.author.voice.channel if ctx.author.voice else None
(2)修复函数名拼写错误
play_song方法中调用了不存在的next_song函数,实际你的函数名为play_next,修改为:
self.vc.play(discord.FFmpegPCMAudio(music_link, **self.ffmpeg_options), after=lambda e: self.play_next())
(3)简化命令参数处理
play命令中*, args的写法可以直接替换为*, query,避免多余的字符串拼接:
@commands.command() async def play(self, ctx, *, query): # 移除原代码中的 query = " ".join(args) # 直接使用query变量即可
(4)修复暂停状态逻辑漏洞
恢复播放时需要重置ispaused状态,否则下次调用play会重复触发恢复操作:
elif self.ispaused == True: self.vc.resume() self.ispaused = False # 新增此行重置状态
3. 其他必要检查
- 确保已安装所有依赖:执行
pip install discord.py youtube-dl ffmpeg-python,同时系统需安装FFmpeg(需添加到环境变量)。 - 检查Bot权限:确保Bot拥有连接语音频道、发送消息、语音活动的权限。
- 目录结构:
cogs文件夹需与主程序在同一目录下,且文件名与类名大小写一致。
按上述步骤修改后,重新运行Bot,play命令即可正常识别并执行。
内容的提问来源于stack exchange,提问作者Zaid Tahir
相关产品推荐
相关产品推荐

