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

Discord.py音乐机器人无法响应命令 提示join命令不存在求助

问题排查与修复方案

错误原因总览

你遇到的CommandNotFound报错是多个语法/逻辑错误共同导致的,按优先级排序如下:

  • 核心错误:所有命令方法的缩进完全错误,全部被嵌套到了music类的__init__构造函数内部,不属于Cog的公开方法,加载Cog时无法识别到这些命令
  • 拼写错误:p播放命令中调用YoutubeDL时的库名写错
  • 命令名不匹配:你预期的leave命令实际定义的方法名为disconnect,触发命令和定义不对应

修正后的代码

音乐模块Cog代码

import discord
from discord.ext import commands
import youtube_dl

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

  # 注意:所有命令方法要和__init__同级,不要缩进进__init__里面
  @commands.command()
  async def join(self, ctx):
      if ctx.author.voice is None:
        await ctx.send("Not in channel")
        return
      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(name="leave") # 加name参数可以直接指定触发命令名,无需改方法名
  async def disconnect(self, ctx):
    if ctx.voice_client:
      await ctx.voice_client.disconnect()

  @commands.command(name="play") # 同理,指定触发名为play,这样!play就可以触发,不用写!p
  async def p(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

      # 修正拼写错误:把youtube.dl改成youtube_dl
      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)

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

主文件无需修改,原有逻辑可正常运行

修正后即可正常使用!join/!play/!leave三个命令。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 22:36:02