/// <summary> /// Initiates a new Lavalink node connection /// </summary> /// <param name="discordClient"></param> /// <param name="config"></param> public LavalinkManager(DiscordSocketClient discordClient, LavalinkManagerConfig config = null) { this.config = config ?? new LavalinkManagerConfig(); this.discordClient = discordClient; // Setup the socket client events discordClient.VoiceServerUpdated += async(voiceServer) => { Console.WriteLine(new LogMessage(LogSeverity.Debug, "Lavalink", "VOICE_SERVER_UPDATE(" + voiceServer.Guild.Id + ")")); await players[voiceServer.Guild.Id].UpdateSessionAsync(SessionChange.Connect, voiceServer); }; discordClient.UserVoiceStateUpdated += async(user, oldVoiceState, newVoiceState) => { // We only need voice state updates for the current user if (user.Id == discordClient.CurrentUser.Id) { if (oldVoiceState.VoiceChannel == null && newVoiceState.VoiceChannel != null) { Console.WriteLine(new LogMessage(LogSeverity.Debug, "Lavalink", "VOICE_STATE_UPDATE(" + newVoiceState.VoiceChannel.Guild.Id + ", Connected)")); // Connected LavalinkPlayer player = players[newVoiceState.VoiceChannel.Guild.Id]; player?.SetSessionId(newVoiceState.VoiceSessionId); } else if (oldVoiceState.VoiceChannel != null && newVoiceState.VoiceChannel == null) { Console.WriteLine(new LogMessage(LogSeverity.Debug, "Lavalink", "VOICE_STATE_UPDATE(" + oldVoiceState.VoiceChannel.Guild.Id + ", Disconnected)")); // Disconnected LavalinkPlayer player = players[oldVoiceState.VoiceChannel.Guild.Id]; player?.SetSessionId(""); await player.UpdateSessionAsync(SessionChange.Disconnect, oldVoiceState.VoiceChannel.Guild.Id); players.Remove(oldVoiceState.VoiceChannel.Guild.Id); } } }; discordClient.Disconnected += (exception) => { foreach (KeyValuePair <ulong, LavalinkPlayer> player in players) { player.Value.DisconnectAsync().GetAwaiter(); } players.Clear(); return(Task.CompletedTask); }; }
/// <summary> /// Joins a voice channel and returns a new instance of <see cref="LavalinkPlayer"/> /// </summary> /// <param name="voiceChannel"></param> /// <returns></returns> public async Task <LavalinkPlayer> JoinAsync(IVoiceChannel voiceChannel) { if (players.ContainsKey(voiceChannel.GuildId)) { throw new InvalidOperationException("This guild is already actively connected"); } LavalinkPlayer player = new LavalinkPlayer(this, voiceChannel); players.Add(voiceChannel.GuildId, player); // Initiates the voice connection await player.ConnectAsync(); return(player); }