/// <summary> /// Adiciona novas músicas à playlist utilizando a API do YouTube para realizar a busca. /// </summary> /// <param name="numberOfTracksToGrab"> How many songs to search for. </param> /// <returns></returns> public static async Task AddSongs(short numberOfTracksToGrab) { LavalinkGuildConnection guildConnection = LavalinkNode.GetGuildConnection(await Lavalink.Client.GetGuildAsync(configJson.ServerId).ConfigureAwait(false)); for (int i = 0; i < numberOfTracksToGrab; i++) { WordsGenerator _wordsGenerator = new WordsGenerator(_randomNumber); List <string> wordList = _wordsGenerator.GenerateWordList(); YoutubeSearchEngine _youtubeSearchEngine = new YoutubeSearchEngine(1); Dictionary <string, string> searchResult = _youtubeSearchEngine.SearchVideos(wordList); foreach (var result in searchResult) { Uri videoUri = new Uri(result.Value); LavalinkLoadResult loadResult = await LavalinkNode.Rest.GetTracksAsync(videoUri).ConfigureAwait(false); if (loadResult.LoadResultType == LavalinkLoadResultType.LoadFailed || loadResult.LoadResultType == LavalinkLoadResultType.NoMatches) { await guildConnection.Guild.GetChannel(configJson.ComandosBotCanalId).SendMessageAsync($"ERR0! Pesquisa por {searchResult} falhou! Tipo do resultado: {result.Key}").ConfigureAwait(false); } else { Playlist.Add(loadResult.Tracks.First()); await guildConnection.Guild.GetChannel(configJson.ComandosBotCanalId).SendMessageAsync($"A música: {loadResult.Tracks.First().Title} foi adicionada à playlist de músicas para tocar!").ConfigureAwait(false); } } } }
public async Task Stop(CommandContext ctx) { LavalinkNodeConnection node = ctx.Client.GetLavalink().ConnectedNodes.Values.First(); LavalinkGuildConnection conn = node.GetGuildConnection(ctx.Member.VoiceState.Guild); if (ctx.Member.VoiceState.Channel != conn.Channel) { await ctx.RespondAsync("You are not in a VC with me."); return; } if (conn == null) { await ctx.RespondAsync("Lavalink not connected"); return; } if (conn.CurrentState.CurrentTrack == null) { await ctx.RespondAsync("Nothing playing"); return; } try { LavalinkService.Instance.Queues.Remove(ctx.Guild); } catch { } await conn.StopAsync(); await conn.DisconnectAsync(); await ctx.RespondAsync("Bye"); }
private async Task Player_PlaybackFinished(LavalinkGuildConnection con, TrackFinishEventArgs e) { await Task.Delay(500); this.IsPlaying = false; await this.PlayHandlerAsync(); }
public async Task Resume(CommandContext ctx) { if (ctx.Member.VoiceState == null || ctx.Member.VoiceState.Channel == null) { await ctx.RespondAsync("You are not in a vc."); return; } LavalinkNodeConnection node = ctx.Client.GetLavalink().ConnectedNodes.Values.First(); LavalinkGuildConnection conn = node.GetGuildConnection(ctx.Member.VoiceState.Guild); if (conn == null) { await ctx.RespondAsync("Lavalink not connected"); return; } if (conn.CurrentState.CurrentTrack == null) { await ctx.RespondAsync("Nothing playing"); return; } await conn.ResumeAsync(); await ctx.RespondAsync("Resuming"); }
public async Task Proxima(CommandContext context) { if (context.Channel.Id == BotClient.configJson.ComandosBotCanalId) { guildConnection = BotClient.LavalinkNode.GetGuildConnection(await BotClient.Lavalink.Client.GetGuildAsync(BotClient.configJson.ServerId).ConfigureAwait(false)); if (context.Member.VoiceState == null || context.Member.VoiceState.Channel == null) { await context.RespondAsync($"{context.User.Username} você precisa estar conectado a um canal de voz!").ConfigureAwait(false); return; } if (guildConnection == null) { await context.RespondAsync($"{context.User.Username}, eu não estou conectado a nenhum canal de voz!").ConfigureAwait(false); return; } if (BotClient.Playlist.Count == BotClient._currentTrackIndex + 1) { await context.RespondAsync($"Não posso pular para a próxima música! Pois estou tocando a música de número {BotClient._currentTrackIndex + 1} e a Playlist só tem {BotClient.Playlist.Count}"); } else { await guildConnection.PlayAsync(BotClient.Playlist[BotClient._currentTrackIndex + 1]).ConfigureAwait(false); await context.RespondAsync($"Ok {context.User.Username}! Vou pular para a próxima música!").ConfigureAwait(false); } } }
public async Task Shuffle(CommandContext ctx) { LavalinkNodeConnection node = ctx.Client.GetLavalink().ConnectedNodes.Values.First(); LavalinkGuildConnection conn = node.GetGuildConnection(ctx.Member.VoiceState?.Guild); if (ctx.Member.VoiceState == null || ctx.Member.VoiceState.Channel != conn.Channel) { await ctx.RespondAsync("We are not in one VC"); return; } if (conn == null) { await ctx.RespondAsync("Lavalink not connected"); return; } if (conn.CurrentState.CurrentTrack == null) { await ctx.RespondAsync("Nothing playing."); return; } Random random = new Random(); for (int index = LavalinkService.Instance.Queues[conn.Guild].Count; index > 0; index--) { int rngRes = random.Next(0, index); LavalinkTrack temp = LavalinkService.Instance.Queues[conn.Guild][0]; LavalinkService.Instance.Queues[conn.Guild][0] = LavalinkService.Instance.Queues[conn.Guild][rngRes]; LavalinkService.Instance.Queues[conn.Guild][rngRes] = temp; } await ctx.RespondAsync("Queue shuffled!"); }
public async Task Join(CommandContext ctx) { if (this.node?.IsConnected == false) { await ctx.RespondAsync($"{ctx.User.Mention} :x: Conexão com o lavalink falhou!"); return; } if (this.connection?.IsConnected == true) { await ctx.RespondAsync($"{ctx.User.Mention} :x: Estou no canal de voz: `{this.connection.Channel.Name}`."); return; } if (ctx.Member.VoiceState?.Channel == null) { await ctx.RespondAsync($"{ctx.User.Mention} :x: Você não está no canal de voz!"); return; } this.connection = await this.node.ConnectAsync(ctx.Member.VoiceState.Channel); if (this.connection?.IsConnected == false) { await ctx.RespondAsync($"{ctx.User.Mention} :x: Conexão com o canal de voz falhou."); return; } await ctx.RespondAsync($"{ctx.User.Mention} :white_check_mark: Conectado no canal de voz `{this.connection.Channel.Name}`"); }
public LavalinkPlayPartial(LavalinkGuildConnection lvl, LavalinkTrack track, TimeSpan start, TimeSpan stop) : base("play", lvl.GuildIdString) { this.Track = track.TrackString; this.StartTime = (long)start.TotalMilliseconds; this.StopTime = (long)stop.TotalMilliseconds; }
private async Task <bool> CheckVoiceAndChannel(CommandContext ctx, LavalinkGuildConnection lvc) { if (lvc == null) { await CTX.RespondSanitizedAsync(ctx, "Not connected in this guild."); return(false); } var chn = ctx.Member?.VoiceState?.Channel; if (chn == null) { await CTX.RespondSanitizedAsync(ctx, "You need to be in a voice channel."); return(false); } if (chn != lvc.Channel) { await CTX.RespondSanitizedAsync(ctx, "You need to be in the same voice channel."); return(false); } return(true); }
private async Task PlayNext(LavalinkGuildConnection conn, TrackFinishEventArgs args) { if (conn.CurrentState.CurrentTrack != null) { if (PrevQueueCount == 0) { conn.PlaybackFinished += PlayNext; } return; } var track = Queue.Dequeue(); await conn.PlayAsync(track); if (Queue.Count > 0) { conn.PlaybackFinished += PlayNext; } var builder = new DiscordEmbedBuilder() .WithTitle("Playing now:") .WithDescription($"[{track.Title}]({track.Uri.AbsoluteUri})"); var message = await SoundContext.RespondAsync(null, false, builder.Build()); }
private async Task Conn_PlaybackFinished(LavalinkGuildConnection sender, DSharpPlus.Lavalink.EventArgs.TrackFinishEventArgs e) { if (m_Queue.Count != 0) { var track = m_Queue.Dequeue(); await sender.PlayAsync(track.lavaTrack); await track.requestChannel.SendMessageAsync($"Playing {track.lavaTrack.Title}"); lastChannel = track.requestChannel; } else { if (lastChannel != null) { await lastChannel.SendMessageAsync("Queue end!"); } else { await sender.Guild.GetDefaultChannel().SendMessageAsync("Queue end!"); } isPaused = false; } }
public MusicPlayer(LavalinkNodeConnection node, DiscordGuild guild) { this._node = node; this.Guild = guild; this._connection = default; this._tracks = new List <TrackInfo>(); }
private async Task PlaybackFinished(LavalinkGuildConnection guildConnection, TrackFinishEventArgs e) { var trackFind = this.Playlist.FirstOrDefault(t => string.Equals(t.Key?.Title, e.Track.Title)); if (!(trackFind.Key is null && trackFind.Value is null)) { this.Playlist.Remove(trackFind.Key); } if (this.Playlist.Any()) { await this.LavalinkGuildConnection.PlayAsync(this.Playlist.Keys.FirstOrDefault()); } else { await trackFind.Value.RespondAsync("There are no more songs in the playlist, disconnecting me from the voice channel."); await this.LavalinkGuildConnection.DisconnectAsync(false); if (this._isPlaying) { this._isPlaying = false; } if (!this._isPaused) { this._isPaused = true; } if (!this._isStopped) { this._isStopped = true; } } }
private async Task TrackError(LavalinkGuildConnection guildConnection, TrackExceptionEventArgs e) { LavalinkTrack track = e.Track; var kv = this.Playlist.FirstOrDefault(kv => string.Equals(kv.Key.Title, track.Title)); CommandContext ctx = kv.Value; await ctx.RespondAsync($"{ctx.Member.Mention}, it was not possible to play the song `{track.Title}` by `{track.Author}`."); }
public async Task RepeatMode(CommandContext ctx) { if (ctx.Member.VoiceState == null || ctx.Member.VoiceState.Channel == null) { await ctx.RespondAsync("You are not in a vc."); return; } LavalinkNodeConnection node = ctx.Client.GetLavalink().ConnectedNodes.Values.First(); LavalinkGuildConnection conn = node.GetGuildConnection(ctx.Member.VoiceState.Guild); if (conn == null) { await ctx.RespondAsync("Lavalink not connected"); return; } if (conn.CurrentState.CurrentTrack == null) { await ctx.RespondAsync("Nothing playing"); return; } await ctx.TriggerTypingAsync(); Repeaters? current = LavalinkService.Instance.Repeats?[ctx.Guild]; DiscordMessageBuilder builder = new DiscordMessageBuilder { Content = "" }; builder.AddComponents(new List <DiscordButtonComponent> { new DiscordButtonComponent(ButtonStyle.Success, "off", "off", current == Repeaters.off, new DiscordComponentEmoji("🚫")), new DiscordButtonComponent(ButtonStyle.Success, "all", "all", current == Repeaters.all, new DiscordComponentEmoji("🔁")), new DiscordButtonComponent(ButtonStyle.Success, "single", "single", current == Repeaters.single, new DiscordComponentEmoji("🔂")) }); var message = await ctx.RespondAsync(builder); InteractivityExtension interactivity = ctx.Client.GetInteractivity(); var result = await interactivity.WaitForButtonAsync(message, ctx.User, TimeSpan.FromMinutes(1)); var repeatMode = result.Result.Id switch { string a when a.ToLower().Contains("all") => Repeaters.all, string b when b.ToLower().Contains("single") => Repeaters.single, string b when b.ToLower().Contains("off") => Repeaters.off, _ => Repeaters.all, }; LavalinkService.Instance.Repeats?.Remove(ctx.Guild); LavalinkService.Instance.Repeats.Add(ctx.Guild, repeatMode); await ctx.RespondAsync($"Repeatmode set to: {LavalinkService.Instance.Repeats[ctx.Guild]}"); }
public async Task Play(CommandContext ctx, [Description("URI to the audio to play.")] string song, [Description("Source to search from. {Youtube, SoundCloud}")] string source = "Youtube") { LavalinkNodeConnection lavalinkNodeConnection = await Connections.GetNodeConnection(ctx); LavalinkTrack track = null; if (Uri.TryCreate(song, UriKind.Absolute, out Uri uri)) { LavalinkLoadResult results = await lavalinkNodeConnection.Rest.GetTracksAsync(uri); if (results.Exception.Message != null) { throw new Exception(results.Exception.Message); } IEnumerable <LavalinkTrack> tracks = results.Tracks; if (tracks.Count() == 0) { throw new InvalidOperationException($"Could not find `{uri.OriginalString}`."); } track = tracks.First(); } else { if (Enum.TryParse(source, true, out LavalinkSearchType lavalinkSearchType)) { IEnumerable <LavalinkTrack> tracks = lavalinkNodeConnection.Rest.GetTracksAsync(song, lavalinkSearchType).GetAwaiter().GetResult().Tracks; if (tracks.Count() == 0) { throw new InvalidOperationException($"There were 0 results for `{song}`."); } track = tracks.First(); } else { throw new InvalidOperationException($"`{source}` is not a valid source."); } } LavalinkGuildConnection lavalinkGuildConnection = lavalinkNodeConnection.GetGuildConnection(ctx.Guild); Messaging messaging = new Messaging(ctx); if (lavalinkGuildConnection.CurrentState.CurrentTrack == null) { await lavalinkGuildConnection.PlayAsync(track); if (loops[ctx.Guild.Id]) { queues[ctx.Guild.Id].Enqueue(track); } await messaging.RespondContent(true, track.Length)($"🎤 {track.Author} - {track.Title}"); } else { queues[ctx.Guild.Id].Enqueue(track); await messaging.RespondContent()("Added to the queue."); } }
public MusicPlayer(CommandContext ctx, BotContext context) { _ctx = ctx; Queue = new Queue <LavalinkTrack>(); _context = context; Tracks = new List <LavalinkTrack>(); Lava = _ctx.Client.GetLavalink(); Node = Lava.ConnectedNodes.Values.First(); Connection = Node.GetGuildConnection(_ctx.Member.VoiceState.Guild); }
public async Task Resume(CommandContext ctx) { LavalinkNodeConnection lavalinkNodeConnection = await Connections.GetNodeConnection(ctx); LavalinkGuildConnection lavalinkGuildConnection = lavalinkNodeConnection.GetGuildConnection(ctx.Guild); await lavalinkGuildConnection.ResumeAsync(); Messaging messaging = new Messaging(ctx); await messaging.RespondContent()("▶️ Resumed."); }
private void CreatePlayer() { if (node is null || node.ConnectedGuilds.Count == 0) { throw new NodeNotConnectedException("There is a problem with your Lavalink connection!"); } Player = node.GetGuildConnection(helper.DiscordGuild); Player.PlaybackFinished += Player_PlaybackFinished; }
private async Task LavalinkVoice_PlaybackFinished(LavalinkGuildConnection ll, TrackFinishEventArgs e) { if (this.ContextChannel == null) { return; } await this.ContextChannel.SendMessageAsync($"Playback of {Formatter.Bold(Formatter.Sanitize(e.Track.Title))} by {Formatter.Bold(Formatter.Sanitize(e.Track.Author))} finished.").ConfigureAwait(false); this.ContextChannel = null; }
public async Task Skip(CommandContext ctx) { LavalinkNodeConnection lavalinkNodeConnection = await Connections.GetNodeConnection(ctx); LavalinkGuildConnection lavalinkGuildConnection = lavalinkNodeConnection.GetGuildConnection(ctx.Guild); LavalinkPlayerState currentState = lavalinkGuildConnection.CurrentState; if (currentState != null) { await SkipSong(ctx, lavalinkNodeConnection, lavalinkGuildConnection); } }
public async Task Stop(CommandContext ctx) { LavalinkNodeConnection lavalinkNodeConnection = await Connections.GetNodeConnection(ctx); LavalinkGuildConnection lavalinkGuildConnection = lavalinkNodeConnection.GetGuildConnection(ctx.Guild); queues[ctx.Guild.Id].Clear(); loops[ctx.Guild.Id] = false; await lavalinkGuildConnection.StopAsync(); Messaging messaging = new Messaging(ctx); await messaging.RespondContent()("⏹️ Queue has been emptied and looping has been turned off."); }
private async Task LavalinkErrorHandler(LavalinkGuildConnection con, TrackExceptionEventArgs e) { if (e.Player?.Guild == null) { return; } if (!this.data.TryGetValue(e.Player.Guild.Id, out GuildMusicPlayer? gd)) { return; } if (gd.CommandChannel is { })
private async Task Lavalink_TrackExceptionThrown(LavalinkGuildConnection con, TrackExceptionEventArgs e) { if (e.Player?.Guild == null) { return; } if (!this.MusicData.TryGetValue(e.Player.Guild.Id, out var gmd)) { return; } await gmd.CommandChannel.SendMessageAsync($"{DiscordEmoji.FromName(this.Discord, ":msfrown:")} A problem occured while playing {Formatter.Bold(Formatter.Sanitize(e.Track.Title))} by {Formatter.Bold(Formatter.Sanitize(e.Track.Author))}:\n{e.Error}"); }
/// <summary> /// Destroys the player /// </summary> /// <returns>The completed task</returns> public async Task DestroyPlayerAsync() { if (Player == null) { await Task.CompletedTask; } if (Player.IsConnected) { await Player.DisconnectAsync(); } Player = null; await Task.CompletedTask; }
public async Task Join(CommandContext ctx, [Description("The channel to add B-118 to.")] DiscordChannel channel = null) { LavalinkNodeConnection lavalinkNodeConnection = await Connections.GetNodeConnection(ctx, true); LavalinkGuildConnection lavalinkGuildConnection = await Connections.GetGuildConnection(ctx, channel, lavalinkNodeConnection); queues.TryAdd(ctx.Guild.Id, new Queue()); loops.TryAdd(ctx.Guild.Id, false); await lavalinkGuildConnection.SetVolumeAsync(25); lavalinkGuildConnection.PlaybackFinished += PlayNextSong(ctx, lavalinkNodeConnection, lavalinkGuildConnection); Messaging messaging = new Messaging(ctx); await messaging.RespondContent()($"Joining {lavalinkGuildConnection.Channel.Name}"); }
/// <summary> /// Destroys a player for this guild. /// </summary> /// <returns></returns> public async Task DestroyPlayerAsync() { if (this.Player == null) { return; } if (this.Player.IsConnected) { await this.Player.DisconnectAsync(); } this.Player = null; }
public async Task Board(CommandContext ctx, [Description("The sound to play.")] string sound, [Description("The volume to play the sound at.")] int?volume = null, [Description("The volume to set after the sound plays.")] int?postVolume = null) { LavalinkNodeConnection lavalinkNodeConnection = await Connections.GetNodeConnection(ctx); FileInfo clip = Program.GetB118SoundClip().LoadClip(sound); if (Program.GetB118SoundClip().Verify(clip)) { LavalinkTrack track = lavalinkNodeConnection.Rest.GetTracksAsync(clip).GetAwaiter().GetResult().Tracks.First(); LavalinkGuildConnection lavalinkGuildConnection = lavalinkNodeConnection.GetGuildConnection(ctx.Guild); if (volume.HasValue && volume >= 0 && volume <= 200) { await lavalinkGuildConnection.SetVolumeAsync(volume.Value); } if (lavalinkGuildConnection.CurrentState.CurrentTrack == null) { await lavalinkGuildConnection.PlayAsync(track); TimeSpan length = track.Length; await Task.Delay(length).ContinueWith(async(_) => { if (postVolume.HasValue && postVolume >= 0 && postVolume <= 200) { await lavalinkGuildConnection.SetVolumeAsync(postVolume.Value); } }); await ctx.Message.DeleteAsync(); } else { LavalinkTrack previousTrack = lavalinkGuildConnection.CurrentState.CurrentTrack; TimeSpan position = lavalinkGuildConnection.CurrentState.PlaybackPosition; await lavalinkGuildConnection.PlayAsync(track); TimeSpan length = track.Length; await Task.Delay(length).ContinueWith(async(_) => { if (postVolume.HasValue && postVolume >= 0 && postVolume <= 200) { await lavalinkGuildConnection.SetVolumeAsync(postVolume.Value); } await lavalinkGuildConnection.PlayPartialAsync(previousTrack, position, previousTrack.Length); }); await ctx.Message.DeleteAsync(); } } }
/// <summary> /// Destroys a player for this guild. /// </summary> /// <returns></returns> public Task DestroyPlayerAsync() { if (this.Player == null) { return(Task.CompletedTask); } if (this.Player.IsConnected) { this.Player.Disconnect(); } this.Player = null; return(Task.CompletedTask); }
public async Task Volume(CommandContext ctx, [Description("The volume to set it to. Min. 0, Max. 200.")] int volume) { if (volume < 0 || volume > 200) { throw new InvalidOperationException($"Volume `{volume}` is not between 0 and 200."); } LavalinkNodeConnection lavalinkNodeConnection = await Connections.GetNodeConnection(ctx); LavalinkGuildConnection lavalinkGuildConnection = lavalinkNodeConnection.GetGuildConnection(ctx.Guild); await lavalinkGuildConnection.SetVolumeAsync(volume); Messaging messaging = new Messaging(ctx); string emoji = volume < 25 ? "🔈" : volume < 75 ? "🔉" : "🔊"; await messaging.RespondContent()($"{emoji} Set the volume to {volume}%"); }