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

如何在discord.py音乐机器人中实现队列与播放功能联动?

实现队列系统的修改代码

我们直接在原有代码基础上新增队列存储、自动切歌逻辑,同时修复原有代码的已知bug即可:

import discord
from discord.ext import commands
import youtube_dl
import asyncio

class music(commands.Cog):
    def __init__(self, client):
        self.client = client
        # 新增歌曲队列,存储待播放的音频源
        self.music_queue = []
        # 标记当前是否正在播放
        self.is_playing = False
        # 当前语音客户端实例
        self.vc = None
        # FFmpeg和YoutubeDL配置统一放在初始化里方便复用
        self.FFMPEG_OPTIONS = {'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn'}
        self.YDL_OPTIONS = {'format':"worstaudio"}

    # 新增内部方法:播放队列里的下一首歌
    async def play_next(self, ctx):
        if len(self.music_queue) > 0:
            self.is_playing = True
            # 取出队列第一个元素
            next_source = self.music_queue.pop(0)
            # 播放,传入播放结束后的回调函数
            self.vc.play(next_source, after=lambda e: asyncio.run_coroutine_threadsafe(self.play_next(ctx), self.client.loop))
            await ctx.send("开始播放队列中的下一首歌曲")
        else:
            self.is_playing = False
            await ctx.send("队列已空,停止播放")

    @commands.command()
    async def join(self,ctx):
        if ctx.author.voice is None:
            await ctx.send("你还没有加入语音频道")
        voice_channel = ctx.author.voice.channel
        if ctx.voice_client is None:
            self.vc = await voice_channel.connect()
        else:
            # 修复原有代码的bug:原来的ctx.voice_channel改为ctx.voice_client
            await ctx.voice_client.move_to(voice_channel)
            self.vc = ctx.voice_client
      
    @commands.command()
    async def disconnect(self,ctx):
        if ctx.author.voice is None:
            await ctx.send("你还没有加入语音频道") 
        if ctx.voice_client is None:
            await ctx.send("我没有加入任何语音频道")
        else:
            # 退出前清空队列
            self.music_queue.clear()
            self.is_playing = False
            await ctx.voice_client.disconnect()

    @commands.command()
    async def play(self,ctx,url):
        # 先确保机器人已经加入语音频道
        if self.vc is None or not self.vc.is_connected():
            await ctx.invoke(self.join)

        with youtube_dl.YoutubeDL(self.YDL_OPTIONS) as ydl:
            info = ydl.extract_info(url, download=False)
            url2 = info['formats'][0]['url']
            source = await discord.FFmpegOpusAudio.from_probe(url2, **self.FFMPEG_OPTIONS)
            
            # 如果当前没有在播放,直接播放
            if not self.is_playing:
                self.is_playing = True
                self.vc.play(source, after=lambda e: asyncio.run_coroutine_threadsafe(self.play_next(ctx), self.client.loop))
                await ctx.send("开始播放歌曲")
            # 如果正在播放,加入队列
            else:
                self.music_queue.append(source)
                await ctx.send(f"已加入队列,当前队列还有{len(self.music_queue)}首歌")

    @commands.command()
    async def skip(self,ctx):
        if ctx.author.voice is None:
            await ctx.send("你还没有加入语音频道")
        elif not self.is_playing:
            await ctx.send("当前没有正在播放的歌曲")
        else:
            # 停止当前播放,会自动触发play_next回调
            self.vc.stop()
            await ctx.send("已跳过当前歌曲")

    @commands.command()
    async def queue(self, ctx):
        # 新增查看队列的命令
        if len(self.music_queue) == 0:
            await ctx.send("当前队列为空")
        else:
            await ctx.send(f"当前队列共有{len(self.music_queue)}首歌曲待播放")

    @commands.command()
    async def pause(self,ctx):
        if self.vc.is_playing():
            await self.vc.pause()
            await ctx.send("已暂停播放")
        else:
            await ctx.send("当前没有正在播放的内容")

    @commands.command()
    async def resume(self,ctx):
        if self.vc.is_paused():
            await self.vc.resume()
            await ctx.send("已恢复播放")
        else:
            await ctx.send("当前没有暂停的内容")

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

核心逻辑说明

  • 初始化时创建的music_queue列表用来存储所有待播放的音频源
  • 新增的play_next方法作为播放回调,当前歌曲播放结束后会自动调用该方法拉取队列下一首歌曲播放
  • play命令现在会根据当前播放状态决定是直接播放还是把歌曲加入队列,不会再直接打断正在播放的内容
  • 额外新增了queue命令可以查看当前队列长度,你可以根据需要扩展展示队列里的歌曲名称等信息

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 04:30:01