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

开发Discord音乐机器人命令失效,报CommandNotFound错误求解决

问题根因
  • 核心问题是代码缩进错误,所有命令函数没有被正确注册到Cog类中,机器人无法识别到命令定义:
    1. 所有@commands.command装饰的方法(join、disconnect、play、pause、resume)都属于music Cog类的成员,需要缩进一层,和__init__方法保持同级对齐
    2. 原代码中disconnect、play方法多缩进了一层,被包裹在join方法的else分支内,不会被识别为独立命令
  • 若使用discord.py 2.0及以上版本,还需要额外开启消息内容意图,否则机器人无法读取前缀触发的命令
修正后的Cog代码
import discord
from discord.ext import commands
import youtube_dl

class music(commands.Cog):
    def __init__(self, client):
        self.client = client

    @commands.command()
    async def join(self,ctx):
        if ctx.author.voice is None:
            await ctx.send("You have to be in a voice channel to listen to music")
        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()
        FFMPEG_OPTIONS = {'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn'}
        YDL_OPTIONS = {'format':"bestaudio"}
        vc = ctx.voice_client

        with youtube_dl.YoutubeDL(YDL_OPTIONS) as ydl:
            info = ydl.extract_info(url,download=False)
            url2 = info ['formats'][0]['url']
            source = await discord.FFmpegOpusAudio.from_probe(url2, **FFMPEG_OPTIONS)
            vc.play(source)

    @commands.command()
    async def pause(self,ctx):
        await ctx.voice_client.pause()
        await ctx.send("Paused")

    @commands.command()
    async def resume(self,ctx):
        await ctx.voice_client.resume()
        await ctx.send("Resumed")

def setup(client):
    client.add_cog(music(client))
额外配置检查

你需要在机器人主文件中确保开启了消息内容意图,并且正确加载了该Cog,参考配置如下:

import discord
from discord.ext import commands

# 开启必要权限
intents = discord.Intents.default()
intents.message_content = True

# 初始化机器人,替换为你自己的命令前缀
client = commands.Bot(command_prefix='!', intents=intents)

# 加载音乐Cog,替换为你存放上述代码的文件名(不需要带.py后缀)
client.load_extension('music')

client.run('你的机器人Token')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 21:00:03