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

如何解决Python开发Discord音乐机器人时出现“command 'play' not found”报错

问题原因

  1. 核心错误是music.py中命令函数的缩进层级错误:你把所有带@commands.command装饰器的方法全部写在了__init__构造方法内部,这些函数变成了构造方法的局部函数,discord.py的命令注册机制无法扫描识别,所以会提示命令不存在。你说join、disconnect命令可以正常使用,大概率是这两个方法的实际缩进是正确的,只有play相关方法缩进错误。
  2. 如果你使用的是2.0及以上版本的discord.py,旧的同步加载cog的方式已经失效,也会导致命令注册失败。
  3. 额外注意你当前代码里的暂停命令命名为pausel(末尾是字母L),后续使用时容易和正确的pause混淆。

修复方案

第一步:修正music.py的缩进与加载逻辑

将所有命令方法移出__init__方法,和__init__平级,同时适配discord.py 2.x的异步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 need to be in a vc in order to play 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(name="play")     
    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")

async def setup(client):
    await client.add_cog(music(client))

第二步:调整main.py的cog加载逻辑

将同步加载改为异步加载,避免2.x版本的兼容问题:

import discord
from discord.ext import commands
import music

client = commands.Bot(command_prefix='$', intents = discord.Intents.all())

@client.event
async def on_command_error(ctx, error): 
    if isinstance(error, commands.CommandNotFound): 
        em = discord.Embed(title=f"Error!!!", description=f"Command not found.", color=ctx.author.color) 
        await ctx.send(embed=em)

@client.event
async def on_ready():
    await music.setup(client)
    print('Bot is on!')

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

额外注意

请确认你已经在Discord开发者平台的机器人管理页开启了Message Content Intent权限,否则带前缀的文本命令无法被机器人正常读取。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 08:06:03