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

Discord Bot启动无报错但命令无法识别提示CommandNotFound

故障根因

所有命令未被注册的核心原因是缩进错误:你把所有带@commands.command()装饰器的命令方法,全部写在了music Cog类的__init__构造方法内部。discord.py加载Cog时,只会识别类下与__init__同级的直接方法作为可注册命令,嵌套在__init__内部的方法完全不会被扫描到,因此启动时无报错,但实际没有任何命令被成功加载,触发CommandNotFound异常。
另外你的join命令还存在逻辑缩进错误:连接语音频道的代码被写在了if ctx.author.voice is None的判断块内,会导致用户不在语音频道时反而尝试获取语音频道对象触发报错,用户在语音频道时又不会执行连接逻辑。

修复步骤
  • 调整music.py的代码缩进,将所有命令方法移出__init__方法,与__init__保持同一缩进层级,作为music类的直接成员
  • 修正join命令的判断逻辑,仅当用户不在语音频道时发送提示并终止执行,用户在频道时再执行连接逻辑

修正后的完整music.py代码如下:

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("请先加入一个语音频道")
            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()
    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("已暂停播放")

    @commands.command()
    async def resume(self,ctx):
        await ctx.voice_client.resume()
        await ctx.send("已恢复播放")

    @commands.command()
    async def test(self,ctx):
        await ctx.send("test!")

def setup(client):
    client.add_cog(music(client))
额外注意事项
  • 替换代码后重启Bot,发送?test即可收到正常回复
  • Replit环境运行音乐功能需要提前在依赖中安装ffmpeg,否则播放功能会报错
  • 不要把真实的Bot Token硬编码在代码里,建议用Replit的环境变量存储,避免Token泄露被他人盗用
  • 你当前使用的youtube_dl库已经停止维护,后续播放功能如果出现解析失败,可以替换为维护分支yt-dlp

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 05:03:19