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

Python Discord音乐机器人无法识别命令问题求助

Discord音乐机器人命令未找到问题解决方法

问题描述

参考教程制作的Discord音乐机器人启动时连接日志正常,但输入/play [yt link]等命令时,机器人报错CommandNotFound: Command "play" is not found,无法识别任何自定义命令。

问题原因

  1. Cogs未正确加载:main.py中仅定义了setup函数但未执行,导致music_cog和help_cog中的命令从未注册到机器人实例。
  2. help_cog.py存在缩进错误:文件开头的import语句有多余缩进,会触发Python语法错误,导致该cog无法加载。

解决方案

修改main.py

删除未执行的setup函数,改用异步主函数加载cogs并启动机器人:

import discord
from discord.ext import commands
import os
import logging
import asyncio
logging.basicConfig(level="INFO")

from help_cog import help_cog
from music_cog import music_cog

async def main():
    intents = discord.Intents.all()
    bot = commands.Bot(command_prefix='/', intents=intents)
    
    bot.remove_command('help')
    
    # 注册cogs到机器人
    await bot.add_cog(help_cog(bot))
    await bot.add_cog(music_cog(bot))
    
    await bot.start(os.getenv("TOKEN"))

asyncio.run(main())

修改help_cog.py

移除开头import语句的多余缩进,修正语法错误:

import discord
from discord.ext import commands

class help_cog(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.help_message = """

General commands:
/help - 显示所有命令
/p <关键词> - 搜索并播放YouTube歌曲
/q - 查看当前队列
/skip - 跳过当前歌曲
/clear - 清空队列
/leave - 让机器人退出语音频道
/pause - 暂停/继续当前歌曲
/resume - 继续播放当前歌曲

"""
        self.text_channel_list = []

    @commands.Cog.listener()
    async def on_ready(self):
        for guild in self.bot.guilds:
            for channel in guild.text_channels:
                self.text_channel_list.append(channel)

        await self.send_to_all(self.help_message)        

    @commands.command(name="help", help="显示所有可用命令")
    async def help(self, ctx):
        await ctx.send(self.help_message)

    async def send_to_all(self, msg):
        for text_channel in self.text_channel_list:
            await text_channel.send(msg)

说明

  • setup函数是discord.py中扩展文件加载的专用函数,仅当使用bot.load_extension()加载整个文件时才会自动触发。直接导入cog类时,需要手动通过await bot.add_cog()完成注册,且必须在异步环境中执行。
  • 缩进错误会导致Python解释器无法解析代码,修正后才能正常加载help_cog,确保所有自定义命令被机器人识别。

修改完成后重启机器人,即可正常使用/play等命令。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 17:07:03