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

ASP.NET Core 6中Discord Bot的ConnectAsync方法超时问题求助

解决Discord Bot调用ConnectAsync后超时断开的问题

针对你遇到的调用ConnectAsync后机器人成功加入语音频道但挂起超时断开的问题,可通过以下几个步骤排查解决:

1. 保留音频客户端的持久引用

局部变量的audioClient可能在异步操作完成后被垃圾回收,导致连接异常断开。将其改为类级别的成员变量,维持持久引用:

private IAudioClient _audioClient; // 类级别的音频客户端引用

private async Task HandleMessageReceived(SocketMessage message)
{
    if (message.Author.Id == _client.CurrentUser.Id)
    {
        return;
    }

    else if (message.Content == "!ping")
    {
        await message.Channel.SendMessageAsync("Pong!");
    }

    else if (message.Content == "!join" && message.Author is IGuildUser guildUser)
    {
        _voiceChannel = guildUser.VoiceChannel;
        if (_voiceChannel != null)
        {
            await message.Channel.SendMessageAsync("I joined the channel.");
            // 将音频客户端赋值给类变量,避免被GC回收
            _audioClient = await guildUser.VoiceChannel.ConnectAsync();
        }
        else
        {
            await message.Channel.SendMessageAsync("You need to be in a voice channel to use this command.");
        }
    }
}

2. 使用ConfigureAwait(false)避免同步上下文死锁

ASP.NET Core的同步上下文可能导致异步方法挂起超时,在调用ConnectAsync时添加ConfigureAwait(false):

_audioClient = await guildUser.VoiceChannel.ConnectAsync().ConfigureAwait(false);

3. 确保启用了语音相关的网关意图

创建DiscordSocketClient时,必须启用GuildVoiceStates网关意图,否则机器人无法维持语音连接:

var socketConfig = new DiscordSocketConfig
{
    GatewayIntents = GatewayIntents.AllUnprivileged | GatewayIntents.GuildVoiceStates
};
var _client = new DiscordSocketClient(socketConfig);

4. 避免同步阻塞异步方法

确保所有异步操作都使用await,不要使用.Result或.Wait()这类同步阻塞调用,防止上下文死锁。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 16:20:32