Search code examples
c#asynchronousaudioconsolediscord.net

How do I check if my Discord.Net bot is already connected to a Voice Channel


My bot can join and leave a voice channel without issue but how would I validate if it's already connected to a voice chat?

Code from my audio service .cs file

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();
        }

Solution

  • So I was using the VoiceChannel property of .CurrentUser to check if the bot is connected or not and I was having issues with the bot joining and leaving simultaneously or not joining at all. So I decided to just add a bool variable to my class and it works for me.

    private bool voiceCheck;
            public AudioService() { voiceCheck = false; }
    
    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;
                }
                if(voiceCheck == true)
                {
                    await ctx.Channel.SendMessageAsync("Already connected!");
                    return null;
                }
                await ctx.Channel.SendMessageAsync("Joining Voice!");
                voiceCheck = true;
                return await chnl.ConnectAsync();
            }
    
    

    Between my ConnecttoVC and Leave(omitted) methods, voiceCheck would switch between true and false while checking for each respectively.