Exemplo n.º 1
0
        public async Task Play(CommandContext ctx, [RemainingText] string search)
        {
            if (ctx.Member.VoiceState == null || ctx.Member.VoiceState.Channel == null)
            {
                await ctx.RespondAsync("You must be in a voice channel!");

                return;
            }

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


            if (conn == null)
            {
                await Join(ctx);
            }
            conn = node.GetGuildConnection(ctx.Guild);
            var loadResult = new LavalinkLoadResult();

            if (search.StartsWith("D:/"))
            {
                loadResult = await Lavalink.Rest.GetTracksAsync(new Uri(search, UriKind.Relative));
            }
            else if (search.StartsWith("https:"))
            {
                loadResult = await Lavalink.Rest.GetTracksAsync(new Uri(search, UriKind.Absolute));
            }
            else
            {
                loadResult = await Lavalink.Rest.GetTracksAsync(search);
            }

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

                if (conn.CurrentState.CurrentTrack == null)
                {
                    await Leave(ctx);
                }
                return;
            }

            var result = loadResult.Tracks.First();

            if (queues.ContainsKey(ctx.Guild.Id))
            {
                if (queues[ctx.Guild.Id].IsEmpty && conn.CurrentState.CurrentTrack == null)
                {
                    await conn.PlayAsync(result);
                }
                else
                {
                    queues[ctx.Guild.Id].Enqueue(result);
                    if (!result.Identifier.StartsWith("D:/"))
                    {
                        await ctx.RespondAsync(
                            $"A track was already playing, the requested track ({result.Title}, `{"https://youtu.be/" + result.Uri.ToString()[^11..]}`) has been added to the queue!");
Exemplo n.º 2
0
        public async Task PlayAsync(CommandContext ctx,
                                    [Description("desc-audio-url")] Uri uri)
        {
            LavalinkLoadResult tlr = await this.Service.GetTracksAsync(uri);

            await this.InternalPlayAsync(ctx, tlr);
        }
        /// <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);
                    }
                }
            }
        }
Exemplo n.º 4
0
        public async Task PlayFileAsync(CommandContext ctx,
                                        [RemainingText, Description("desc-audio-url")] string path)
        {
            var fi = new FileInfo(path);
            LavalinkLoadResult tlr = await this.Service.GetTracksAsync(fi);

            await this.InternalPlayAsync(ctx, tlr);
        }
Exemplo n.º 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.");
            }
        }
Exemplo n.º 6
0
        public async Task CreateFixed(CommandContext ctx, [RemainingText] string name)
        {
            var inter = ctx.Client.GetInteractivity();
            var pls   = await PlaylistDB.GetPlaylistsSimple(ctx.Member.Id);

            if (pls.Any(x => x == name))
            {
                await ctx.RespondAsync(embed : new DiscordEmbedBuilder().WithTitle("Create Fixed Playlist").WithDescription("**Error** You already have a playlist with that name!").Build());

                return;
            }
            var msg = await ctx.RespondAsync(embed : new DiscordEmbedBuilder().WithTitle("Create Fixed Playlist").WithDescription("Please send the playlist URL now!\n" +
                                                                                                                                  "> Just the link, no bot prefix needed!").Build());

            var gets = await inter.WaitForMessageAsync(x => x.Author == ctx.Member, TimeSpan.FromSeconds(30));

            await msg.DeleteAsync();

            LavalinkLoadResult s = null;

            try
            {
                s = await Bot.LLEU[ctx.Client.ShardId].GetTracksAsync(new Uri(gets.Result.Content));
            }
            catch
            {
                await ctx.RespondAsync(embed : new DiscordEmbedBuilder().WithTitle("Create Fixed Playlist").WithDescription("**Error** Reasons could be:\n" +
                                                                                                                            "> The provided link was not a playlist\n" +
                                                                                                                            "> The playlist is unavailable (for example set to private)").Build());

                return;
            }
            if (s.LoadResultType != DSharpPlus.Lavalink.LavalinkLoadResultType.PlaylistLoaded)
            {
                await ctx.RespondAsync(embed : new DiscordEmbedBuilder().WithTitle("Create Fixed Playlist").WithDescription("**Error** Reasons could be:\n" +
                                                                                                                            "> The provided link was not a playlist\n" +
                                                                                                                            "> The playlist is unavailable (for example set to private)").Build());

                return;
            }
            if (gets.Result.Content.Contains("youtu") && !gets.Result.Content.Contains("soundcloud"))
            {
                await PlaylistDB.AddPlaylist(name, ctx.Member.Id, ExtService.Youtube, gets.Result.Content);
            }
            else
            {
                await PlaylistDB.AddPlaylist(name, ctx.Member.Id, ExtService.Soundcloud, gets.Result.Content);
            }
            await ctx.RespondAsync(embed : new DiscordEmbedBuilder().WithTitle("Create Fixed Playlist").WithDescription($"Fixed playlist created with name -> {name} and {s.Tracks.Count()} Songs!").Build());
        }
Exemplo n.º 7
0
        private async Task InternalPlayAsync(CommandContext ctx, LavalinkLoadResult tlr)
        {
            IEnumerable <LavalinkTrack> tracks = tlr.Tracks;

            if (tlr.LoadResultType == LavalinkLoadResultType.LoadFailed || !tracks.Any() || this.Player is null)
            {
                throw new CommandFailedException(ctx, "cmd-err-music-none");
            }

            if (this.Player.IsShuffled)
            {
                tracks = this.Service.Shuffle(tracks);
            }

            int trackCount = tracks.Count();

            foreach (LavalinkTrack track in tracks)
            {
                this.Player.Enqueue(new Song(track, ctx.Member));
            }

            DiscordChannel?chn = ctx.Member.VoiceState?.Channel ?? ctx.Guild.CurrentMember.VoiceState?.Channel;

            if (chn is null)
            {
                throw new CommandFailedException(ctx, "cmd-err-music-vc");
            }

            await this.Player.CreatePlayerAsync(chn);

            await this.Player.PlayAsync();

            if (trackCount > 1)
            {
                await ctx.ImpInfoAsync(this.ModuleColor, Emojis.Headphones, "fmt-music-add-many", trackCount);
            }
            else
            {
                LavalinkTrack track = tracks.First();
                await ctx.RespondWithLocalizedEmbedAsync(emb => {
                    emb.WithColor(this.ModuleColor);
                    emb.WithLocalizedTitle("fmt-music-add", Emojis.Headphones);
                    emb.WithDescription(Formatter.Bold(Formatter.Sanitize(track.Title)));
                    emb.AddLocalizedTitleField("str-author", track.Author, inline: true);
                    emb.AddLocalizedTitleField("str-duration", track.Length.ToDurationString(), inline: true);
                    emb.WithUrl(track.Uri);
                });
            }
        }
Exemplo n.º 8
0
        public async Task Play(CommandContext ctx, LavalinkLoadResult results)
        {
            var audio = results.Tracks.FirstOrDefault();

            if (results.LoadResultType == LavalinkLoadResultType.LoadFailed || audio is null)
            {
                await ctx.RespondAsync(":mag: No tracks were found at specified link.").ConfigureAwait(false);

                return;
            }

            Player.Enqueue(new MusicData(audio, ctx.Member));
            await Player.CreatePlayerAsync(ctx.Member.VoiceState.Channel);

            await Player.PlayAsync();

            await ctx.RespondAsync(
                $":play_pause: Now playing: {Formatter.Bold(Formatter.Sanitize(audio.Title))} by {Formatter.Bold(Formatter.Sanitize(audio.Author))}.")
            .ConfigureAwait(false);
        }
Exemplo n.º 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);
                }
            }
        }
Exemplo n.º 10
0
        public async Task PlayAsync(CommandContext ctx, string searchQuery)
        {
            if (this._isPaused && !this._isStopped)
            {
                await this.LavalinkGuildConnection.ResumeAsync();

                return;
            }

            DiscordChannel commandChannel       = ctx.Channel;
            DiscordMember  memberCommand        = ctx.Member;
            string         memberCommandMention = memberCommand.Mention;

            this.LavalinkGuildConnection = this._lavalinkNodeConnection.GetGuildConnection(ctx.Guild);
            if (this.LavalinkGuildConnection?.IsConnected != true)
            {
                DiscordChannel memberVoiceChannel = ctx.Member.VoiceState?.Channel;
                if (memberVoiceChannel is null)
                {
                    await commandChannel.SendMessageAsync($"{memberCommandMention}, join a voice channel!!");

                    return;
                }

                this.LavalinkGuildConnection = await this._lavalinkNodeConnection.ConnectAsync(memberVoiceChannel);

                await this.LavalinkGuildConnection.SetVolumeAsync(50);

                this.LavalinkGuildConnection.PlaybackFinished += this.PlaybackFinished;
                this.LavalinkGuildConnection.PlaybackStarted  += this.PlaybackStarted;
                this.LavalinkGuildConnection.TrackException   += this.TrackError;
                this.LavalinkGuildConnection.TrackStuck       += this.TrackStuck;
            }

            LavalinkLoadResult resultTracks = !Uri.TryCreate(searchQuery, UriKind.Absolute, out Uri resultUri) ?
                                              await this.LavalinkGuildConnection.GetTracksAsync(searchQuery) :
                                              await this.LavalinkGuildConnection.GetTracksAsync(resultUri);

            if (this.Playlist is null)
            {
                this.Playlist = new Dictionary <LavalinkTrack, CommandContext>();
            }

            switch (resultTracks.LoadResultType)
            {
            case LavalinkLoadResultType.TrackLoaded:
            case LavalinkLoadResultType.SearchResult:
            {
                var trackResult = resultTracks.Tracks.FirstOrDefault();
                this.Playlist.Add(trackResult, ctx);

                if (this._isPlaying)
                {
                    await commandChannel.SendMessageAsync($"{memberCommandMention}, `{trackResult.Author}'s` - `{trackResult.Title}` song was successfully added to the playlist.");

                    return;
                }

                break;
            }

            case LavalinkLoadResultType.PlaylistLoaded:
            {
                IEnumerable <LavalinkTrack> listOfTracks = resultTracks.Tracks;
                foreach (LavalinkTrack trackForeach in listOfTracks)
                {
                    this.Playlist.Add(trackForeach, ctx);
                }

                if (this._isPlaying)
                {
                    await commandChannel.SendMessageAsync($"{memberCommandMention}, `{listOfTracks.Count()}` songs have been successfully added to the playlist.");

                    return;
                }

                break;
            }

            case LavalinkLoadResultType.NoMatches:
            {
                await commandChannel.SendMessageAsync($"{memberCommandMention}, no songs were found, please search again later.");

                return;
            }

            case LavalinkLoadResultType.LoadFailed:
            {
                if (this._reconnections == 3)
                {
                    await commandChannel.SendMessageAsync($"{memberCommandMention}, an error occurred while trying to load this song, please try again.");

                    return;
                }

                ++this._reconnections;

                await this.PlayAsync(ctx, searchQuery);

                return;
            }
            }

            LavalinkTrack track = this.Playlist.Keys.FirstOrDefault();

            await this.LavalinkGuildConnection.PlayAsync(track);

            this._isPlaying = true;
        }
Exemplo n.º 11
0
        public async Task EnqueueTrack(CommandContext ctx, [RemainingText] string input)
        {
            _Cmdctx = ctx;

            if (ctx.Member?.VoiceState?.Channel == null)
            {
                await ctx.RespondAsync("You must be connected to a voice channel to use this command.");

                return;
            }

            var lavaconfig = new LavalinkConfiguration
            {
                Password = ""
            };

            if (_LavalinkNode == null || !_LavalinkNode.IsConnected)
            {
                _LavalinkNode = await _Lavalink.ConnectAsync(lavaconfig);
            }

            if ((_LavalinkGuild == null || !_LavalinkGuild.IsConnected))
            {
                _LavalinkGuild = await _LavalinkNode.ConnectAsync(ctx.Member.VoiceState.Channel);

                _LavalinkGuild.PlaybackFinished += PlayTrack;
            }

            var tracks = new LavalinkLoadResult();

            Uri uri;

            if (Uri.TryCreate(input, UriKind.Absolute, out uri))
            {
                tracks = await _LavalinkNode.GetTracksAsync(uri);
            }
            else
            {
                tracks = await _LavalinkNode.GetTracksAsync(input);
            }

            switch (tracks.LoadResultType)
            {
            case LavalinkLoadResultType.SearchResult:

            case LavalinkLoadResultType.TrackLoaded:
                _Playlist.Enqueue(tracks.Tracks.First());
                await ctx.RespondAsync($"**[Enqueued]** {tracks.Tracks.First().Title}");

                break;

            case LavalinkLoadResultType.PlaylistLoaded:
                foreach (LavalinkTrack track in tracks.Tracks)
                {
                    _Playlist.Enqueue(track);
                }
                await ctx.RespondAsync($"Playlist Loaded.");

                break;

            case LavalinkLoadResultType.LoadFailed:
                await ctx.RespondAsync($"Track could not be loaded.");

                break;

            case LavalinkLoadResultType.NoMatches:
                await ctx.RespondAsync($"Track Not Found.");

                break;

            default:
                await ctx.RespondAsync($"Error.");

                return;
            }

            if (string.IsNullOrEmpty(_LavalinkGuild.CurrentState.CurrentTrack.Title))
            {
                _LavalinkGuild.Play(_Playlist.Peek());
            }
        }
Exemplo n.º 12
0
        public async Task PlayAsync(CommandContext ctx,
                                    [Description("Termo de pesquisa ou link para tocar.")]
                                    [RemainingText] string pesquisa = null)
        {
            if (pesquisa == null)
            {
                await ctx.RespondAsync($"{ctx.User.Mention} **|** Você precisa fornecer uma url ou termo para eu pesquisar no Youtube e depois tocar a música desejada.");

                return;
            }

            MusicPlayer player = await _music.GetOrCreatePlayerAsync(ctx.Guild, ctx.Channel);

            LavalinkLoadResult result = null;

            if (Uri.IsWellFormedUriString(pesquisa, UriKind.Absolute))
            {
                result = await _music.Node.GetTracksAsync(new Uri(pesquisa));
            }
            else
            {
                result = await _music.Node.GetTracksAsync(pesquisa);
            }

            switch (result.LoadResultType)
            {
            case LavalinkLoadResultType.LoadFailed:
                await ctx.RespondAsync($"{ctx.User.Mention} **|** Houve um problema ao carregar a música selecionada!");

                return;

            case LavalinkLoadResultType.NoMatches:
                await ctx.RespondAsync($"{ctx.User.Mention} **|** Nenhum resultado com a pesquisa ou link foi encontrado!");

                return;

            case LavalinkLoadResultType.PlaylistLoaded: {
                int indice = 0;

                lock (player.Queue)
                    indice = player.Queue.Count;

                var str   = "";
                var pages = new List <Page>();

                foreach (var track in result.Tracks)
                {
                    if (str.Length >= 1500)
                    {
                        pages.Add(new Page {
                                Content = ctx.User.Mention,
                                Embed   = new DiscordEmbedBuilder()
                                          .WithTitle($"{ctx.User.Mention} **|** Músicas adicionadas na Playlist.")
                                          .WithDescription(str)
                                          .WithFooter($"Comando requisitado pelo: " + ctx.Member.Username, iconUrl: ctx.User.AvatarUrl)
                                          .WithColor(DiscordColor.Orange)
                            });

                        str = "";
                    }
                    else
                    {
                        str += $"**`{string.Format("{0:00}", indice++)}`**: {Formatter.MaskedUrl(Formatter.Sanitize(track.Title), track.Uri)} (`{MusicPlayer.FormatTimespan(track.Length)}`)\n";
                    }

                    var qresult = player.Enqueue(new MusicItem(track, ctx.Member, ctx.Channel));
                    if (qresult == MusicOperationResult.QueueFull)
                    {
                        await ctx.RespondAsync($"{ctx.User.Mention} **|** A fila encheu e nem todas as músicas foram adicionadas! :/");
                        await PrepareAsync();

                        player.Play();

                        await ctx.Client.GetInteractivity()
                        .SendPaginatedMessage(ctx.Channel, ctx.User, pages);

                        return;
                    }
                }

                if (!string.IsNullOrEmpty(str))
                {
                    pages.Add(new Page {
                            Content = ctx.User.Mention,
                            Embed   = new DiscordEmbedBuilder()
                                      .WithTitle($"{ctx.User.Mention} **|** Músicas adicionadas na Playlist.")
                                      .WithDescription(str)
                                      .WithFooter($"Comando requisitado pelo: " + ctx.Member.Username, iconUrl: ctx.User.AvatarUrl)
                                      .WithColor(DiscordColor.Orange)
                        });
                }

                await PrepareAsync();

                player.Play();

                await ctx.Client.GetInteractivity()
                .SendPaginatedMessage(ctx.Channel, ctx.User, pages);
            }
                return;

            case LavalinkLoadResultType.SearchResult:
            case LavalinkLoadResultType.TrackLoaded: {
                var track = result.Tracks
                            .FirstOrDefault();

                await ctx.RespondAsync($"{ctx.User.Mention} **|** A música: **{Formatter.Sanitize(track.Title)}** " +
                                       $"por: **{Formatter.Sanitize(track.Author)}** foi adicionada a playlist.");

                Console.ForegroundColor = ConsoleColor.White;
                Console.WriteLine($"[{DateTime.Now.Year}-{DateTime.Now.Month}-{DateTime.Now.Day} {DateTime.Now.Hour}:{DateTime.Now.Minute}:{DateTime.Now.Second} -03:00] [Lavalink] A música: \"{Formatter.Sanitize(track.Title)}\" " +
                                  $"por: \"{Formatter.Sanitize(track.Author)}\" foi adicionada a playlist.");
                Console.ResetColor();

                await PrepareAsync();

                player.Enqueue(new MusicItem(track, ctx.Member, ctx.Channel));
                player.Play();
            }
                return;
            }

            async Task PrepareAsync()
            {
                var vs  = ctx.Member.VoiceState;
                var chn = vs.Channel;
                await player.CreatePlayerAsync(chn);
            }
        }
Exemplo n.º 13
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();
        }
Exemplo n.º 14
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).");
        }