Exemplo n.º 1
0
        public async Task Search([Remainder] string query)
        {
            await Context.Channel.TriggerTypingAsync();

            _logger.LogInformation("{username}#{discriminator} executed search ({query}) on {server}/{channel}",
                                   Context.User.Username, Context.User.Discriminator, query, Context.Guild?.Name ?? "DM", Context.Channel.Name);

            if (!CheckIfLavaLinkIsEnabled())
            {
                return;
            }

            var searchResponse = await _lavaNode.SearchYouTubeAsync(query);

            if (searchResponse.LoadStatus == LoadStatus.LoadFailed ||
                searchResponse.LoadStatus == LoadStatus.NoMatches)
            {
                await ReplyAsync($"I wasn't able to find anything for `{query}`.");

                return;
            }

            StringBuilder sb = new StringBuilder();

            foreach (var track in searchResponse.Tracks)
            {
                sb.AppendLine($"{track.Author} - {track.Title} ({track.Duration})");
            }

            await ReplyAsync(sb.ToString());
        }
Exemplo n.º 2
0
        public async Task Play([Remainder] string query)
        {
            var guild  = Context.Guild as IGuild;
            var player = _lavaNode.GetPlayer(guild);
            await player.UpdateVolumeAsync(10);

            var results = await _lavaNode.SearchYouTubeAsync(query);

            if (results.LoadStatus == LoadStatus.NoMatches || results.LoadStatus == LoadStatus.LoadFailed)
            {
                await ReplyAsync("No matches found.");
            }

            var track = results.Tracks.FirstOrDefault();

            if (player.PlayerState == PlayerState.Playing)
            {
                player.Queue.Enqueue(track);
                await ReplyAsync("Track added to queue.");
            }
            else
            {
                await player.PlayAsync(track);
                await ReplyAsync($"Now playing: {track.Title}");
            }
        }
Exemplo n.º 3
0
        public async Task <string> PlayTrack(string query, SocketUser user, SocketGuild guild, bool skipQueue)
        {
            if (!_lavaNode.HasPlayer(guild))
            {
                await ConnectToChannelAsync(user, guild);
            }
            var player = _lavaNode.GetPlayer(guild);

            var results = await _lavaNode.SearchYouTubeAsync(query);

            if (results.LoadStatus == LoadStatus.LoadFailed || results.LoadStatus == LoadStatus.NoMatches)
            {
                return("No matches found");
            }

            var track = results.Tracks.FirstOrDefault();

            string returnMessage = "";

            if (player.PlayerState == PlayerState.Playing && !skipQueue)
            {
                player.Queue.Enqueue(track);
                returnMessage = $"Track {track.Title} is queued";
            }
            else
            {
                await player.PlayAsync(track);

                returnMessage = $"Track {track.Title} is now playing";
            }

            using (var scope = _serviceScope.CreateScope()) {
                try {
                    var discordTrackService = scope.ServiceProvider.GetService <IDiscordTrackService>();

                    try {
                        await discordTrackService.AddTrackAsync(user, track.Url);
                    } catch (InvalidUrlException e) {
                        returnMessage = e.ToString();
                    } catch (DataContextException e) {
                        returnMessage = e.ToString();
                    }
                } catch (Exception e) {
                    Console.WriteLine(e);
                }
            }

            return(returnMessage);
        }
Exemplo n.º 4
0
        public async Task <string> PlayAsync(string query, IGuild guild)
        {
            _player = _lavaNode.GetPlayer(guild);
            var results = await _lavaNode.SearchYouTubeAsync(query);

            if (results.LoadType == LoadType.NoMatches || results.LoadType == LoadType.LoadFailed)
            {
                return("**No matches found.**");
            }

            var track = results.Tracks.FirstOrDefault();

            if (_player.PlayerState == PlayerState.Playing)
            {
                _player.Queue.Enqueue(track);
                return($"**{track.Title} has been added to the queue**");
            }
            else
            {
                await _player.PlayAsync(track);

                await _client.SetGameAsync(track.Title);

                return($":ok_hand::rofl:**Now playing {track.Title}**:rofl::ok_hand:");
            }
        }
Exemplo n.º 5
0
        public static async Task <List <LavaTrack> > SearchAndSelect(this LavaNode client, string query, Music interactive, int limit = 500)
        {
            List <LavaTrack> tracks;

            if (Uri.IsWellFormedUriString(query, UriKind.Absolute))
            {
                tracks = (await client.SearchAsync(query)).Tracks.Take(limit).ToList();
                return(tracks);
            }

            var res = await client.SearchYouTubeAsync(query);

            tracks = res.Tracks.Take(15).ToList();
            if (tracks.Count == 1)
            {
                return(tracks);
            }

            if (tracks.Count <= 0)
            {
                await interactive.ReplyAsync("*~ No Results ~*", Color.DarkRed.RawValue);

                return(null);
            }

            var player = interactive.GetPlayer();
            await player.PlayLocal("select");

            var track = await SelectTrack(tracks, interactive);

            return(track == null ? null : new List <LavaTrack>
            {
                track
            });
        }
Exemplo n.º 6
0
        public async Task <IXyloxServiceResult> PlayTrackAsync(string query, ulong id)
        {
            var search = await _lavaNode.SearchYouTubeAsync(query);

            var track = search.Tracks.FirstOrDefault();
            var guild = GetGuild(id);

            if (_lavaNode.TryGetPlayer(guild, out var player))
            {
                if (player.PlayerState is PlayerState.Playing)
                {
                    player.Queue.Enqueue(track);
                    return(ConvertTrackToXyloxTrack(track, true));
                }
                else
                {
                    await player.PlayAsync(track);

                    return(ConvertTrackToXyloxTrack(track, false));
                }
            }

            return(new XyloxServiceResult
            {
                Message = $"Player not available for {guild.Name}, use the join command first."
            });
        }
Exemplo n.º 7
0
        public async Task <KeyValuePair <LavaTrack, bool> > PlayAsync(string query, SocketGuild guild, string source = "youtube", SocketVoiceChannel voiceChannel = null, ITextChannel textChannel = null)
        {
            if (voiceChannel != null && textChannel != null && _lavaNode.TryGetPlayer(guild, out var player) == false)
            {
                ConnectAsync(voiceChannel, textChannel).Wait();
            }

            player = _lavaNode.GetPlayer(guild);
            SearchResponse res;

            switch (source)
            {
            case "youtube":
                res = await _lavaNode.SearchYouTubeAsync(query);

                break;

            case "soundcloud":
                res = await _lavaNode.SearchSoundCloudAsync(query);

                break;

            default:
                res = await _lavaNode.SearchYouTubeAsync(query);

                break;
            }

            var track = res.Tracks.FirstOrDefault();

            if (track?.Title == "Track empty" || track is null)
            {
                return(new KeyValuePair <LavaTrack, bool>(null, false));
            }

            if (player.PlayerState == PlayerState.Playing || player.PlayerState == PlayerState.Paused)
            {
                player.Queue.Enqueue(track);
                return(new KeyValuePair <LavaTrack, bool>(track, true));
            }

            await player.PlayAsync(track);

            await player.UpdateVolumeAsync(100);

            return(new KeyValuePair <LavaTrack, bool>(track, false));
        }
Exemplo n.º 8
0
        public async Task <IReadOnlyList <LavaTrack> > SearchAsync(string query)
        {
            var results = await _lavaNode.SearchYouTubeAsync(query);

            if (results.LoadStatus == LoadStatus.NoMatches || results.LoadStatus == LoadStatus.LoadFailed)
            {
                return(null);
            }
            return(results.Tracks);
        }
Exemplo n.º 9
0
        private async Task <Victoria.Responses.Rest.SearchResponse> SearchSongAsync(string query)
        {
            var results = await _lavaSocketClient.SearchAsync(query);

            if (results.LoadStatus == Victoria.Enums.LoadStatus.NoMatches || results.LoadStatus == Victoria.Enums.LoadStatus.LoadFailed)
            {
                results = await _lavaSocketClient.SearchYouTubeAsync(query);
            }

            return(results);
        }
Exemplo n.º 10
0
    public async Task PlayAsync(string searchQuery)
    {
        // Join if not playing.
        if (_lavaNode.HasPlayer(Context.Guild) is false)
        {
            await TryJoinAsync();
        }

        var player = _lavaNode.GetPlayer(Context.Guild);

        if (Context.User is IVoiceState user && user.VoiceChannel != player.VoiceChannel)
        {
            await RespondAsync("You must be in the same voice channel.");

            return;
        }

        await DeferAsync();

        // Play from url or search YouTube.
        var search = Uri.IsWellFormedUriString(searchQuery, UriKind.Absolute)
            ? await _lavaNode.SearchAsync(SearchType.Direct, searchQuery)
            : await _lavaNode.SearchYouTubeAsync(searchQuery);

        if (search.Status is SearchStatus.NoMatches or SearchStatus.LoadFailed)
        {
            await RespondAsync($"No matches found for query `{searchQuery.Truncate(100, "...")}`");

            return;
        }

        // Generate select menu for search results.
        var selectMenu = new SelectMenuBuilder()
                         .WithPlaceholder("Select a track")
                         .WithCustomId($"tracks:{Context.Interaction.Id}")
                         .WithMinValues(1)
                         .WithMaxValues(1);

        foreach (var track in search.Tracks.Take(10))
        {
            selectMenu.AddOption(
                track.Title,
                track.Url,
                track.Duration.ToString("c"),
                new Emoji("▶️"));
        }

        var components = new ComponentBuilder().WithSelectMenu(selectMenu);
        await Context.Interaction.ModifyOriginalResponseAsync(properties =>
        {
            properties.Content    = "Choose a track from the menu to play";
            properties.Components = components.Build();
        });
    }
Exemplo n.º 11
0
        public static async Task <string> PlayAsync(SocketGuildUser user, IGuild guild, string query)
        {
            if (user.VoiceChannel is null)
            {
                return("bir kanala gir babun");
            }

            try
            {
                var player = _lavaNode.GetPlayer(guild);

                LavaTrack track;

                var search = Uri.IsWellFormedUriString(query, UriKind.Absolute)
                    ? await _lavaNode.SearchAsync(query)
                    : await _lavaNode.SearchYouTubeAsync(query);

                if (search.LoadStatus == LoadStatus.NoMatches)
                {
                    return($"{query} hakkında bir şey bulamadım :(");
                }

                track = search.Tracks.FirstOrDefault();


                if (player.Track != null && player.PlayerState is PlayerState.Playing ||
                    player.PlayerState is PlayerState.Paused)
                {
                    player.Queue.Enqueue(track);
                    Console.WriteLine($"[{DateTime.Now}]\t(AUDIO)\tŞarkı sıraya eklendi.");
                    return($"{track.Title} sıraya eklendi.");
                }

                await player.PlayAsync(track);

                Console.WriteLine($"Şuanda Çalan Parça: {track.Title}");
                return($"Şuanda Çalan Parça: {track.Title} {track.Duration}");
            }
            catch (Exception ex)
            {
                return($"ERROR:\t{ex.Message}");
            }
        }
Exemplo n.º 12
0
        public async Task PlayAsync([Remainder] string query)
        {
            if (string.IsNullOrWhiteSpace(query))
            {
                await Context.Channel.SendErrorAsync("Music", "Please provide search terms.");

                return;
            }

            if (!_lavaNode.HasPlayer(Context.Guild))
            {
                await Context.Channel.SendErrorAsync("Music", "I'm not connected to a voice channel.");

                return;
            }

            var searchResponse = await _lavaNode.SearchYouTubeAsync(query);

            if (searchResponse.LoadStatus == LoadStatus.LoadFailed ||
                searchResponse.LoadStatus == LoadStatus.NoMatches)
            {
                await Context.Channel.SendErrorAsync("Music", $"I wasn't able to find anything for `{query}`.");

                return;
            }

            var player = _lavaNode.GetPlayer(Context.Guild);

            if (player.PlayerState == PlayerState.Playing || player.PlayerState == PlayerState.Paused)
            {
                var track = searchResponse.Tracks[0];
                player.Queue.Enqueue(track);
                await Context.Channel.SendSuccessAsync("Music", $"Enqueued: {track.Title}");
            }

            else
            {
                var track = searchResponse.Tracks[0];
                await player.PlayAsync(track);

                await Context.Channel.SendSuccessAsync("Music", $"Now Playing: {track.Title}");
            }
        }
Exemplo n.º 13
0
        /// <summary>
        ///     Search the source(s) for one or more tracks to play.
        /// </summary>
        /// <param name="query">The query to search for.</param>
        public async Task <SearchResult> Search(string query)
        {
            await Connect();

            var result = await _lavaNode.SearchAsync(query);

            if (result.LoadStatus == LoadStatus.NoMatches)
            {
                result = await _lavaNode.SearchYouTubeAsync(query);
            }

            var      tracks       = result.Tracks.Select(x => new VictoriaTrack(x)).ToList();
            var      resultStatus = ResultStatus.Failed;
            Playlist playlist     = null;
            string   exception    = null;

            switch (result.LoadStatus)
            {
            case LoadStatus.LoadFailed:
                resultStatus = ResultStatus.Failed;
                exception    = result.Exception.Message;
                break;

            case LoadStatus.NoMatches:
                resultStatus = ResultStatus.NoMatch;
                break;

            case LoadStatus.SearchResult:
                resultStatus = ResultStatus.SearchResult;
                break;

            case LoadStatus.TrackLoaded:
                resultStatus = ResultStatus.SingleTrack;
                break;

            case LoadStatus.PlaylistLoaded:
                resultStatus = ResultStatus.Playlist;
                playlist     = new Playlist(result.Playlist.Name, result.Playlist.SelectedTrack);
                break;
            }

            return(new SearchResult(tracks, resultStatus, playlist, exception));
        }
Exemplo n.º 14
0
        public async Task <string> PlayAsync(string query, ulong guildId)
        {
            var _player = _lavaNode.GetPlayer(_client.GetGuild(guildId));
            var results = await _lavaNode.SearchYouTubeAsync(query);

            if (results.LoadStatus == LoadStatus.NoMatches || results.LoadStatus == LoadStatus.LoadFailed)
            {
                return($"No matches found for '{query}'");
            }

            var track = results.Tracks.FirstOrDefault();

            if (_player.PlayerState == PlayerState.Playing)
            {
                _player.Queue.Enqueue(track);
                return($"**{track.Title}** has been added to the queue");
            }
            else
            {
                await _player.PlayAsync(track);

                return($"Now playing **{track.Title}**");
            }
        }
Exemplo n.º 15
0
        public async Task <string> PlayAsync(string query, IGuild guild, SocketGuildUser bot, SocketVoiceChannel vc, SocketTextChannel tc)
        {
            SearchResponse result;

            if (query.Contains("https://"))
            {
                result = _lavaNode.SearchAsync(query).Result;
            }
            else
            {
                result = _lavaNode.SearchYouTubeAsync(query).Result;
            }
            if (result.LoadStatus == LoadStatus.LoadFailed)
            {
                return(":x: Search failed.");
            }
            if (result.LoadStatus == LoadStatus.NoMatches)
            {
                return(":x: No matches found.");
            }
            PlaylistInfo playlist;

            LavaTrack track = result.Tracks.First();

            if (bot.VoiceChannel == null)
            {
                await ConnectAsync(vc, tc);
            }

            _player = _lavaNode.GetPlayer(guild);

            if (result.LoadStatus == LoadStatus.PlaylistLoaded)
            {
                playlist = result.Playlist;

                if (_player.PlayerState == PlayerState.Playing)
                {
                    foreach (LavaTrack resultTrack in result.Tracks)
                    {
                        _player.Queue.Enqueue(resultTrack);
                    }
                    return($":1234: Playlist `{playlist.Name}` loaded in queue.");
                }

                await _player.PlayAsync(track);

                foreach (LavaTrack resultTrack in result.Tracks)
                {
                    if (resultTrack != track)
                    {
                        _player.Queue.Enqueue(resultTrack);
                    }
                }
                return($":1234: Playlist `{playlist.Name}` loaded in queue ({result.Tracks.Count()} tracks).\n" +
                       $":arrow_forward: Now playing: `{track.Title}`");
            }

            if (_player.PlayerState == PlayerState.Playing)
            {
                _player.Queue.Enqueue(track);
                return($":fast_forward: `{track.Title}` added to the queue in position {_player.Queue.Items.ToList().IndexOf(track) + 1}.");
            }

            await _player.PlayAsync(track);

            return($":arrow_forward: Now playing: `{track.Title}`");
        }
Exemplo n.º 16
0
        public async Task PlayAsync([Remainder] string searchQuery)
        {
            if (string.IsNullOrWhiteSpace(searchQuery))
            {
                await FormatEmbedMessage("Please provide search terms.");

                return;
            }

            if (!_lavaNode.HasPlayer(Context.Guild))
            {
                await JoinAsync();
            }


            var searchResponse = await _lavaNode.SearchYouTubeAsync(searchQuery);

            if (searchResponse.LoadStatus == LoadStatus.LoadFailed ||
                searchResponse.LoadStatus == LoadStatus.NoMatches)
            {
                await FormatEmbedMessage($"I wasn't able to find anything for `{searchQuery}`.");

                return;
            }

            var player = _lavaNode.GetPlayer(Context.Guild);

            if (player.PlayerState == PlayerState.Playing || player.PlayerState == PlayerState.Paused)
            {
                if (!string.IsNullOrWhiteSpace(searchResponse.Playlist.Name))
                {
                    foreach (var track in searchResponse.Tracks)
                    {
                        player.Queue.Enqueue(track);
                    }

                    await FormatEmbedMessage($"Enqueued {searchResponse.Tracks.Count} tracks.");
                }
                else
                {
                    var track = searchResponse.Tracks[0];
                    player.Queue.Enqueue(track);
                    await FormatEmbedMessage($"Enqueued: {track.Title}");
                }
            }
            else
            {
                var track = searchResponse.Tracks[0];

                if (!string.IsNullOrWhiteSpace(searchResponse.Playlist.Name))
                {
                    for (var i = 0; i < searchResponse.Tracks.Count; i++)
                    {
                        if (i == 0)
                        {
                            await player.PlayAsync(track);
                            await FormatEmbedMessage(track.Title, $"Now Playing");
                        }
                        else
                        {
                            player.Queue.Enqueue(searchResponse.Tracks[i]);
                        }
                    }

                    await FormatEmbedMessage($"Enqueued {searchResponse.Tracks.Count} tracks.");
                }
                else
                {
                    await player.PlayAsync(track);
                    await FormatEmbedMessage(track.Title, "Now Playing");
                }
            }
        }
Exemplo n.º 17
0
        public async Task <LavaTrack?> PlayTrackAsync(string song, ICommandContext context, ITextChannel textChannel, bool useSC)
        {
            bool isLink = song.StartsWith("https://youtube.com/watch?v=") ||
                          song.StartsWith("youtube.com/watch?v=") ||
                          song.StartsWith("soundcloud.com") ||
                          song.StartsWith("https://soundcloud.com") ||
                          song.StartsWith("https://www.youtube.com/playlist?list=") ||
                          song.StartsWith("youtube.com/playlist?list=");

            var usersVc = context.UsersVC() as SocketVoiceChannel;
            var user    = context.User as IGuildUser;
            var player  = await JoinAsync(context, textChannel, true, false);

            var guild = GetOrAddConfig(context.Guild.Id);

            if (player == null)
            {
                return(null);
            }

            if (usersVc.Users.Count > 2 && !user.HasRole("DJ") && player.PlayerState == PlayerState.Playing)
            {
                return(await QueueAsync(song, context, textChannel, useSC));
            }
            SearchResponse response;

            if (!isLink)
            {
                if (useSC)
                {
                    response = await _audio.SearchSoundCloudAsync(song);
                }
                else
                {
                    response = await _audio.SearchYouTubeAsync(song);
                }
            }
            else
            {
                response = await _audio.SearchAsync(song);
            }

            if (response.Tracks.Count == 0)
            {
                await textChannel.SendMessageAsync(":musical_note: Cannot find the song :(.");

                return(null);
            }
            if (response.Tracks.Count > 1 && (isLink && song.Contains("playlist?list=")))
            {
                var tracks = new List <TrackInput>();
                foreach (var item in response.Tracks)
                {
                    tracks.Add(new TrackInput(item, context.User.Id));
                }
                for (int i = 1; i < tracks.Count; i++)
                {
                    guild.Queue.Enqueue(tracks[i]);
                }
            }
            var track = response.Tracks.FirstOrDefault();
            await player.PlayAsync(track);

            guild.CurrentUserPlaying = context.User.Id;

            {
                EmbedBuilder Embed = new EmbedBuilder();

                Embed.Title       = "Playing Song";
                Embed.Description = $"[{track.Title}]({track.Url})";


                Embed.AddField("Length", track.Duration.ToString(), true);
                if (guild.Repeat)
                {
                    Embed.AddField("Tracks in Queue", (guild.Queue.Count).ToString(), true);
                }
                else
                {
                    Embed.AddField("Tracks in Queue", (guild.Queue.Count).ToString(), true);
                }

                Embed.AddField("Next Track", guild.Queue.Count == 0 ? "No tracks" : (guild.Queue[0].Track as LavaTrack).Title, true);

                Embed.ImageUrl = await track.FetchArtworkAsync();

                await textChannel.SendMessageAsync("", false, Embed.Build());
            }
            return(track);
        }
Exemplo n.º 18
0
        public async Task QueueAsync(ICommandContext ctx, string query)
        {
            LavaPlayer player = _lavaNode.GetPlayer(ctx.Guild);

            if (string.IsNullOrWhiteSpace(query))
            {
                await player.TextChannel.EmbedAsync(new EmbedBuilder().WithDynamicColor(ctx)
                                                    .WithAuthor("Playing song", "https://i.imgur.com/fGNKX6x.png")
                                                    .WithDescription($"{player.Track.PrettyFullTrackWithCurrentPos()}")
                                                    .WithFooter(player.Track.PrettyFooter(player.Volume))).ConfigureAwait(false);

                return;
            }

            // check if url is youtube
            bool isYtUrl = Regex.IsMatch(query, @"^(https?\:\/\/)?((www\.)?youtube\.com|youtu\.?be)\/.+$");

            // matches youtube playlist
            // can use to capture playlist ID if needed
            bool isYtPlaylist = Regex.IsMatch(query, @"^.*(youtu.be\/|list=)([^#\&\?]*).*");

            SearchResponse result;

            if (isYtUrl)
            {
                result = await _lavaNode.SearchAsync(query).ConfigureAwait(false);
            }
            else
            {
                result = await _lavaNode.SearchYouTubeAsync(query).ConfigureAwait(false);
            }

            if (result.LoadStatus == LoadStatus.NoMatches)
            {
                await ctx.Channel.SendErrorAsync("No matches found.").ConfigureAwait(false);

                return;
            }

            if (result.LoadStatus == LoadStatus.LoadFailed)
            {
                await ctx.Channel.SendErrorAsync("Failed to load track.").ConfigureAwait(false);

                return;
            }

            if (isYtPlaylist && result.Tracks.Count > 1)
            {
                await QueuePlaylistAsync(ctx, player, result.Tracks).ConfigureAwait(false);

                return;
            }

            LavaTrack track = result.Tracks[0];

            // set the queued property so we know which user queued the track
            track.Queued = ctx.User as IGuildUser;
            LinkedListNode <LavaTrack> linkedTrack = player.Queue.Enqueue(track);

            EmbedBuilder embed = new EmbedBuilder().WithDynamicColor(ctx);

            if (player.PlayerState == PlayerState.Playing || player.PlayerState == PlayerState.Paused)
            {
                embed.WithAuthor($"Queued: #{player.Queue.Count}", "https://i.imgur.com/VTRacvz.png")
                .WithDescription($"{track.PrettyTrack()}")
                .WithFooter(track.PrettyFooter(player.Volume) + FormatAutoplayAndLoop(player));
                IUserMessage msg = await ctx.Channel.EmbedAsync(embed).ConfigureAwait(false);

                msg.DeleteAfter(10);
            }
            else
            {
                await player.PlayAsync(linkedTrack).ConfigureAwait(false);

                embed.WithAuthor("Playing song", "https://i.imgur.com/fGNKX6x.png")
                .WithDescription($"{track.PrettyTrack()}")
                .WithFooter(track.PrettyFooter(player.Volume));
                await ctx.Channel.EmbedAsync(embed).ConfigureAwait(false);
            }

            await ctx.Message.DeleteAsync().ConfigureAwait(false);
        }
Exemplo n.º 19
0
        public async Task Play([Remainder] string name)
        {
            var channel = (Context.User as IGuildUser).VoiceChannel;

            if (channel == null)
            {
                await ReplyAsync("You are not connected to any voice channel!");

                return;
            }

            var result = await _node.SearchYouTubeAsync(name);

            if (result.Tracks.Count() == 0)
            {
                await ReplyAsync("Results not found!");

                return;
            }

            int resultSize   = 5;
            int i            = 1;
            var resultString = result.Tracks.Take(resultSize).Aggregate("**Choose the track to play:**\n", (prev, track) =>
            {
                return(prev + "**" + i++ + ".** " + track.Title.ToString() + " (<" + track.Uri.ToString() + ">)\n");
            });

            var listMessage = await ReplyAsync(resultString);

            int           number;
            SocketMessage response;

            while (true)
            {
                response = await NextMessageAsync(new NumberCriterion());

                number = int.Parse(response.Content);
                await(response as IUserMessage).DeleteAsync();
                if (number <= 0 || number > resultSize || number > result.Tracks.Count())
                {
                    await ReplyAsync("Invalid track number");
                }
                else
                {
                    break;
                }
            }

            _player = await _node.ConnectAsync(channel);

            var selectedTrack = result.Tracks.Skip(number - 1).FirstOrDefault();

            if (_player.IsPlaying)
            {
                _player.Queue.Enqueue(selectedTrack);
                await ReplyAsync($"Added track to the queue at position **{_player.Queue.Count}.**");
                await Queue();
            }
            else
            {
                await _player.PlayAsync(selectedTrack);
            }

            await listMessage.DeleteAsync();
        }
Exemplo n.º 20
0
        /***
         * Searches the internet for a song and plays it
         */
        public async Task <Embed> PlayAsync(string query, IGuild guild, SocketGuildUser user)
        {
            //Check If User Is Connected To Voice Cahnnel.
            if (user.VoiceChannel == null)
            {
                return(await EmbedHandler.CreateErrorEmbed("Music, Join/Play", "You Must First Join a Voice Channel."));
            }

            //Check the guild has a player available.
            if (!_lavaNode.HasPlayer(guild))
            {
                return(await EmbedHandler.CreateErrorEmbed("Music, Play", "I'm not connected to a voice channel."));
            }

            try
            {
                //Get the player for that guild.
                var player = _lavaNode.GetPlayer(guild);

                //Find The Youtube Track the User requested.
                LavaTrack      track;
                SearchResponse search = new SearchResponse();

                if (query.Contains("youtube.com"))
                {
                    // Search Youtube
                    search = await _lavaNode.SearchYouTubeAsync(query);
                }
                else if (query.Contains("soundcloud.com"))
                {
                    // Search Soundcloud
                    search = await _lavaNode.SearchSoundCloudAsync(query);
                }
                else
                {
                    // Search youtube if not a URL
                    search = await _lavaNode.SearchYouTubeAsync(query);
                }

                //If we couldn't find anything, tell the user.
                if (search.LoadStatus == LoadStatus.NoMatches)
                {
                    return(await EmbedHandler.CreateErrorEmbed("Music", $"I wasn't able to find anything for {query}."));
                }

                //Get the first track from the search results.
                //TODO: Add a 1-5 list for the user to pick from. (Like Fredboat)
                track = search.Tracks.FirstOrDefault();

                //If the Bot is already playing music, or if it is paused but still has music in the queue, Add the requested track to the queue.
                if (player.Track != null && player.PlayerState is PlayerState.Playing || player.PlayerState is PlayerState.Paused)
                {
                    player.Queue.Enqueue(track);
                    Log.Information("Music", $"{track.Title} has been added to the queue.");
                    return(await EmbedHandler.CreateSongQueueEmbed(track));
                }

                //Player was not playing anything, so lets play the requested track.
                await player.PlayAsync(track);

                Log.Information("Music", $"Bot Now Playing: {track.Title}\nUrl: {track.Url}");
                return(await EmbedHandler.CreateSongPlayEmbed(track));
            }

            //If after all the checks we did, something still goes wrong. Tell the user about it so they can report it back to us.
            catch (Exception ex)
            {
                return(await EmbedHandler.CreateErrorEmbed("Music, Play", ex.Message));
            }
        }
Exemplo n.º 21
0
        public async Task PlayAsync([Remainder] string query)
        {
            var voiceState = Context.User as IVoiceState;

            if (voiceState?.VoiceChannel == null)
            {
                await ReplyAsync("You must be connected to a voice channel!");

                return;
            }

            if (!_lavaNode.TryGetPlayer(Context.Guild, out var player)
                ) //Check if bot is connected to a voice channel in that guild and if not join new one
            {
                try
                {
                    await _lavaNode.JoinAsync(voiceState.VoiceChannel, Context.Channel as ITextChannel);

                    await Context.Channel.SendSuccessAsync("Success", $"Joined {voiceState.VoiceChannel.Name}");
                }
                catch (Exception exception)
                {
                    await Context.Channel.SendErrorAsync("Error", exception.Message);
                }
            }

            if (string.IsNullOrWhiteSpace(query)) //Check if nothing was entered
            {
                await Context.Channel.SendErrorAsync("Error", "Please provide search terms");

                return;
            }

            var players = _lavaNode.GetPlayer(Context.Guild);

            if (query.StartsWith("https://")) //Check if user entered link
            {
                var queries = query.Split(' ');
                foreach (var songQuery in queries)
                {
                    var searchResponse1 = await _lavaNode.SearchAsync(songQuery);

                    if (searchResponse1.LoadStatus == LoadStatus.LoadFailed ||
                        searchResponse1.LoadStatus == LoadStatus.NoMatches)
                    {
                        await Context.Channel.SendErrorAsync("Error", $"I could not find anything for `{songQuery}`");

                        return;
                    }


                    if (players.PlayerState == PlayerState.Playing || players.PlayerState == PlayerState.Paused)
                    {
                        if (!string.IsNullOrWhiteSpace(searchResponse1.Playlist.Name))
                        {
                            foreach (var track in searchResponse1.Tracks)
                            {
                                players.Queue.Enqueue(track);
                            }

                            var track1    = searchResponse1.Tracks[0];
                            var thumbnail = await track1.FetchArtworkAsync(); //get album cover for current song

                            await Context.Channel.Music("Enqued:",
                                                        $"Enqueued `{searchResponse1.Tracks.Count}` songs from the `{searchResponse1.Playlist.Name}` playlist",
                                                        thumbnail ??
                                                        "https://external-content.duckduckgo.com/iu/?u=http%3A%2F%2Ficons.iconarchive.com%2Ficons%2Fiynque%2Fios7-style%2F1024%2FMusic-icon.png&f=1&nofb=1");
                        }
                        else
                        {
                            var track     = searchResponse1.Tracks[0];
                            var thumbnail = await track.FetchArtworkAsync(); //get album cover for current song

                            players.Queue.Enqueue(track);
                            await ReplyAsync($"Enqueued: {track.Title}");

                            await Context.Channel.Music("Enqued:", $"Enqueued `{track.Title}`",
                                                        thumbnail ??
                                                        "https://external-content.duckduckgo.com/iu/?u=http%3A%2F%2Ficons.iconarchive.com%2Ficons%2Fiynque%2Fios7-style%2F1024%2FMusic-icon.png&f=1&nofb=1");
                        }
                    }
                    else
                    {
                        var track = searchResponse1.Tracks[0];
                        var thumb = await track.FetchArtworkAsync(); //get album cover for current song

                        if (!string.IsNullOrWhiteSpace(searchResponse1.Playlist.Name))
                        {
                            for (var i = 0; i < searchResponse1.Tracks.Count; i++)
                            {
                                if (i == 0)
                                {
                                    await players.PlayAsync(track);

                                    await Context.Channel.Music("Now Playing:", $"Now playing `{track.Title}`", thumb);
                                }
                                else
                                {
                                    players.Queue.Enqueue(searchResponse1.Tracks[i]);
                                }
                            }

                            var track1    = searchResponse1.Tracks[0];
                            var thumbnail = await track1.FetchArtworkAsync(); //get album cover for current song

                            await Context.Channel.Music("Enqued:",
                                                        $"Enqueued `{searchResponse1.Tracks.Count}` songs from the `{searchResponse1.Playlist.Name}` playlist",
                                                        thumbnail ??
                                                        "https://external-content.duckduckgo.com/iu/?u=http%3A%2F%2Ficons.iconarchive.com%2Ficons%2Fiynque%2Fios7-style%2F1024%2FMusic-icon.png&f=1&nofb=1");
                        }
                        else
                        {
                            var track1    = searchResponse1.Tracks[0];
                            var durSec    = track1.Duration.Seconds;
                            var durMin    = track1.Duration.Minutes;
                            var thumbnail = await track1.FetchArtworkAsync(); //get album cover for current song

                            await players.PlayAsync(track);

                            await Context.Channel.Music("Now Playing:",
                                                        $"**Now playing:** `{track.Title}`\n**Duration:** `{durMin}:{durSec}`", thumbnail);
                        }
                    }
                }
            }
            else //if query is not a url search youtube
            {
                var searchResponse = await _lavaNode.SearchYouTubeAsync(query);

                if (searchResponse.LoadStatus == LoadStatus.LoadFailed ||
                    searchResponse.LoadStatus == LoadStatus.NoMatches)
                {
                    await Context.Channel.SendErrorAsync("Error", $"I could not find anything for `{query}`");

                    //await ReplyAsync($"I wasn't able to find anything for `{query}`.");
                    return;
                }


                if (players.PlayerState == PlayerState.Playing || players.PlayerState == PlayerState.Paused)
                {
                    var track     = searchResponse.Tracks[0];
                    var thumbnail = await track.FetchArtworkAsync(); //get album cover for current song

                    var durSec = track.Duration.Seconds;
                    var durMin = track.Duration.Minutes;

                    players.Queue.Enqueue(track);
                    await Context.Channel.Music("Enqued:",
                                                $"**Song:** `{track.Title}`\n**Duration:** `{durMin}:{durSec}`",
                                                thumbnail ??
                                                "https://external-content.duckduckgo.com/iu/?u=http%3A%2F%2Ficons.iconarchive.com%2Ficons%2Fiynque%2Fios7-style%2F1024%2FMusic-icon.png&f=1&nofb=1");
                }
                else
                {
                    var track     = searchResponse.Tracks[0];
                    var thumbnail = await track.FetchArtworkAsync(); //get album cover for current song

                    var durSec = track.Duration.Seconds;
                    var durMin = track.Duration.Minutes;

                    await players.PlayAsync(track);

                    await Context.Channel.Music("Playing:",
                                                $"**Song:** `{track.Title}`\n**Duration:** `{durMin}:{durSec}`",
                                                thumbnail ??
                                                "https://external-content.duckduckgo.com/iu/?u=http%3A%2F%2Ficons.iconarchive.com%2Ficons%2Fiynque%2Fios7-style%2F1024%2FMusic-icon.png&f=1&nofb=1");
                }
            }
        }
Exemplo n.º 22
0
        public async Task PlayAsync([Remainder] string searchQuery)
        {
            if (string.IsNullOrWhiteSpace(searchQuery))
            {
                //await ReplyAsync("Please provide search terms.");
                await Context.Channel.SendErrorAsync("No search terms!", "Please provide search terms!");

                return;
            }

            if (!_lavaNode.HasPlayer(Context.Guild))
            {
                await Context.Channel.SendErrorAsync("Error!", "I'm not connected to a voice channel!");

                return;
            }

            var voiceState = Context.User as IVoiceState;

            if (voiceState?.VoiceChannel == null)
            {
                await Context.Channel.SendErrorAsync("Error!", "You must be connected to a voice channel!");

                return;
            }

            if (!searchQuery.StartsWith("http"))
            {
                var searchResponse = await _lavaNode.SearchYouTubeAsync(searchQuery);

                if (searchResponse.LoadStatus == LoadStatus.LoadFailed ||
                    searchResponse.LoadStatus == LoadStatus.NoMatches)
                {
                    await Context.Channel.SendErrorAsync("Error!", $"I wasn't able to find anything for `{searchQuery}`.");

                    return;
                }


                var player = _lavaNode.GetPlayer(Context.Guild);

                if (player.PlayerState == PlayerState.Playing || player.PlayerState == PlayerState.Paused)
                {
                    if (!string.IsNullOrWhiteSpace(searchResponse.Playlist.Name))
                    {
                        foreach (var track in searchResponse.Tracks)
                        {
                            player.Queue.Enqueue(track);
                        }

                        //await ReplyAsync($"Enqueued {searchResponse.Tracks.Count} tracks.");
                        await Context.Channel.SendSuccessAsync("Queued!", $"Enqueued {searchResponse.Tracks.Count} tracks.");
                    }
                    else
                    {
                        var track = searchResponse.Tracks[0];
                        player.Queue.Enqueue(track);
                        await Context.Channel.SendSuccessAsync("Queued!", $"Enqueued: `{track.Title}`");
                    }
                }
                else
                {
                    var track = searchResponse.Tracks[0];
                    if (!string.IsNullOrWhiteSpace(searchResponse.Playlist.Name))
                    {
                        for (var i = 0; i < searchResponse.Tracks.Count; i++)
                        {
                            if (i == 0)
                            {
                                await player.PlayAsync(track);

                                await Context.Channel.SendSuccessAsync("Playing!", $"Now Playing: `{track.Title}`");

                                await _client.SetGameAsync($"{track.Title}", null, ActivityType.Listening);
                            }
                            else
                            {
                                player.Queue.Enqueue(searchResponse.Tracks[i]);
                            }
                        }
                        await Context.Channel.SendSuccessAsync("Queued!", $"Enqueued {searchResponse.Tracks.Count} tracks.");
                    }
                    else
                    {
                        await player.PlayAsync(track);

                        await Context.Channel.SendSuccessAsync("Playing!", $"Now Playing: `{track.Title}`");

                        await _client.SetGameAsync($"{track.Title}", null, ActivityType.Listening);
                    }
                }
            }
            else
            {
                var queries = searchQuery.Split(' ');
                foreach (var query in queries)
                {
                    var searchResponse = await _lavaNode.SearchAsync(query);

                    if (searchResponse.LoadStatus == LoadStatus.LoadFailed ||
                        searchResponse.LoadStatus == LoadStatus.NoMatches)
                    {
                        await Context.Channel.SendErrorAsync("Error!", $"I wasn't able to find anything for `{query}`.");

                        return;
                    }


                    var player = _lavaNode.GetPlayer(Context.Guild);

                    if (player.PlayerState == PlayerState.Playing || player.PlayerState == PlayerState.Paused)
                    {
                        if (!string.IsNullOrWhiteSpace(searchResponse.Playlist.Name))
                        {
                            foreach (var track in searchResponse.Tracks)
                            {
                                player.Queue.Enqueue(track);
                            }

                            //await ReplyAsync($"Enqueued {searchResponse.Tracks.Count} tracks.");
                            await Context.Channel.SendSuccessAsync("Queued!", $"Enqueued {searchResponse.Tracks.Count} tracks.");
                        }
                        else
                        {
                            var track = searchResponse.Tracks[0];
                            player.Queue.Enqueue(track);
                            await Context.Channel.SendSuccessAsync("Queued!", $"Enqueued: `{track.Title}`");
                        }
                    }
                    else
                    {
                        var track = searchResponse.Tracks[0];
                        if (!string.IsNullOrWhiteSpace(searchResponse.Playlist.Name))
                        {
                            for (var i = 0; i < searchResponse.Tracks.Count; i++)
                            {
                                if (i == 0)
                                {
                                    await player.PlayAsync(track);

                                    await Context.Channel.SendSuccessAsync("Playing!", $"Now Playing: `{track.Title}`");

                                    await _client.SetGameAsync($"{track.Title}", null, ActivityType.Listening);
                                }
                                else
                                {
                                    player.Queue.Enqueue(searchResponse.Tracks[i]);
                                }
                            }
                            await Context.Channel.SendSuccessAsync("Queued!", $"Enqueued {searchResponse.Tracks.Count} tracks.");
                        }
                        else
                        {
                            await player.PlayAsync(track);

                            await Context.Channel.SendSuccessAsync("Playing!", $"Now Playing: `{track.Title}`");

                            await _client.SetGameAsync($"{track.Title}", null, ActivityType.Listening);
                        }
                    }
                }
            }
        }
Exemplo n.º 23
0
        public async Task Play(
            [Summary("Either add a link to what you want to play or if you just enter a search " +
                     "it will query YouTube and take the first result."), Remainder]
            string query)
        {
            if (!_node.TryGetPlayer(Context.Guild, out var player))
            {
                await ReplyFailureEmbed("I have not joined any Voice Channel yet.");

                return;
            }

            if (!await CheckIfSameVc(player.VoiceChannel))
            {
                return;
            }

            if (query.StartsWith("<") && query.EndsWith(">"))
            {
                query = query.TrimStart('<').TrimEnd('>');
            }

            bool isLink = Uri.IsWellFormedUriString(query, UriKind.RelativeOrAbsolute);

            var search = isLink
                ? await _node.SearchAsync(query)
                : await _node.SearchYouTubeAsync(query);

            if (search.LoadStatus == LoadStatus.LoadFailed ||
                search.LoadStatus == LoadStatus.NoMatches ||
                search.Tracks == null || search.Tracks.Count == 0)
            {
                await ReplyFailureEmbed("Couldn't find anything :/");

                return;
            }

            if (search.LoadStatus == LoadStatus.PlaylistLoaded)
            {
                int skip = -1;
                // First add selected track
                if (search.Playlist.SelectedTrack > 0 && search.Playlist.SelectedTrack < search.Tracks.Count)
                {
                    if (player.Track != null)
                    {
                        player.Queue.Enqueue(search.Tracks[search.Playlist.SelectedTrack]);
                    }
                    else
                    {
                        await player.PlayAsync(search.Tracks[search.Playlist.SelectedTrack]);
                    }
                    skip = search.Playlist.SelectedTrack;
                }

                // Add playlist
                for (var i = 0; i < search.Tracks.Count; i++)
                {
                    if (i == skip)
                    {
                        continue;
                    }

                    var track = search.Tracks[i];
                    if (player.Track != null)
                    {
                        player.Queue.Enqueue(track);
                    }
                    else
                    {
                        await player.PlayAsync(track);
                    }
                }

                await ReplyMusicEmbed(
                    $"Successfully added {search.Tracks.Count.ToString()} songs from playlist {search.Playlist.Name}");
            }
            else
            {
                var track = search.Tracks[0];
                if (player.Track != null)
                {
                    player.Queue.Enqueue(track);
                    await ReplyMusicExtended(track);
                }
                else
                {
                    await player.PlayAsync(track);
                    await ReplyMusicExtended(track, false);
                }
            }
        }
Exemplo n.º 24
0
        public async Task Play([Remainder] string query)
        {
            if (string.IsNullOrWhiteSpace(query))
            {
                await SendWarningAsync("Please provide search terms.");

                return;
            }

            if (!LavaNode.HasPlayer(Context.Guild))
            {
                await SendWarningAsync("I'm not connected to a voice channel.");

                return;
            }

            var searchResponse = await LavaNode.SearchAsync(query);

            if (searchResponse.LoadStatus == LoadStatus.LoadFailed || searchResponse.LoadStatus == LoadStatus.NoMatches)
            {
                searchResponse = await LavaNode.SearchYouTubeAsync(query);

                if (searchResponse.LoadStatus == LoadStatus.LoadFailed ||
                    searchResponse.LoadStatus == LoadStatus.NoMatches)
                {
                    await SendErrorAsync($"I wasn't able to find anything for <{query}>.");

                    return;
                }
            }

            var player = LavaNode.GetPlayer(Context.Guild);

            if (player.PlayerState == PlayerState.Playing || player.PlayerState == PlayerState.Paused)
            {
                if (!string.IsNullOrWhiteSpace(searchResponse.Playlist.Name))
                {
                    foreach (var lavaTrack in searchResponse.Tracks)
                    {
                        var track = lavaTrack;
                        track.Queued = Context.User as IGuildUser;
                        player.Queue.Enqueue(track);
                    }

                    await SendSuccessAsync($"Enqueued {searchResponse.Tracks.Count} tracks.");
                }
                else
                {
                    var track = searchResponse.Tracks[0];
                    track.Queued = Context.User as IGuildUser;
                    player.Queue.Enqueue(track);
                    var artwork = await track.FetchArtworkAsync();

                    var embed = new EmbedBuilder()
                                .WithAuthor("Added to queue", Context.User.GetAvatarUrl())
                                .WithTitle(track.Title)
                                .WithUrl(track.Url)
                                .WithThumbnailUrl(artwork)
                                .AddField("Channel", track.Author, true)
                                .AddField("Duration", track.Duration, true)
                                .AddField("Position in queue", player.Queue.Count)
                                .WithFooter($"Requested By {track.Queued.Username}")
                                .WithColor(Color.Teal)
                                .Build();

                    await SendEmbedAsync(embed);
                }
            }
            else
            {
                var track = searchResponse.Tracks[0];
                track.Queued = Context.User as IGuildUser;

                if (!string.IsNullOrWhiteSpace(searchResponse.Playlist.Name))
                {
                    for (var i = 0; i < searchResponse.Tracks.Count; i++)
                    {
                        if (i == 0)
                        {
                            await SendPlayingEmbed(player, track);
                        }
                        else
                        {
                            player.Queue.Enqueue(searchResponse.Tracks[i]);
                        }
                    }

                    await SendSuccessAsync($"Enqueued {searchResponse.Tracks.Count} tracks.");
                }
                else
                {
                    await SendPlayingEmbed(player, track);
                }
            }
        }
Exemplo n.º 25
0
        private async Task QueryAndPlayHelperAsync(string searchQuery)
        {
            var            queries = searchQuery.Split(' ');
            SearchResponse searchResponse;

            if (searchQuery.Contains('/') || searchQuery.Contains('?'))
            {
                foreach (var query in queries)
                {
                    searchResponse = await _lavaNode.SearchAsync(query);

                    if (searchResponse.LoadStatus == LoadStatus.LoadFailed || searchResponse.LoadStatus == LoadStatus.NoMatches)
                    {
                        return;
                    }
                    var player = _lavaNode.GetPlayer(Context.Guild);

                    if (player.PlayerState == PlayerState.Playing || player.PlayerState == PlayerState.Paused)
                    {
                        if (!string.IsNullOrWhiteSpace(searchResponse.Playlist.Name))
                        {
                            foreach (var track in searchResponse.Tracks)
                            {
                                player.Queue.Enqueue(track);
                            }

                            await ReplyAsync($"Enqueued {searchResponse.Tracks.Count} tracks.");
                        }
                        else
                        {
                            var track = searchResponse.Tracks[0];

                            player.Queue.Enqueue(track);

                            await ReplyAsync($"Enqueued: {track.Title}");
                        }
                    }
                    else
                    {
                        var track = searchResponse.Tracks[0];

                        if (!string.IsNullOrWhiteSpace(searchResponse.Playlist.Name))
                        {
                            for (var i = 0; i < searchResponse.Tracks.Count; i++)
                            {
                                if (i == 0)
                                {
                                    await player.PlayAsync(track);
                                    await ReplyAsync($"Now Playing: {track.Title}");
                                }
                                else
                                {
                                    player.Queue.Enqueue(searchResponse.Tracks[i]);
                                }
                            }

                            await ReplyAsync($"Enqueued {searchResponse.Tracks.Count} tracks.");
                        }
                        else
                        {
                            await player.PlayAsync(track);
                            await ReplyAsync($"Now Playing: {track.Title}");
                        }
                    }
                }
            }
            else
            {
                searchResponse = await _lavaNode.SearchYouTubeAsync(searchQuery);

                LavaTrack track;
                if (searchResponse.LoadStatus == LoadStatus.LoadFailed || searchResponse.LoadStatus == LoadStatus.NoMatches)
                {
                    return;
                }
                var player = _lavaNode.GetPlayer(Context.Guild);

                if (player.PlayerState == PlayerState.Playing || player.PlayerState == PlayerState.Paused)
                {
                    track = searchResponse.Tracks[0];

                    player.Queue.Enqueue(track);

                    await ReplyAsync($"Enqueued: {track.Title}");
                }
                else
                {
                    track = searchResponse.Tracks[0];
                    await player.PlayAsync(track);
                    await ReplyAsync($"Now Playing: {track.Title}");
                }
            }
            return;
        }
Exemplo n.º 26
0
        public async Task PlayAsync([Remainder] string query = null)
        {
            if (!_lavaNode.HasPlayer(Context.Guild))
            {
                await ReplyAndDeleteAsync(":x: I am not connected to a voice channel.");

                return;
            }

            var player = _lavaNode.GetPlayer(Context.Guild);

            if (query == null && player.Queue.TryDequeue(out var queueable))
            {
                if (!(queueable is LavaTrack track))
                {
                    await ReplyAndDeleteAsync(":x: Next item in queue is not a track.");

                    return;
                }

                await player.PlayAsync(track);
            }

            var isUri          = Uri.TryCreate(query, UriKind.Absolute, out _);
            var searchResponse = isUri
                ? await _lavaNode.SearchAsync(query)
                : await _lavaNode.SearchYouTubeAsync(query);

            if (!(searchResponse.LoadStatus != LoadStatus.LoadFailed && searchResponse.LoadStatus != LoadStatus.NoMatches) && !isUri)
            {
                searchResponse = await _lavaNode.SearchSoundCloudAsync(query);
            }

            if (searchResponse.LoadStatus == LoadStatus.LoadFailed || searchResponse.LoadStatus == LoadStatus.NoMatches)
            {
                await ReplyAndDeleteAsync($":x: No search results for `{query}`.");

                return;
            }

            var tracks = searchResponse.Tracks;

            if (player.PlayerState == PlayerState.Playing || player.PlayerState == PlayerState.Paused)
            {
                if (!string.IsNullOrWhiteSpace(searchResponse.Playlist.Name))
                {
                    player.Queue.Enqueue(tracks);
                    await ReplyAndDeleteAsync($"Enqueued {tracks.Count} tracks.");

                    return;
                }
                else
                {
                    var eta = "";

                    var track = tracks.First();
                    player.Queue.Enqueue(track);
                    var artwork = await track.FetchArtworkAsync();

                    var embed = new EmbedBuilder()
                                .WithTitle("Enqueued")
                                .WithDescription($"[{track.Title}]({track.Url})")
                                .WithThumbnailUrl(artwork)
                                .AddField("Duration", $"`{track.Duration.StripMilliseconds()}`", true)
                                .AddField("ETA", $"`{eta}`");
                    await ReplyAndDeleteAsync(embed : embed.Build());

                    return;
                }
            }
            else
            {
                await player.PlayAsync(tracks.First());

                if (!string.IsNullOrWhiteSpace(searchResponse.Playlist.Name))
                {
                    player.Queue.Enqueue(tracks.Skip(1));
                    await ReplyAndDeleteAsync($"Enqueued {tracks.Count - 1} tracks.");

                    return;
                }

                await Context.Message.DeleteAsync();
            }
        }
Exemplo n.º 27
0
        public async Task PlayAsync([Remainder] string searchQuery)
        {
            Language lang = Commands.GetLanguage(Context.Guild.Id);

            if (!_lavaNode.HasPlayer(Context.Guild))
            {
                IVoiceState voiceState = Context.User as IVoiceState;
                if (voiceState?.VoiceChannel == null)
                {
                    EmbedBuilder b = new EmbedBuilder();
                    b.WithTitle(lang.Not_connected);
                    b.WithFooter(lang.Requested_by + Context.User.Username, Commands.GetUserAvatarUrl(Context.User));
                    await ReplyAsync(embed : b.Build());

                    return;
                }

                try
                {
                    await _lavaNode.JoinAsync(voiceState.VoiceChannel, Context.Channel as ITextChannel);

                    EmbedBuilder b = new EmbedBuilder();
                    b.WithTitle(lang.Joined_before + voiceState.VoiceChannel.Name + lang.Joined_after);
                    b.WithFooter(lang.Requested_by + Context.User.Username, Commands.GetUserAvatarUrl(Context.User));
                    await ReplyAsync(embed : b.Build());
                }
                catch (Exception exception)
                {
                    await Exeptionhandle(exception, "join in play").ConfigureAwait(false);

                    throw;
                }
            }
            LavaPlayer player = _lavaNode.GetPlayer(Context.Guild);

            if (player.PlayerState == PlayerState.Paused && string.IsNullOrEmpty(searchQuery))
            {
                try
                {
                    await player.ResumeAsync();
                    await ReplyAsync(lang.Resumed_front + player.Track.Title);

                    return;
                }
                catch (Exception exception)
                {
                    await Exeptionhandle(exception, "resume in play").ConfigureAwait(false);

                    throw;
                }
            }
            else
            {
                if (string.IsNullOrWhiteSpace(searchQuery))
                {
                    await ReplyAsync(lang.No_search_term);

                    return;
                }
            }
            int searchtype = 0;

            Victoria.Responses.Rest.SearchResponse searchResponse = await _lavaNode.SearchAsync(searchQuery);

            if (searchResponse.LoadStatus == LoadStatus.LoadFailed ||
                searchResponse.LoadStatus == LoadStatus.NoMatches)
            {
                searchResponse = await _lavaNode.SearchYouTubeAsync(searchQuery); searchtype = 1;
                if (searchResponse.LoadStatus == LoadStatus.LoadFailed ||
                    searchResponse.LoadStatus == LoadStatus.NoMatches)
                {
                    searchResponse = await _lavaNode.SearchSoundCloudAsync(searchQuery); searchtype = 2;
                    if (searchResponse.LoadStatus == LoadStatus.LoadFailed ||
                        searchResponse.LoadStatus == LoadStatus.NoMatches)
                    {
                        EmbedBuilder eb = new EmbedBuilder();
                        eb.WithTitle(lang.No_results_front + searchQuery + lang.No_results_back);
                        eb.WithFooter(lang.Requested_by + Context.User.Username, Commands.GetUserAvatarUrl(Context.User));
                        await ReplyAsync($"", false, eb.Build());

                        return;
                    }
                }
            }

            if (player.PlayerState == PlayerState.Playing || player.PlayerState == PlayerState.Paused)
            {
                if (!string.IsNullOrWhiteSpace(searchResponse.Playlist.Name))
                {
                    foreach (LavaTrack track in searchResponse.Tracks)
                    {
                        player.Queue.Enqueue(track);
                    }

                    await ReplyAsync($"Enqueued {searchResponse.Tracks.Count} tracks.");
                }
                else
                {
                    LavaTrack track = searchResponse.Tracks[0];
                    player.Queue.Enqueue(track);
                    await ReplyAsync($"Enqueued: {track.Title}");
                }
            }
            else
            {
                LavaTrack track = searchResponse.Tracks[0];

                if (!string.IsNullOrWhiteSpace(searchResponse.Playlist.Name))
                {
                    for (int i = 0; i < searchResponse.Tracks.Count; i++)
                    {
                        if (i == 0)
                        {
                            await player.PlayAsync(track);

                            EmbedBuilder b = new EmbedBuilder();
                            b.WithTitle($"Now playing: {track.Title}");
                            if (searchtype == 1)
                            {
                                b.AddField("source", "<:youtube:793403957871247360> search");
                            }
                            if (searchtype == 2)
                            {
                                b.AddField("source", "<:soundcloud:793405493204090911> search");
                            }
                            string art = await track.FetchArtworkAsync();

                            b.WithThumbnailUrl(art);
                            b.WithFooter(lang.Requested_by + Context.User.Username, Commands.GetUserAvatarUrl(Context.User));
                            await ReplyAsync(embed : b.Build());
                        }
                        else
                        {
                            if (searchResponse.Tracks[i] == null)
                            {
                                await ReplyAsync(i + " was null");
                            }
                            player.Queue.Enqueue(searchResponse.Tracks[i]);
                        }
                    }

                    await ReplyAsync($"Enqueued {searchResponse.Tracks.Count} tracks.");
                }
                else
                {
                    await player.PlayAsync(track);

                    EmbedBuilder b = new EmbedBuilder();
                    b.WithTitle($"Now playing: {track.Title}");
                    if (searchtype == 1)
                    {
                        b.AddField("source", "<:youtube:793403957871247360> search");
                    }
                    if (searchtype == 2)
                    {
                        b.AddField("source", "<:soundcloud:793405493204090911> search");
                    }
                    string art = await track.FetchArtworkAsync();

                    b.WithThumbnailUrl(art);
                    b.WithFooter(new Language().Requested_by + Context.User.Username, Commands.GetUserAvatarUrl(Context.User));
                    await ReplyAsync(embed : b.Build());
                }
            }
        }
Exemplo n.º 28
0
        public static async System.Threading.Tasks.Task <bool> MusicCommands(SocketMessage message, CommandContext context, DiscordSocketClient client, LavaNode lava)
        {
            if (Validation.CheckCommand(message, "play"))
            {
                if ((message.Author as IVoiceState).VoiceChannel == null)
                {
                    DiscordFunctions.EmbedThis("Music", "You must first join a voice channel!", "red", context);
                    return(true);
                }


                var temp = client.GetGuild(context.Guild.Id).CurrentUser.VoiceState;
                if (temp != null && client.GetGuild(context.Guild.Id).CurrentUser.VoiceChannel != (message.Author as IVoiceState).VoiceChannel)
                {
                    DiscordFunctions.EmbedThis("Music", "I can't join another voice channel until I'm disconnected from another channel.", "red", context);
                    return(true);
                }

                SearchResponse search    = new SearchResponse();
                var            videoId   = string.Empty;
                var            timestamp = string.Empty;
                string         query     = message.Content.ToLower().Replace("!play ", "");
                if (query.ToLower().Contains("www.youtube.com/watch?v="))
                {
                    var uri     = new Uri(@query);
                    var queryid = HttpUtility.ParseQueryString(uri.Query);

                    if (queryid.AllKeys.Contains("v"))
                    {
                        videoId = queryid["v"];
                    }
                    else
                    {
                        videoId = uri.Segments.Last();
                    }
                    if (queryid.AllKeys.Contains("t"))
                    {
                        timestamp = queryid["t"];
                    }
                    if (timestamp != string.Empty)
                    {
                        videoId = videoId.Replace("&t=" + timestamp, "");
                    }
                    search = await lava.SearchYouTubeAsync(query.Replace("&t=" + timestamp, ""));
                }
                else
                {
                    search = await lava.SearchYouTubeAsync(query);
                }
                LavaTrack track = new LavaTrack();
                if (query.ToLower().Contains("www.youtube.com/watch?v="))
                {
                    bool found = false;
                    foreach (var vid in search.Tracks)
                    {
                        if (vid.Id.ToLower() == videoId)
                        {
                            track = vid;
                            found = true;
                            break;
                        }
                    }
                    if (found == false)
                    {
                        track = search.Tracks.FirstOrDefault();
                    }
                }
                else
                {
                    track = search.Tracks.FirstOrDefault();
                }

                var player = lava.HasPlayer(context.Guild)
                    ? lava.GetPlayer(context.Guild)
                    : await lava.JoinAsync((context.User as IVoiceState).VoiceChannel, (ITextChannel)message.Channel);

                if (player.PlayerState == PlayerState.Playing)
                {
                    player.Queue.Enqueue(track);
                    DiscordFunctions.EmbedThis("Music", "Enqeued " + track.Title, "orange", context);
                }
                else
                {
                    await player.PlayAsync(track);

                    try
                    {
                        if (timestamp != string.Empty)
                        {
                            if (timestamp.ToLower().Contains("s"))
                            {
                                timestamp = timestamp.ToLower().Replace("s", "");
                            }
                            await player.SeekAsync(TimeSpan.FromSeconds(Convert.ToDouble(timestamp)));
                        }
                    }
                    catch { }
                    DiscordFunctions.EmbedThis("Music", "Playing " + track.Title, "green", context);
                }
                return(true);
            }
            else if (Validation.CheckCommand(message, "skip"))
            {
                var _player = lava.GetPlayer(context.Guild);
                if (_player is null || _player.Queue.Count is 0)
                {
                    DiscordFunctions.EmbedThis("Music", "Nothing in the queue", "orange", context);
                    return(true);
                }

                var oldTrack = _player.Track;
                await _player.SkipAsync();

                DiscordFunctions.EmbedThis("Music", "Skipped: " + oldTrack.Title + "\nNow Playing: " + _player.Track.Title, "orange", context);
                return(true);
            }
            else if (Validation.CheckCommand(message, "stop"))
            {
                var _player = lava.GetPlayer(context.Guild);
                if (_player == null)
                {
                    return(true);
                }

                await _player.StopAsync();

                DiscordFunctions.EmbedThis("Music", "Stopped player", "orange", context);
                return(true);
            }
            else if (Validation.CheckCommand(message, "volume"))
            {
                LavaPlayer _player;
                try
                {
                    _player = lava.GetPlayer(context.Guild);
                }
                catch
                {
                    DiscordFunctions.EmbedThis("Music", "Nothing is playing", "orange", context);
                    return(true);
                }
                if (string.IsNullOrWhiteSpace(message.Content.Replace("!volume", "")))
                {
                    DiscordFunctions.EmbedThis("Music", "Please use a number between 2- 150", "orange", context);
                    return(true);
                }
                var vol = Convert.ToUInt16(message.Content.Replace("!volume", "").Trim());
                if (vol > 150 || vol <= 2)
                {
                    DiscordFunctions.EmbedThis("Music", "Please use a number between 2- 150", "orange", context);
                    return(true);
                }

                await _player.UpdateVolumeAsync(vol);

                DiscordFunctions.EmbedThis("Music", "Volume set to: " + vol.ToString(), "green", context);
                return(true);
            }
            else if (Validation.CheckCommand(message, "pause"))
            {
                LavaPlayer _player;
                try
                {
                    _player = lava.GetPlayer(context.Guild);
                }
                catch
                {
                    DiscordFunctions.EmbedThis("Music", "Nothing is playing", "orange", context);
                    return(true);
                }
                if (_player.PlayerState != PlayerState.Paused)
                {
                    await _player.PauseAsync();

                    DiscordFunctions.EmbedThis("Music", "Player is Paused", "orange", context);
                    return(true);
                }
                else
                {
                    await _player.ResumeAsync();

                    DiscordFunctions.EmbedThis("Music", "Playback Resumed", "green", context);
                    return(true);
                }
            }
            else if (Validation.CheckCommand(message, "resume"))
            {
                LavaPlayer _player;
                try
                {
                    _player = lava.GetPlayer(context.Guild);
                }
                catch
                {
                    DiscordFunctions.EmbedThis("Music", "Nothing is playing", "orange", context);
                    return(true);
                }
                if (_player.PlayerState != PlayerState.Paused)
                {
                    await _player.ResumeAsync();

                    DiscordFunctions.EmbedThis("Music", "Playback Resumed", "green", context);
                    return(true);
                }
                else
                {
                    DiscordFunctions.EmbedThis("Music", "Playback is not paused", "orange", context);
                    return(true);
                }
            }
            else if (Validation.CheckCommand(message, "join"))
            {
                var user = context.User as SocketGuildUser;
                if (user.VoiceChannel is null)
                {
                    DiscordFunctions.EmbedThis("Music", "You need to connect to a voice channel", "red", context);
                    return(true);
                }
                else
                {
                    LavaPlayer _player;
                    try
                    {
                        _player = lava.GetPlayer(context.Guild);
                        DiscordFunctions.EmbedThis("Music", "Bot is already in a channel", "red", context);
                        return(true);
                    }
                    catch
                    {
                        await lava.JoinAsync((context.User as IVoiceState).VoiceChannel, (ITextChannel)message.Channel);

                        return(true);
                    }
                }
            }
            else if (Validation.CheckCommand(message, "leave"))
            {
                var user = context.User as SocketGuildUser;
                if (user.VoiceChannel is null)
                {
                    DiscordFunctions.EmbedThis("Music", "Please join the channel the bot is in to make it leave", "red", context);
                    return(true);
                }
                else
                {
                    LavaPlayer _player;
                    try
                    {
                        _player = lava.GetPlayer(context.Guild);
                    }
                    catch
                    {
                        DiscordFunctions.EmbedThis("Music", "Please join the channel the bot is in to make it leave", "red", context);
                        return(true);
                    }
                    if (_player.VoiceChannel == user.VoiceChannel)
                    {
                        await lava.LeaveAsync((context.User as IVoiceState).VoiceChannel);
                    }
                    else
                    {
                        DiscordFunctions.EmbedThis("Music", "Please join the channel the bot is in to make it leave", "red", context);
                        return(true);
                    }
                }
            }
            return(false);
        }
Exemplo n.º 29
0
        public async Task PlayAsync([Remainder] string searchQuery)
        {
            if (string.IsNullOrWhiteSpace(searchQuery))
            {
                var embed = new EmbedBuilder()
                            .WithColor(new Color(255, 255, 255))
                            .AddField("Giib me da title retard!", "");

                await ReplyAsync(embed : embed.Build());

                return;
            }

            if (!_lavaNode.HasPlayer(Context.Guild))
            {
                var embed = new EmbedBuilder()
                            .WithColor(new Color(255, 255, 255))
                            .AddField("LET ME IN DA VOICE CHANNEL YUO MORON!", "");
                await ReplyAsync(embed : embed.Build());

                return;
            }

            var queries = searchQuery.Split(' ');

            foreach (var query in queries)
            {
                var searchResponse = await _lavaNode.SearchYouTubeAsync(query);

                if (query.Contains("https"))
                {
                    searchResponse = await _lavaNode.SearchAsync(SearchType.Direct, query);
                }

                else
                {
                    searchResponse = await _lavaNode.SearchYouTubeAsync(query);
                }


                if (searchResponse.Status == SearchStatus.LoadFailed ||
                    searchResponse.Status == SearchStatus.NoMatches)
                {
                    var em = new EmbedBuilder()
                             .WithColor(new Color(255, 255, 255))
                             .AddField("Sumimasen master pero no consejos encotro", query, true);

                    await ReplyAsync(embed : em.Build());

                    return;
                }

                var player = _lavaNode.GetPlayer(Context.Guild);

                if (player.PlayerState == PlayerState.Playing || player.PlayerState == PlayerState.Paused)
                {
                    if (!string.IsNullOrWhiteSpace(searchResponse.Playlist.Name))
                    {
                        foreach (var track in searchResponse.Tracks)
                        {
                            player.Queue.Enqueue(track);
                        }

                        var emb = new EmbedBuilder()
                                  .WithColor(new Color(255, 255, 255))
                                  .AddField("Enqueued:", $"{searchResponse.Tracks.Count} tracks", true);

                        await ReplyAsync(embed : emb.Build());
                    }
                    else
                    {
                        var track = searchResponse.Tracks.ElementAt(0);
                        player.Queue.Enqueue(track);
                        var embeded = new EmbedBuilder()
                                      .WithColor(new Color(255, 255, 255))
                                      .AddField("Enqueued:", track.Title, true);
                        await ReplyAsync(embed : embeded.Build());
                    }
                }
                else
                {
                    var track = searchResponse.Tracks.ElementAt(0);

                    if (!string.IsNullOrWhiteSpace(searchResponse.Playlist.Name))
                    {
                        for (var i = 0; i < searchResponse.Tracks.Count; i++)
                        {
                            if (i == 0)
                            {
                                await player.PlayAsync(track);

                                var Embed = new EmbedBuilder()
                                            .WithColor(new Color(255, 255, 255))
                                            .AddField("Now Playing", track.Title);
                                await ReplyAsync(embed : Embed.Build());
                            }
                            else
                            {
                                player.Queue.Enqueue(searchResponse.Tracks.ElementAt(i));
                            }
                        }

                        var embed = new EmbedBuilder()
                                    .WithColor(new Color(255, 255, 255))
                                    .AddField("", $"Enqueued {searchResponse.Tracks.Count} tracks");


                        await ReplyAsync(embed : embed.Build());
                    }
                    else
                    {
                        await player.PlayAsync(track);

                        var eb = new EmbedBuilder()
                                 .WithColor(new Color(255, 255, 255))
                                 .AddField("Now playing: ", track.Title, true)
                                 .Build();

                        await ReplyAsync(embed : eb);
                    }
                }
            }
            _lavaNode.OnTrackEnded     += OnTrackEnded;
            _lavaNode.OnTrackStuck     += OnTruckStuck;
            _lavaNode.OnTrackException += OnTruckException;
        }
Exemplo n.º 30
0
        /// <summary>Plays the requested song or adds it to the queue.
        /// <para>It also joins the voice channel if the bot isn't already joined.</para>
        /// </summary>
        public async Task PlayAsync(SocketCommandContext context, string query)
        {
            var user  = (SocketGuildUser)context.User;
            var guild = context.Guild;

            //Check If User Is Connected To Voice channel.
            if (user.VoiceChannel == null)
            {
                await context.Channel.SendMessageAsync(
                    embed : CustomFormats.CreateErrorEmbed("You must be connected to a voice channel!"));

                return;
            }

            //Check the guild has a player available.
            if (!_lavaNode.HasPlayer(guild))
            {
                //If it doesn't, then it means the bot isn't connected to a voice channel,
                //so we make the bot join a voice channel in order for play command to work
                var voiceState  = (IVoiceState)context.User;
                var textChannel = (ITextChannel)context.Channel;
                await _lavaNode.JoinAsync(voiceState.VoiceChannel, textChannel);
            }

            try
            {
                //Get the player for that guild.
                var player = _lavaNode.GetPlayer(guild);

                LavaTrack track;

                //Find The Youtube Track the User requested.
                var search = Uri.IsWellFormedUriString(query, UriKind.Absolute) ?
                             await _lavaNode.SearchAsync(query)
                    : await _lavaNode.SearchYouTubeAsync(query);

                //If we couldn't find anything, tell the user.
                if (search.LoadStatus == LoadStatus.NoMatches)
                {
                    await context.Channel.SendMessageAsync(
                        embed : CustomFormats.CreateErrorEmbed($"No results found for {query}."));

                    return;
                }

                if (search.LoadStatus == LoadStatus.LoadFailed)
                {
                    await context.Channel.SendMessageAsync(embed : CustomFormats.CreateErrorEmbed("**Failed to load song!**"));

                    return;
                }

                //If results derive from search results (ex: ytsearch: some song)
                if (search.LoadStatus == LoadStatus.SearchResult)
                {
                    //Then load the first track of the search results
                    track = search.Tracks[0];

                    //If the Bot is already playing music, or if it is paused but still has music in the playlist, Add the requested track to the queue.
                    if (player.Track != null && (player.PlayerState is PlayerState.Playing || player.PlayerState is PlayerState.Paused))
                    {
                        player.Queue.Enqueue(track);
                        await player.TextChannel.SendMessageAsync(embed : CustomFormats.CreateBasicEmbed("Track queued",
                                                                                                         $"**{track.Title}** has been added to queue. [{context.User.Mention}]\nPosition in queue: `{player.Queue.Count}`", Color.Blue));

                        return;
                    }

                    //Player was not playing anything, so lets play the requested track.
                    await player.PlayAsync(track);

                    return;
                }

                //If results derive from a playlist,
                //If the Bot is already playing music, or if it is paused but still has music in the playlist
                if (player.Track != null && (player.PlayerState is PlayerState.Playing || player.PlayerState is PlayerState.Paused))
                {
                    //Then add all the playlist songs to the queue
                    for (int i = 0; i < search.Tracks.Count; i++)
                    {
                        track = search.Tracks.ElementAt(i);
                        player.Queue.Enqueue(track);
                    }

                    //And send a message saying that X tracks have been added to queue
                    await context.Channel.SendMessageAsync(embed : CustomFormats.CreateBasicEmbed("Tracks queued",
                                                                                                  $"**{search.Tracks.Count} tracks** have been added to queue.",
                                                                                                  Color.Blue));

                    return;
                }

                //If the player isn't playing anything
                //Then add all the songs EXCLUDING the first one, because we will play that one next
                for (int i = 1; i < search.Tracks.Count; i++)
                {
                    track = search.Tracks.ElementAt(i);
                    player.Queue.Enqueue(track);
                }

                //After adding every song except the first, we retrieve the first track
                track = search.Tracks[0];

                //And ask the player to play it
                await player.PlayAsync(track);

                //If there is more than 1 song on search results (playlist) then say that we added every track in the playlist to the queue
                if (search.Tracks.Count - 1 > 0) //-1 because there will always be at least 1 song
                {
                    //Send a message saying that X other tracks have been added to queue
                    await context.Channel.SendMessageAsync(embed : CustomFormats.CreateBasicEmbed("",
                                                                                                  $"{search.Tracks.Count - 1} tracks have been added to queue.", Color.Blue));
                }
            }
            //If after all the checks we did, something still goes wrong. Tell the user about it so they can report it back to us.
            catch (Exception ex)
            {
                await context.Channel.SendMessageAsync(embed : CustomFormats.CreateErrorEmbed(ex.Message));
            }
        }