You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Discord音乐机器人无响应:play命令未找到错误求助

问题分析与解决

你遇到的CommandNotFound错误和Discord无关,它并没有取消机器人的play命令功能,问题出在你的代码结构和初始化逻辑上,具体问题及修正方案如下:

核心问题点

  1. 命令未挂载到Bot实例
    你的代码里定义了join、disconnect、play命令,但这些方法既没有放在commands.Cog类中,也没有添加到Bot实例里,导致Bot无法识别这些命令。

  2. 拼写错误
    disconnect方法的参数写成了slef,正确应为self,这个拼写错误会导致方法无法被正常识别。

  3. 缺少Bot初始化与意图配置
    代码没有创建Bot实例,也没有开启必要的消息意图(Discord.py v2.x版本必须开启message_content意图才能接收用户命令消息)。

修正后的完整代码

import discord
from discord.ext import commands
import youtube_dl

# 将命令封装到Cog类中,这是Discord.py管理命令的标准方式
class MusicCog(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.command()
    async def join(self, ctx):
        if ctx.author.voice is None:
            await ctx.send("请先加入一个语音频道!")
        voice_channel = ctx.author.voice.channel
        if ctx.voice_client is None:
            await voice_channel.connect()
        else:
            await ctx.voice_client.move_to(voice_channel)

    @commands.command()
    async def disconnect(self, ctx):
        await ctx.voice_client.disconnect()

    @commands.command()
    async def play(self, ctx, url):
        ctx.voice_client.stop()
        # 补充基础的音频播放逻辑(基于youtube_dl)
        ydl_opts = {
            'format': 'bestaudio/best',
            'postprocessors': [{
                'key': 'FFmpegExtractAudio',
                'preferredcodec': 'mp3',
                'preferredquality': '192',
            }],
        }
        with youtube_dl.YoutubeDL(ydl_opts) as ydl:
            info = ydl.extract_info(url, download=False)
            audio_url = info['formats'][0]['url']
            audio_source = await discord.FFmpegOpusAudio.from_probe(audio_url)
            ctx.voice_client.play(audio_source)
        await ctx.send(f"正在播放: {info['title']}")

# 初始化Bot实例,设置命令前缀并开启必要意图
intents = discord.Intents.default()
intents.message_content = True  # 必须开启该意图才能接收用户命令
bot = commands.Bot(command_prefix='!', intents=intents)

# 当Bot启动完成后加载Cog
@bot.event
async def on_ready():
    await bot.add_cog(MusicCog(bot))
    print(f'已登录为 {bot.user}')

# 替换成你的机器人令牌,运行Bot
bot.run('你的机器人令牌')

关键修改说明

  • 所有命令方法被封装到继承自commands.Cog的类中,确保Bot能正确识别并加载这些命令。
  • 修正了disconnect方法的参数拼写错误。
  • 添加了Bot实例初始化代码,并开启message_content意图,这是接收用户命令的必要配置。
  • 补充了play命令的基础播放逻辑,让机器人能够实际播放音频。

内容的提问来源于stack exchange,提问作者moe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 13:07:23