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

Discord音乐机器人断开重连后提示Not connected to voice问题问询

故障原因

你遇到的问题核心是DiscordUtils库的全局音乐管理器会缓存每个服务器的播放器实例,播放器首次创建时会绑定当时的语音客户端对象。当你执行leave命令断开机器人的语音连接后,旧的语音客户端已经失效,但对应的播放器实例仍然被缓存,下次机器人重新加入语音频道后,play命令仍然读取旧的绑定了失效语音客户端的播放器,所以会抛出「未连接到语音频道」的错误。

修复方案

你只需要修改两处代码即可解决问题:

1. 修改leave命令,离开时删除缓存的旧播放器

在leave命令的断开连接逻辑后,新增删除当前服务器播放器实例的代码,修改后的完整leave命令如下:

@sm.command()
async def leave(ctx):
    voicetrue = ctx.author.voice
    mevoicetrue = ctx.guild.me.voice
    player = music.get_player(guild_id=ctx.guild.id)
    if voicetrue is None:
        embedVar=discord.Embed(color=0x70cfff)
        embedVar.set_author(name=ctx.message.author.name, icon_url=ctx.message.author.avatar_url)
        embedVar.add_field(name=":no_entry_sign: | Error! You are not in a voice channel!", value="-----------------------------")
        return await ctx.send(embed=embedVar)
    if mevoicetrue is None:
        embedVar=discord.Embed(color=0x70cfff)
        embedVar.set_author(name=ctx.message.author.name, icon_url=ctx.message.author.avatar_url)
        embedVar.add_field(name=":no_entry_sign: | Error! I am not connected to a voice channel!", value="-----------------------------")
        return await ctx.send(embed=embedVar)
    
    if ctx.message.author.voice:
        channel = ctx.message.author.voice.channel
        server = ctx.message.guild.voice_client
        await server.disconnect()
        # 新增:删除当前服务器缓存的旧播放器实例
        if player:
            music.delete_player(ctx.guild.id)

2. 给play命令添加容错校验(可选,推荐添加)

为了避免特殊情况(比如机器人被管理员手动踢出语音频道,没有触发leave命令)导致的同类问题,可以在play命令开头新增校验逻辑,发现播放器绑定的语音客户端失效时自动删除旧实例,修改后的play命令开头部分如下:

@sm.command()
async def play(ctx, *, url):
    player = music.get_player(guild_id=ctx.guild.id)
    # 新增校验:如果播放器存在但绑定的语音客户端和当前不一致,删除旧实例
    if player and player.voice != ctx.voice_client:
        music.delete_player(ctx.guild.id)
        player = None
    
    if not player:
        player = music.create_player(ctx, ffmpeg_error_betterfix=True)
    # 剩余原有代码保持不变即可

修改完成后,机器人每次离开语音频道都会清空旧的播放器实例,重新加入后会创建绑定新语音客户端的播放器,不会再出现连接失效的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 08:48:01