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

Discord音乐机器人VoiceClient无法识别歌曲播放状态问题

问题分析与解决方案

你的代码核心问题出在无参数分支的逻辑结构错误,导致播放状态判断混乱,进而出现不符合预期的输出。

具体问题点

  1. 独立双if导致无效操作:当机器人正在播放时,第一个if执行暂停后,第二个if会立即检测到暂停状态并执行恢复,相当于没有任何实际操作;如果此时播放状态检测出现延迟(比如is_playing()未及时返回True),两个if都不触发,就会进入else输出“Nothing to play”。
  2. else归属错误:代码中的else仅属于第二个if,而非外层的状态判断逻辑,导致分支逻辑完全混乱。
  3. 缺少语音客户端存在性检查:如果机器人未连接到语音频道,直接访问voice_client的方法会抛出异常,这是潜在的崩溃风险。

修正后的代码

async def play(self, ctx, *, url=''):
    async with ctx.typing():
        if url == '':
            vc = ctx.message.guild.voice_client
            # 先判断机器人是否在语音频道
            if not vc:
                await ctx.send('Nothing to play')
                return
            # 用if-elif-else确保同一时间只进入一个状态分支
            if vc.is_playing():
                vc.pause()
                await ctx.send(f"Bot was paused by {ctx.message.author.mention}")
            elif vc.is_paused():
                vc.resume()
                await ctx.send(f"Bot was resumed by {ctx.message.author.mention}")
            else:
                await ctx.send('Nothing to play')
        else:
            guild_id = ctx.message.guild.id
            if guild_id not in servers:
                servers[guild_id] = {}
            # 建议改用列表存储队列(更合理),这里暂时保留原逻辑
            servers[guild_id][len(servers[guild_id])] = url
            await ctx.send(
                f':mag_right: **Searching for** ``{url}``\n'
                '<:youtube:763374159567781890> **Added to queue:** ``{url}``'
            )
            await self.startPlaying(ctx, 0, servers[guild_id])

额外优化建议

  • 队列存储建议改用列表:原代码用字典长度作为键的方式容易出问题,改为servers[guild_id] = [],添加歌曲时用servers[guild_id].append(url)更直观可靠。
  • 可以添加权限检查:比如判断用户是否在同一个语音频道,避免非频道内用户操作机器人。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 13:45:32