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

Python Discord音乐机器人CommandNotFound报错问题求助

Discord音乐机器人错误修复方案

1. 解决RuntimeWarning: 协程'setup'从未被等待

这个警告是因为未正确异步加载Music cog,导致setup协程未执行,进而命令未完成注册。

修正方式:

  • 在主文件roydiscordbot.py中,使用异步方式加载cog,禁止直接调用setup(bot):
import discord
from discord.ext import commands
import asyncio

# 开启必要的权限意图
intents = discord.Intents.default()
intents.message_content = True  # 必须开启,否则无法接收命令消息

bot = commands.Bot(command_prefix='!', intents=intents)

async def main():
    async with bot:
        # 异步加载Music扩展,自动触发setup协程
        await bot.load_extension("Music")
        await bot.start("你的机器人TOKEN")

asyncio.run(main())
  • 在Music.py中,确保setup函数为异步,且正确添加cog:
from discord.ext import commands

class Music(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    # 示例join命令
    @commands.command()
    async def join(self, ctx):
        if ctx.author.voice:
            channel = ctx.author.voice.channel
            await channel.connect()
        else:
            await ctx.send("你不在语音频道里!")

    # play、disconnect等命令同理,需用@commands.command()装饰

async def setup(bot):
    # 必须await添加cog的操作
    await bot.add_cog(Music(bot))

2. 解决CommandNotFound错误

该错误多因命令未正确注册或bot无法接收命令消息,按以下步骤排查:

  • 检查命令前缀:使用命令时必须加上你设置的前缀(比如上述代码中的!),例如输入!join而非直接输入join。
  • 开启Message Content Intent:登录Discord开发者后台,进入机器人页面,在"Privileged Gateway Intents"下开启Message Content Intent,否则bot无法读取用户发送的命令消息。
  • 检查命令装饰器:Music.py中所有命令必须用@commands.command()装饰(不能用@bot.command()),因为cog内的命令需要绑定到Cog类,而非直接绑定到bot实例。
  • 确认discord.py版本:确保安装的是discord.py v2.x版本,v1.x与v2.x加载逻辑不同,可通过pip install -U discord.py升级。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 15:15:36