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

Discord音乐Bot报错:BotBase.add_cog协程未await及tracemalloc提示

问题解决:Discord音乐Bot的RuntimeWarning与tracemalloc提示

报错分析

1. RuntimeWarning: coroutine 'BotBase.add_cog' was never awaited

这个报错的核心原因是Discord.py v2.0及以上版本中,add_cog方法已从同步函数改为异步协程,必须通过await关键字调用,而你的代码直接同步调用了该方法,导致协程未被执行。

2. tracemalloc提示

这个提示并非错误,只是系统告诉你:如果启用tracemalloc功能,可以追踪内存分配的回溯信息,辅助排查潜在问题。它和第一个报错无关,解决第一个问题后该提示会自动消失。

代码修复步骤

步骤1:修改setup函数为异步并添加await

将原同步的setup函数改为异步函数,并用await调用add_cog:

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

步骤2:修正命令装饰器的缩进

你的代码中@commands.command()没有缩进在music类内部,导致命令未绑定到Cog实例上。必须将装饰器和对应方法统一缩进在类范围内:

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

    @commands.command()
    async def join(self, ctx):
        # 方法内容保持不变

步骤3:修复变量名大小写错误

代码中定义了大写的YDL_OPTIONS,但调用时写成了YDL_Options(大小写不匹配),需统一变量名:

with youtube_dl.YoutubeDL(YDL_OPTIONS) as ydl:

完整修复后的代码

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 join a voice channel!")
        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 stop(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("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))

额外提示

  • 确保你的Discord.py版本为v2.0及以上,旧版本中add_cog仍是同步方法,但建议升级到新版本以获得更好的兼容性和功能支持。
  • youtube_dl已停止维护,推荐使用yt-dlp替代,安装后只需将import youtube_dl改为import yt_dlp as youtube_dl即可,用法基本一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 08:30:53