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

使用Nextcord开发Discord机器人遇WebSocket 4006会话无效错误

Discord机器人语音连接反复失败(错误4006)解决方案

问题分析

错误nextcord.errors.ConnectionClosed: Shard ID None WebSocket closed with 4006对应Discord语音网关的Session invalidated(会话失效),结合你的场景,核心原因是无效的语音客户端资源未被正确清理,导致新连接复用了失效的会话信息。

解决方案

1. 清理无效语音客户端连接

在尝试连接语音频道前,先检查并清理当前服务器中所有状态异常的语音客户端(比如已断开、正在连接但未成功的实例),确保每次连接都是全新的会话。

2. 升级Nextcord到最新稳定版

旧版本Nextcord可能存在语音连接的会话管理bug,执行以下命令升级:

pip install --upgrade nextcord

3. 优化连接逻辑与错误处理

修改join命令的代码,增加无效客户端清理、更严谨的状态判断,以及重试时的资源重置:

import logging
import nextcord
from nextcord.ext import commands

logging.basicConfig(
    format="%(asctime)s [%(levelname)s] %(message)s (%(filename)s:%(lineno)d)",
    level=logging.INFO
)

TOKEN=""

intents = nextcord.Intents.default()
intents.message_content = True
intents.voice_states = True

bot = commands.Bot(command_prefix="!", intents=intents)

@bot.command()
async def join(ctx):
    channel = ctx.author.voice.channel if ctx.author.voice else None
    if not channel:
        await ctx.send("You must be in a voice channel.")
        return

    # 清理当前服务器中所有无效的语音客户端
    for vc in bot.voice_clients:
        if vc.guild == ctx.guild:
            if not vc.is_connected() or vc.is_connecting():
                await vc.disconnect(force=True)

    # 获取有效语音客户端
    voice_client = nextcord.utils.get(bot.voice_clients, guild=ctx.guild)

    if voice_client and voice_client.is_connected():
        await voice_client.move_to(channel)
    else:
        retry_count = 0
        max_retries = 3
        success = False
        while retry_count < max_retries and not success:
            try:
                await channel.connect(reconnect=True)
                success = True
                await ctx.send(f"Successfully joined {channel.name}")
            except nextcord.errors.ConnectionClosed as e:
                retry_count += 1
                logging.error(f"Voice connection attempt {retry_count} failed: {e.code} - {e.reason}")
                # 重试前再次清理可能残留的无效客户端
                for vc in bot.voice_clients:
                    if vc.guild == ctx.guild:
                        await vc.disconnect(force=True)
                if retry_count == max_retries:
                    await ctx.send(f"Failed to join voice channel after {max_retries} attempts.")

bot.run(TOKEN)

关键修改说明

  • 强制清理无效客户端:在每次连接前和重试前,断开所有当前服务器中状态异常的语音客户端,避免复用失效会话。
  • 增加重试机制:设置最多3次重试,每次重试后重置资源,提高连接成功率。
  • 显式设置reconnect=True:让客户端在连接中断时自动尝试重连,配合资源清理避免会话失效。

额外排查点

  • 确认机器人在目标服务器拥有Connect和Speak语音权限。
  • 若使用自助托管机器人,确保服务器的UDP端口(Discord语音默认使用UDP)未被拦截。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 12:42:51