Example #1
0
        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();
                }
            }
        }
Example #2
0
        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);
                }
            }
        }
Example #3
0
        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;
            }
        }
Example #4
0
        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());
        }
Example #5
0
        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.");
            }
        }
        /// <summary>
        /// Executa quando uma música acaba ou quando um usuário utiliza o comando !proxima.
        /// </summary>
        /// <param name="TrackFinishEventArgs"></param>
        /// <returns></returns>
        private static async Task Lavalink_PlaybackFinished(EventArgs TrackFinishEventArgs)
        {
            LavalinkGuildConnection guildConnection = LavalinkNode.GetGuildConnection(await Lavalink.Client.GetGuildAsync(configJson.ServerId).ConfigureAwait(false));

            _currentTrackIndex++;
            if (_currentTrackIndex + 1 > Playlist.Count)
            {
                Playlist.Clear();
                await guildConnection.Guild.GetChannel(configJson.ComandosBotCanalId).SendMessageAsync($"A playlist está vazia! Adicionando novas músicas!");
                await AddSongs(5);

                if (Playlist.Count > 0)
                {
                    _currentTrackIndex = 0;
                    IsSongPlaying      = true;
                    await guildConnection.PlayAsync(Playlist.ElementAt(_currentTrackIndex)).ConfigureAwait(false);
                }
            }
            else
            {
                await guildConnection.PlayAsync(Playlist.ElementAt(_currentTrackIndex)).ConfigureAwait(false);
            }
        }
Example #7
0
        public async Task PlayNextSongIfExists(CommandContext ctx, LavalinkNodeConnection lavalinkNodeConnection, LavalinkGuildConnection lavalinkGuildConnection, Uri uri)
        {
            Messaging messaging = new Messaging(ctx);

            if (queues[ctx.Guild.Id].Count > 0)
            {
                LavalinkTrack track = (LavalinkTrack)queues[ctx.Guild.Id].Dequeue();
                await lavalinkGuildConnection.PlayAsync(track);

                await messaging.RespondContent(false, track.Length)($"🎤 {track.Author} - {track.Title}");

                if (loops[ctx.Guild.Id] && uri != null)
                {
                    LavalinkTrack newTrack = lavalinkNodeConnection.Rest.GetTracksAsync(uri).GetAwaiter().GetResult().Tracks.First();
                    queues[ctx.Guild.Id].Enqueue(newTrack);
                }
            }
            else
            {
                await messaging.RespondContent()("Queue has finished.");
            }
        }
Example #8
0
        private async Task SkipSong(DiscordGuild guild, DiscordChannel channel,
                                    LavalinkGuildConnection lvc, bool fromVoteSkip = false)
        {
            string title = ShimakazeBot.playlists[guild].songRequests[0].track.Title;

            ShimakazeBot.playlists[guild].songRequests.RemoveAt(0);
            bool wasLooping = false;

            if (ShimakazeBot.playlists[guild].loopCount > 0)
            {
                wasLooping = true;
                ShimakazeBot.playlists[guild].loopCount = 0;
            }

            if (ShimakazeBot.playlists[guild].songRequests.Count > 0)
            {
                await lvc.PlayAsync(ShimakazeBot.playlists[guild].songRequests.First().track);

                await CTX.SendSanitizedMessageAsync(channel,
                                                    $"Skipped *{title}*{(wasLooping ? " and stopped loop" : "")}." +
                                                    (fromVoteSkip ?
                                                     $"\nSkip requested by **{ShimakazeBot.playlists[guild].voteSkip.requester.DisplayName}**" :
                                                     ""));
            }
            else
            {
                await lvc.StopAsync();

                await CTX.SendSanitizedMessageAsync(channel, $"Playlist ended with skip. (Skipped *{title}*" +
                                                    $"{(wasLooping ? " and stopped loop" : "")})" +
                                                    (fromVoteSkip ?
                                                     $"\nSkip requested by **{ShimakazeBot.playlists[guild].voteSkip.requester.DisplayName}**" :
                                                     ""));
            }

            ShimakazeBot.playlists[guild].voteSkip = null;
        }
Example #9
0
        public async Task Tocar(CommandContext context, [Description("Pesquisa que o bot fará no site externo.")][RemainingText] string searchQuery)
        {
            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($"ERR0! Lavalink não está conectado!").ConfigureAwait(false);

                    return;
                }

                YoutubeSearchEngine         youtubeSearchEngine = new YoutubeSearchEngine(1);
                Dictionary <string, string> searchResult        = youtubeSearchEngine.SearchVideos(searchQuery);
                if (searchResult.Count == 0)
                {
                    await context.RespondAsync($"ERR0! Pesquisa por {searchQuery} falhou! Não consegui encontrar nenhum vídeo no YouTube!").ConfigureAwait(false);

                    return;
                }
                string videoTitle = searchResult.ElementAt(0).Key.ToString();

                LavalinkLoadResult loadResult = await BotClient.LavalinkNode.Rest.GetTracksAsync(videoTitle).ConfigureAwait(false);

                if (loadResult.LoadResultType == LavalinkLoadResultType.LoadFailed || loadResult.LoadResultType == LavalinkLoadResultType.NoMatches)
                {
                    await context.RespondAsync($"ERR0! Pesquisa por {searchQuery} falhou! Tipo do resultado: {loadResult.LoadResultType}").ConfigureAwait(false);
                }

                LavalinkTrack track = loadResult.Tracks.First();
                if (track.Length >= new TimeSpan(0, BotClient.configJson.TrackMaxLengthInMinutes, 0))
                {
                    await context.RespondAsync($"Duração da Música {track.Title} é maior que o maximo permitido(valor configurável)! Ignorando esta música...");

                    await context.RespondAsync($"Duração: {track.Length.Hours}:{track.Length.Minutes}:{track.Length.Seconds}.");

                    return;
                }

                if (BotClient.Playlist.Count == 0)
                {
                    BotClient.Playlist.Add(track);
                    await guildConnection.SetVolumeAsync(50).ConfigureAwait(false);

                    await guildConnection.PlayAsync(BotClient.Playlist[0]).ConfigureAwait(false);

                    await context.RespondAsync($"Tocando: {track.Title}! Volume: {50}%").ConfigureAwait(false);

                    BotClient.IsSongPlaying = true;
                }
                else
                {
                    BotClient.Playlist.Add(track);
                    await context.RespondAsync($"A música: {track.Title} foi adicionada à playlist de músicas para tocar!").ConfigureAwait(false);
                }
            }
        }
Example #10
0
        public async Task Play(CommandContext ctx, [Description("The search request")][RemainingText] string search)
        {
            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();
            await node.ConnectAsync(ctx.Member.VoiceState.Channel);

            LavalinkGuildConnection conn = node.GetGuildConnection(ctx.Member.VoiceState.Guild);

            if (conn == null)
            {
                await ctx.RespondAsync("Lavalink not connected.");

                return;
            }
            LavalinkLoadResult loadResult = await node.Rest.GetTracksAsync(search, LavalinkSearchType.Youtube);

            if (loadResult.LoadResultType == LavalinkLoadResultType.LoadFailed ||
                loadResult.LoadResultType == LavalinkLoadResultType.NoMatches)
            {
                await ctx.RespondAsync($"Track search failed for {search}");

                return;
            }
            DiscordEmbedBuilder resultsEmbed = new DiscordEmbedBuilder
            {
                Title       = "I found this for you on Youtube:",
                Description = "Respond with the number you would like to play!",
                Color       = DiscordColor.Red
            };
            int index = 0;

            foreach (LavalinkTrack result in loadResult.Tracks)
            {
                index++;
                resultsEmbed.AddField($"{index}:", $"[{result.Title}]({result.Uri})");
                if (index == 10)
                {
                    break;
                }
            }
            DiscordMessage selectOne = await ctx.RespondAsync(resultsEmbed.Build());

            InteractivityExtension interactivity = ctx.Client.GetInteractivity();
            var selection = await interactivity.WaitForMessageAsync(x => x.Channel == ctx.Channel && x.Author == ctx.User);

            LavalinkTrack track = loadResult.Tracks.ElementAt(int.Parse(selection.Result.Content) - 1);

            if (LavalinkService.Instance.Queues != null && LavalinkService.Instance.Queues.ContainsKey(ctx.Guild))
            {
                LavalinkService.Instance.Queues[ctx.Guild].Add(track);
                DiscordEmbedBuilder embedBuilder = new DiscordEmbedBuilder
                {
                    Title       = "Added to playlist:",
                    Description = $"[{track.Title}]({track.Uri})",
                    Color       = DiscordColor.Red
                };
                await ctx.RespondAsync(embedBuilder.Build());
            }
            else if (conn.CurrentState.CurrentTrack != null)
            {
                if (LavalinkService.Instance.Queues == null)
                {
                    LavalinkService.Instance.Queues  = new Dictionary <DiscordGuild, List <LavalinkTrack> >();
                    LavalinkService.Instance.Repeats = new Dictionary <DiscordGuild, Repeaters>
                    {
                        { ctx.Guild, Repeaters.off }
                    };
                }
                LavalinkService.Instance.Queues.Add(ctx.Guild, new List <LavalinkTrack> {
                    track
                });
                DiscordEmbedBuilder embedBuilder = new DiscordEmbedBuilder
                {
                    Title       = "Added to playlist:",
                    Description = $"[{track.Title}]({track.Uri})",
                    Color       = DiscordColor.Red
                };
                await ctx.RespondAsync(embedBuilder.Build());
            }
            else
            {
                await conn.PlayAsync(track);

                LavalinkService.Instance.Repeats = new Dictionary <DiscordGuild, Repeaters>
                {
                    { ctx.Guild, Repeaters.off }
                };
                DiscordEmbedBuilder embedBuilder = new DiscordEmbedBuilder
                {
                    Title       = "Now playing:",
                    Description = $"[{track.Title}]({track.Uri})",
                    Color       = DiscordColor.Red
                };
                await ctx.RespondAsync(embedBuilder.Build());
            }
            await selectOne.DeleteAsync();

            await selection.Result.DeleteAsync();
        }
Example #11
0
        public async Task Import(CommandContext ctx, [Description("Playlist URL")] Uri playlistURL)
        {
            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();
            await node.ConnectAsync(ctx.Member.VoiceState.Channel);

            LavalinkGuildConnection conn = node.GetGuildConnection(ctx.Member.VoiceState.Guild);

            if (conn == null)
            {
                await ctx.RespondAsync("Lavalink not connected.");

                return;
            }
            LavalinkLoadResult loadResult = await conn.GetTracksAsync(playlistURL);

            if (loadResult.LoadResultType == LavalinkLoadResultType.LoadFailed || loadResult.LoadResultType == LavalinkLoadResultType.NoMatches)
            {
                await ctx.RespondAsync($"Playlist search failed for {playlistURL}");

                return;
            }

            foreach (LavalinkTrack track in loadResult.Tracks)
            {
                if (LavalinkService.Instance.Queues != null && LavalinkService.Instance.Queues.ContainsKey(ctx.Guild))
                {
                    LavalinkService.Instance.Queues[ctx.Guild].Add(track);
                }
                else if (conn.CurrentState.CurrentTrack != null)
                {
                    LavalinkService.Instance.Queues = new Dictionary <DiscordGuild, List <LavalinkTrack> >
                    {
                        { ctx.Guild, new List <LavalinkTrack> {
                              track
                          } }
                    };
                    LavalinkService.Instance.Repeats = new Dictionary <DiscordGuild, Repeaters>
                    {
                        { ctx.Guild, Repeaters.off }
                    };
                }
                else
                {
                    await conn.PlayAsync(track);

                    DiscordEmbedBuilder embedBuilder = new DiscordEmbedBuilder
                    {
                        Title       = "Now playing:",
                        Description = $"[{track.Title}]({track.Uri})",
                        Color       = DiscordColor.Red
                    };
                    await ctx.RespondAsync(embedBuilder.Build());

                    await Task.Delay(1000);
                }
            }
            await ctx.RespondAsync("Done (i think).");
        }