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

discord.py音乐机器人命令全部失效,请求技术排查帮助

Discord.py音乐机器人命令无法运行的问题修复

核心问题汇总

主文件问题

  • 同时初始化Hikari和Discord.py的Bot实例,后者覆盖前者导致框架混乱,Hikari在此场景下完全多余,需移除相关代码。
  • 定义的setup函数未被调用,Discord.py的commands.Bot不会自动执行该函数,需直接添加Cog。
  • 环境变量TOKEN定义后未实际使用,硬编码token存在安全风险。

music_cog模块问题

  • 多个方法缩进错误(如search_yt、play_next、play_music),未作为类成员方法存在,调用时会找不到对应方法。
  • 多处拼写错误:
    • YoutubeDl应为导入的YoutubeDL(大写L)
    • download=false中的false应为Python布尔值False
    • self_play()应为self.play_next()
    • self.musoc_queue应为self.music_queue
    • slef.music_queue和slef.vc应为self.music_queue和self.vc
  • clear命令缩进错误,嵌套在queue方法内部,无法被识别为独立命令。

修正后的代码

主文件代码

import discord
from discord.ext import commands
import os

from help_cog import help_cog 
from music_cog import music_cog

# 启用所有必要的权限意图
intents = discord.Intents.all()
# 初始化Discord.py Bot实例
bot = commands.Bot(command_prefix='!', intents=intents)

bot.remove_command('help')

# 直接添加Cog,无需异步setup函数
bot.add_cog(help_cog(bot))
bot.add_cog(music_cog(bot))

# 使用环境变量获取token,避免硬编码
TOKEN = os.getenv('DISCORD_TOKEN')
if TOKEN:
    bot.run(TOKEN)
else:
    print("未找到DISCORD_TOKEN环境变量,请检查配置")

music_cog模块代码

import discord
from discord.ext import commands
from youtube_dl import YoutubeDL

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

        self.is_playing = False
        self.is_paused = False

        self.music_queue = []
        self.YDL_OPTIONS = {'format': 'bestaudio', 'noplaylist': 'True'}
        self.FFMPEG_OPTIONS = {'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn'}

        self.vc = None

    # 修正缩进,作为类成员方法
    def search_yt(self, item):
        with YoutubeDL(self.YDL_OPTIONS) as ydl:
            try:
                # 修正false为Python布尔值False
                info = ydl.extract_info(f'ytsearch:{item}', download=False)['entries'][0]
            except Exception:
                return False
        return {'source': info['formats'][0]['url'], 'title': info['title']}
    
    # 修正缩进
    def play_next(self):
        if len(self.music_queue) > 0:
            self.is_playing = True
            
            m_url = self.music_queue[0][0]['source']
            self.music_queue.pop(0)

            # 修正self_play为self.play_next
            self.vc.play(discord.FFmpegPCMAudio(m_url, **self.FFMPEG_OPTIONS), after=lambda e: self.play_next())
        else:
            self.is_playing = False

    # 修正缩进
    async def play_music(self, ctx):
        if len(self.music_queue) > 0:
            self.is_playing = True
            m_url = self.music_queue[0][0]['source']

            if self.vc is None or not self.vc.is_connected():
                # 修正musoc_queue拼写错误
                self.vc = await self.music_queue[0][1].connect()

                if self.vc is None:
                    await ctx.send('无法连接到语音频道,抱歉Blooketeers!')
                    return
            else:
                await self.vc.move_to(self.music_queue[0][1])

            self.music_queue.pop(0)
            self.vc.play(discord.FFmpegPCMAudio(m_url, **self.FFMPEG_OPTIONS), after=lambda e: self.play_next())
        else:
            self.is_playing = False

    @commands.command(name='play', aliases=['p', 'playing'], help='播放Blooketeers选择的歌曲!')
    async def play(self, ctx, *args):
        query =' '.join(args)

        voice_channel = ctx.author.voice.channel
        if voice_channel is None:
            await ctx.send('先连接到语音频道吧Blooketeers!')
        elif self.is_paused:
            self.vc.resume()
        else:
            song = self.search_yt(query)
            if isinstance(song, bool):
                await ctx.send('抱歉Blooketeers,我无法下载这首歌。格式不正确,试试其他关键词吧。')
            else:
                await ctx.send('歌曲已添加到队列Blooketeers!祝你收听愉快!')
                self.music_queue.append([song, voice_channel])

                if not self.is_playing:
                    await self.play_music(ctx)

    @commands.command(name='pause', help='暂停当前播放的歌曲!')
    async def pause(self, ctx, *args):
        if self.is_playing:
            self.is_playing = False
            self.is_paused = True
            self.vc.pause()
        elif self.is_paused:
            self.is_playing = True
            self.is_paused = False
            self.vc.resume()

    @commands.command(name='resume', aliases=['r'], help='继续播放当前歌曲!')
    async def resume(self, ctx, *args):
        if self.is_paused:
            self.is_playing = True
            self.is_paused = False
            self.vc.resume()

    @commands.command(name='skip', aliases=['s'], help='跳过当前歌曲!')
    async def skip(self, ctx, *args):
        if self.vc is not None and self.vc.is_connected():
            self.vc.stop()
            await self.play_music(ctx)

    @commands.command(name='queue', aliases=['q'], help='显示当前队列中的所有歌曲!')
    async def queue(self, ctx):
        retval = ''
        # 修正slef拼写错误
        for i in range(len(self.music_queue)):
            if i > 4:
                break
            retval += self.music_queue[i][0]['title'] + '\n'

        if retval:
            await ctx.send(retval)
        else:
            await ctx.send('队列里没有音乐Blooketeers,快去添加一些吧!')

    # 修正缩进,成为独立命令
    @commands.command(name='clear', aliases=['c', 'bin'], help='停止当前歌曲并清空队列!')
    async def clear(self, ctx, *args):
        # 修正slef拼写错误
        if self.vc is not None and self.is_playing:
            self.vc.stop()
        self.music_queue = []
        await ctx.send('所有音乐已清空Blooketeers,快去添加更多吧!')

    @commands.command(name='leave', aliases=['disconnect', 'l', 'd'], help='将机器人踢出语音频道!')
    async def leave(self, ctx):
        self.is_playing = False
        self.is_paused = False
        if self.vc is not None and self.vc.is_connected():
            await self.vc.disconnect()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 13:30:41