c# - 如何检查我的 Discord.Net 机器人是否已连接到语音 channel

标签 c# asynchronous audio console discord.net

我的机器人可以毫无问题地加入和离开语音 channel ,但我如何验证它是否已经连接到语音聊天?

我的音频服务 .cs 文件中的代码

public async Task<IAudioClient> ConnecttoVC(SocketCommandContext ctx)
        {
            SocketGuildUser user = ctx.User as SocketGuildUser;
            IVoiceChannel chnl = user.VoiceChannel;
            if(chnl == null)
            {
                await ctx.Channel.SendMessageAsync("Not connected!");
                return null;
            }
            await ctx.Channel.SendMessageAsync("Joining Voice!");
            return await chnl.ConnectAsync();
        }

最佳答案

我知道您说过您在使用 VoiceChannel 加入和离开机器人时遇到问题CurrentUser 的属性(property),但我需要我的机器人知道它是否与执行命令的用户在同一个 channel 中。所以我采用了这种方法,到目前为止测试时没有任何问题。我想我会在这里为任何试图弄清楚如何做到这一点的人分享我的代码。我已经评论了代码,所以希望它应该很容易理解。

public async Task<IAudioClient> ConnectAudio(SocketCommandContext context)
{
    SocketGuildUser user = context.User as SocketGuildUser; // Get the user who executed the command
    IVoiceChannel channel = user.VoiceChannel;

    bool shouldConnect = false;

    if (channel == null) // Check if the user is in a channel
    {
        await context.Message.Channel.SendMessageAsync("Please join a voice channel first.");
    } else
    {
        var clientUser = await context.Channel.GetUserAsync(context.Client.CurrentUser.Id); // Find the client's current user (I.e. this bot) in the channel the command was executed in
        if (clientUser != null)
        {
            if (clientUser is IGuildUser bot) // Cast the client user so we can access the VoiceChannel property
            {
                if (bot.VoiceChannel == null)
                {
                    Console.WriteLine("Bot is not in any channels");
                    shouldConnect = true;
                }
                else if (bot.VoiceChannel.Id == channel.Id)
                {
                    Console.WriteLine($"Bot is already in requested channel: {bot.VoiceChannel.Name}");
                }
                else
                {
                    Console.WriteLine($"Bot is in channel: {bot.VoiceChannel.Name}");
                    shouldConnect = true;
                }
            }
        }
        else
        {
            Console.WriteLine($"Unable to find bot in server: {context.Guild.Name}");
        }
    }

    return (shouldConnect ? await channel.ConnectAsync() : null); // Return the IAudioClient or null if there was no need to connect
}

关于c# - 如何检查我的 Discord.Net 机器人是否已连接到语音 channel ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60242891/

相关文章:

c# - 如何使用 swagger swashbuckle 保护生成的 API 文档

c# - 是否可以在 winforms 应用程序中定义左手组合框(即左侧的滚动条)?

c# - 如何使用可读/可写的本地 XML 设置?

javascript - 在 Node.js 中执行顺序操作

.net - 异步调用与多线程

javascript - 嵌套异步函数的问题(异步系列中的异步 waterfall )

android - 使用OpenSL ES在Android上生成声音

java - 如何在Java中的两个混合器之间创建 "connection"?

c# - 获取当前用户的 ID ASP.NET Membership

file - 计算音频文件的校验和而不考虑标题