Search code examples
discorddiscord.net

How do I capture who joined/left a discord voice channel via api?


I have a bot I'm working on, I'm using C# and this SDK https://github.com/RogueException/Discord.Net

I'm trying to figure out how I can fire off a method based on when someone joins a voice channel and leaves, based on who it is. The Discord API channel says I need to use the Gateway and the "Voice State Update" event, but I'm not really clear on how to do that.

Is there a way to do it using the docs, https://discord.foxbot.me/docs/api/index.html, from the SDK?


Solution

  • I wrote a short example, I hope this will help.

    private static Task Example(SocketUser user, SocketVoiceState oldVoiceState, SocketVoiceState newVoiceState)
            {
                if(oldVoiceState.VoiceChannel == null && newVoiceState.VoiceChannel != null)
                {
                    //User joined
                    Console.WriteLine($"User (Name: {user.Username} ID: {user.Id}) joined to a VoiceChannel (Name: {newVoiceState.VoiceChannel.Name} ID: {newVoiceState.VoiceChannel.Id})");
                }
                if (oldVoiceState.VoiceChannel != null && newVoiceState.VoiceChannel == null)
                {
                    //User left
                    Console.WriteLine($"User (Name: {user.Username} ID: {user.Id}) left from a VoiceChannel (Name: {oldVoiceState.VoiceChannel.Name} ID: {oldVoiceState.VoiceChannel.Id})");
                }
                return Task.CompletedTask;
            }