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

Discord机器人queue队列功能故障:>q命令仅能同时队列2首歌曲求修复方案

问题根源

你当前队列最多只能存入/播放2首歌曲的核心原因是check_queue消费队列歌曲时,没有绑定after回调参数,导致第二首歌曲播放结束后不会再触发下一轮的队列检测逻辑,队列后续的歌曲就无法被自动播放。
另外代码还存在几处冗余逻辑,优化后的完整代码如下:

import discord
from discord.ext import commands
from youtube_dl import YoutubeDL
from discord.utils import get
from discord import FFmpegPCMAudio

queues = {}

# 队列消费逻辑
def check_queue(ctx, guild_id):
    # 先判断队列存在且不为空
    if guild_id in queues and queues[guild_id]:
        voice = ctx.guild.voice_client
        # 播放下一首时同样绑定after回调,保证后续队列可连续消费
        voice.play(queues[guild_id].pop(0), after=lambda x=0: check_queue(ctx, guild_id))

@client.command(pass_context = True)
async def q(ctx, url):
    # 先校验用户是否在语音频道
    if not ctx.author.voice:
        await ctx.send('You are not in a voice channel')
        return
    
    channel = ctx.author.voice.channel
    voice = get(client.voice_clients, guild=ctx.guild)
    # 处理机器人进频道/切频道逻辑
    if voice and voice.is_connected():
        await voice.move_to(channel)
    else:
        voice = await channel.connect()

    YDL_OPTIONS = {'format': 'bestaudio', 'noplaylist': 'True'}
    FFMPEG_OPTIONS = {'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn'}
    
    with YoutubeDL(YDL_OPTIONS) as ydl:
        info = ydl.extract_info(url, download=False)
    source = FFmpegPCMAudio(info['url'], **FFMPEG_OPTIONS)
    guild_id = ctx.guild.id

    if voice.is_playing() or voice.is_paused():
        # 正在播放/暂停状态就入队
        if guild_id in queues:
            queues[guild_id].append(source)
        else:
            queues[guild_id] = [source]
        await ctx.send('Deemo: Song added to queue')
    else:
        # 空闲状态直接播放,绑定队列消费回调
        voice.play(source, after=lambda x=0: check_queue(ctx, guild_id))
        await ctx.send('Playing: '+ info.get('title'))

主要修改点

  • 给check_queue内的播放逻辑补充了after回调,每首歌播放结束都会自动触发下一次队列检测,支持无限长度队列
  • 补充了暂停状态的判断,机器人暂停时新增歌曲也会正常入队不会抢占播放
  • 提前校验用户语音频道状态,不符合直接返回不执行后续冗余逻辑
  • 移除了重复创建FFmpegPCMAudio的冗余代码,复用提前生成的source对象
  • 补充了队列存在性判断,避免空队列调用报错

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 21:06:02