예제 #1
0
파일: MusicUtil.cs 프로젝트: ta1H3n/Namiko
        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
            });
        }
예제 #2
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();
        });
    }
예제 #3
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);
        }
예제 #4
0
        public async Task <string> PlayQuery(SocketUser username, IGuild guild, IVoiceChannel voiceChannel,
                                             ITextChannel textChannel, string query)
        {
            try
            {
                var search = Uri.IsWellFormedUriString(query, UriKind.Absolute) ? await lavaNode.SearchAsync(Victoria.Responses.Search.SearchType.Direct, query)
                    : await lavaNode.SearchAsync(Victoria.Responses.Search.SearchType.YouTube, query);

                if (search.Status == Victoria.Responses.Search.SearchStatus.LoadFailed)
                {
                    return($"Sorry, failed to load query.");
                }

                LavaTrack track = null;
                track = search.Tracks.FirstOrDefault();

                if (track == null)
                {
                    return("Sorry, can't find the track.");
                }

                var player = lavaNode.HasPlayer(guild) ? lavaNode.GetPlayer(guild) : await lavaNode.JoinAsync(voiceChannel, textChannel);

                if (!guildInfo.TryGetValue(guild, out var g))
                {
                    guildInfo.TryAdd(guild, new DJGuildInfo(voiceChannel));
                }

                DJGuildInfo currentGuild = null;
                guildInfo.TryGetValue(guild, out currentGuild);

                currentGuild.Enqueue(username, track);
                if (player.PlayerState == Victoria.Enums.PlayerState.Playing)
                {
                    return($"**Enqueued** `{track.Title}`");
                }
                else
                {
                    currentGuild.PlayNext();
                    await player.PlayAsync(currentGuild.currentlyPlaying.track);

                    return($"**Playing** 🎶 `{track.Title}`");
                }
            }catch (Exception e)
            {
                return($"Error playing query: `{e.Message}`.");
            }
        }
예제 #5
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));
        }
예제 #6
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}");
            }
        }
예제 #7
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));
            }
        }
예제 #8
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());
                }
            }
        }
예제 #9
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);
        }
예제 #10
0
        public async Task PlayAsync([Remainder] string query)
        {
            //Check if query is empty
            if (string.IsNullOrWhiteSpace(query))
            {
                await ReplyAsync("Please provide search terms.");

                return;
            }

            var voiceState = Context.User as IVoiceState;

            //Check if user is connected to voice room
            if (voiceState.VoiceChannel == null)
            {
                await ReplyAsync("You're not connected to the same voice channel as bot");

                return;
            }

            //Check if bot is already connected to voice room if not - connect
            if (!_lavaNode.TryGetPlayer(Context.Guild, out var player))
            {
                try
                {
                    await _lavaNode.JoinAsync(voiceState.VoiceChannel, Context.Channel as ITextChannel);
                    await ReplyAsync($"Joined {voiceState.VoiceChannel.Name}!");

                    player = _lavaNode.GetPlayer(Context.Guild);
                }
                catch
                {
                    await ReplyAsync("Make sure you're in the voice channel before you use that command");

                    return;
                }
            }

            //Check if the ID of user's room is the same as bot's
            if (voiceState.VoiceChannel != player.VoiceChannel)
            {
                await ReplyAsync("You have to be in the same voice channel as bot to play songs");

                return;
            }

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

            if (searchResponse.LoadStatus == LoadStatus.LoadFailed ||
                searchResponse.LoadStatus == LoadStatus.NoMatches)
            {
                await ReplyAsync($"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.");
                }
                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);

                            var emb = new EmbedBuilder();
                            emb.WithColor(Color.DarkPurple);
                            emb.WithTitle("Now playing");
                            emb.WithDescription(track.Title);
                            emb.AddField("Duration", track.Duration.ToString(@"hh\:mm\:ss"));
                            emb.AddField("Author", track.Author);
                            emb.WithThumbnailUrl(track.FetchArtworkAsync().GetAwaiter().GetResult());
                            await ReplyAsync("", false, emb.Build());
                        }
                        else
                        {
                            player.Queue.Enqueue(searchResponse.Tracks[i]);
                        }
                    }

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

                    var emb = new EmbedBuilder();
                    emb.WithColor(Color.DarkPurple);
                    emb.WithTitle("Now playing");
                    emb.WithDescription(track.Title);
                    emb.AddField("Duration", track.Duration.ToString(@"hh\:mm\:ss"));
                    emb.AddField("Author", track.Author);
                    emb.WithThumbnailUrl(track.FetchArtworkAsync().GetAwaiter().GetResult());
                    await ReplyAsync("", false, emb.Build());
                }
            }
        }
예제 #11
0
        private async Task UserVoiceStateUpdated(SocketUser socketUser, SocketVoiceState oldSocketVoiceState, SocketVoiceState newSocketVoiceState)
        {
            if (socketUser.IsBot)
            {
                return;
            }

            var member = await _db.ServerMembers.FirstOrDefaultAsync(x => x.DiscordId == socketUser.Id.ToString());

            if (member?.IntroSong == null || socketUser.Id == _lastRequestBy)
            {
                return;
            }

            if (oldSocketVoiceState.VoiceChannel == null)
            {
                Console.WriteLine($"User {socketUser.Username} entered the server!");

                if (_lavaNode.HasPlayer(newSocketVoiceState.VoiceChannel.Guild))
                {
                    await _lavaNode.MoveChannelAsync(newSocketVoiceState.VoiceChannel);
                }
                else
                {
                    await _audioService.JoinChannel(socketUser as IVoiceState, newSocketVoiceState.VoiceChannel.Guild);
                }

                var player = _lavaNode.GetPlayer(newSocketVoiceState.VoiceChannel.Guild);
                await player.UpdateVolumeAsync(7);

                var searchResponse = await _lavaNode.SearchAsync(member.IntroSong.Url);

                var track    = searchResponse.Tracks[0];
                var timespan = member?.IntroSongSeek ?? TimeSpan.Zero;
                await player.PlayAsync(track);

                if (member?.IntroSongSeek.HasValue ?? false)
                {
                    await player.SeekAsync(member.IntroSongSeek);
                }

                _lastRequestBy = socketUser.Id;

                if (_cancelIntro != null && !_cancelIntro.IsCancellationRequested)
                {
                    _cancelIntro.Cancel();
                }

                _cancelIntro = new CancellationTokenSource();
                var cancellationToken = _cancelIntro.Token;

                Task.Run(async() =>
                {
                    await Task.Delay(TimeSpan.FromSeconds(30), cancellationToken);

                    if (cancellationToken.IsCancellationRequested)
                    {
                        return;
                    }

                    if (player.PlayerState != PlayerState.Disconnected && socketUser.Id == _lastRequestBy)
                    {
                        await _lavaNode.LeaveAsync(newSocketVoiceState.VoiceChannel);
                    }
                }, cancellationToken);
            }

            return;
        }
예제 #12
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);
                }
            }
        }
예제 #13
0
        public async Task PlayAsync([Remainder] string searchQuery)
        {
            if (string.IsNullOrWhiteSpace(searchQuery))
            {
                await ReplyAsync("Please provide search terms.");

                return;
            }

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

                return;
            }

            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 ReplyAsync($"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.");
                    }
                    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}");
                    }
                }
            }
        }
예제 #14
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();
            }
        }
예제 #15
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);
                        }
                    }
                }
            }
        }
예제 #16
0
        public async Task <string> PlayAsync(string query, IGuild guild)
        {
            SetPlayer(guild);
            SearchResponse results;

            if (Uri.IsWellFormedUriString(query, UriKind.Absolute))
            {
                Util.Log("MUSIC: Link Detected");
                results = await _lavaNode.SearchAsync(query);
            }
            else
            {
                Util.Log($"MUSIC: Youtube search: {query}");
                results = await _lavaNode.SearchYouTubeAsync(query);
            }

            switch (results.LoadStatus)
            {
            case LoadStatus.NoMatches:
                return("No matches found. - " + query);

            case LoadStatus.LoadFailed:
                Util.Log($"MUSIC: LOAD FAILED: {results.Exception.Message}");
                return("Load Failed!");

            case LoadStatus.SearchResult:
            case LoadStatus.TrackLoaded:
                var track = results.Tracks.FirstOrDefault();
                if (track is null)
                {
                    return("Load Failed!");
                }

                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}*\n{track.Url}");
                }

            case LoadStatus.PlaylistLoaded:
                foreach (var t in results.Tracks)
                {
                    if (_player.PlayerState != PlayerState.Playing)
                    {
                        await _player.PlayAsync(t);

                        await _player.ResumeAsync();

                        continue;
                    }
                    _player.Queue.Enqueue(t);
                }

                return($"*{results.Playlist.Name}* loaded with {results.Tracks.Count} songs!");

            default:
                return("Something happened, but I'm not gonna tell you what! HAHA!");
            }
        }
예제 #17
0
        public async Task PlayAsync([Remainder] string query)
        {
            if (string.IsNullOrWhiteSpace(query))
            {
                await ReplyAsync("Please provide search terms.");

                return;
            }

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

                return;
            }

            var searchResponse = await _lavaNode.SearchAsync(query);

            if (searchResponse.LoadStatus == LoadStatus.LoadFailed ||
                searchResponse.LoadStatus == LoadStatus.NoMatches)
            {
                await ReplyAsync($"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($"В очереди {searchResponse.Tracks.Count} треков.");
                }
                else
                {
                    var track = searchResponse.Tracks[0];
                    player.Queue.Enqueue(track);
                    await ReplyAsync($"Добавлен в очередь: {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);

                            #region Embed
                            var embed = new EmbedBuilder()
                                        .WithAuthor(Context.User.Username, Context.User.GetAvatarUrl())
                                        .WithTitle(player.Track.Title)
                                        .WithUrl(player.Track.Url)
                                        .WithColor(Color.Orange)
                                        .WithCurrentTimestamp()
                                        .WithImageUrl(getYouTubeThumbnail(query))
                                        //
                                        .Build();
                            #endregion

                            await ReplyAsync(embed : embed);
                        }
                        else
                        {
                            player.Queue.Enqueue(searchResponse.Tracks[i]);
                        }
                    }

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

                    #region Embed
                    var embed = new EmbedBuilder()
                                .WithAuthor(Context.User.Username, Context.User.GetAvatarUrl())
                                .WithTitle(player.Track.Title)
                                .WithUrl(player.Track.Url)
                                .WithColor(Color.Orange)
                                .WithCurrentTimestamp()
                                .WithImageUrl(getYouTubeThumbnail(query))
                                //
                                .Build();
                    #endregion

                    await ReplyAsync(embed : embed);
                }
            }
        }
예제 #18
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;
        }
예제 #19
0
파일: MusicService.cs 프로젝트: snoww/roki
        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);
        }
예제 #20
0
파일: Search.cs 프로젝트: kaguyabot/Kaguya
        /// <summary>
        ///     Searches the specified <see cref="SearchProvider" /> for the provided <see cref="query" />.
        ///     This method also adds the song to the guild's player queue and will even join the user's voice
        ///     channel automatically.
        /// </summary>
        /// <param name="context"></param>
        /// <param name="query">The song to search for, user input.</param>
        /// <param name="playFirst"></param>
        /// <param name="provider"></param>
        /// <returns></returns>
        public async Task <ReactionCallbackData> SearchAndPlayAsync(ShardedCommandContext context,
                                                                    string query,
                                                                    bool playFirst          = false,
                                                                    SearchProvider provider = SearchProvider.YOU_TUBE)
        {
            User user = await DatabaseQueries.GetOrCreateUserAsync(context.User.Id);

            Server server = await DatabaseQueries.GetOrCreateServerAsync(context.Guild.Id);

            LavaNode           node  = ConfigProperties.LavaNode;
            SocketVoiceChannel curVc = (context.User as SocketGuildUser).VoiceChannel;

            await ConsoleLogger.LogAsync($"Found node and voice channel for guild {context.Guild.Id}.", LogLvl.TRACE);

            if (curVc == null)
            {
                await context.Channel.SendMessageAsync($"{context.User.Mention} You must be in a voice " +
                                                       "channel to use this command.");

                await ConsoleLogger.LogAsync("User was not in voice channel, cancelling music search operation.", LogLvl.TRACE);

                return(null);
            }

            SearchResponse result = provider switch
            {
                SearchProvider.YOU_TUBE => await node.SearchYouTubeAsync(query),
                SearchProvider.SOUNDCLOUD => await node.SearchSoundCloudAsync(query),
                _ => await node.SearchAsync(query)
            };

            if (provider == SearchProvider.TWITCH)
            {
                const string PROVIDER_URL = "www.twitch.tv";
                string       errorString  = "Your search returned no results. Ensure you are only " +
                                            "typing the name of the streamer who you want to watch or a direct link to their stream.\n\n" +
                                            "Note: The streamer must be live for this feature to work.";

                if (!query.ToLower().Contains(PROVIDER_URL))
                {
                    result = await node.SearchAsync($"https://{PROVIDER_URL}/{query}");

                    if (result.Tracks.Count == 0)
                    {
                        await context.Channel.SendBasicErrorEmbedAsync(errorString);

                        await ConsoleLogger.LogAsync($"No livestream found for search {query} in guild {context.Guild.Id}.", LogLvl.TRACE);

                        return(null);
                    }
                }
                else
                {
                    if ((await node.SearchAsync($"https://{PROVIDER_URL}/{query.Split('\\').Last()}")).Tracks.Count == 0 &&
                        (await node.SearchAsync(query)).Tracks.Count == 0)
                    {
                        await context.Channel.SendBasicErrorEmbedAsync(errorString);

                        await ConsoleLogger.LogAsync($"No livestream found for search {query} in guild {context.Guild.Id}.", LogLvl.TRACE);

                        return(null);
                    }
                }
            }

            var tracks = new List <LavaTrack>();

            if (user.IsPremium || server.IsPremium)
            {
                if (result.Tracks.Any())
                {
                    tracks.AddRange(result.Tracks);
                }
            }
            else
            {
                // Limit track duration to 10 minutes for non-premium servers/users.
                if (result.Tracks.Any())
                {
                    tracks.AddRange(result.Tracks.Where(x => x.Duration.TotalMinutes < 10).ToList());
                }
            }

            if (!tracks.Any())
            {
                string suppString = user.IsPremium
                    ? ""
                    : "If you are " +
                                    $"not a [Kaguya Premium Subscriber]({ConfigProperties.KAGUYA_STORE_URL}), " +
                                    "you are only limited to playing songs less than `10 minutes` in duration.";

                await context.Channel.SendBasicErrorEmbedAsync($"Your requested search returned no results. {suppString}");

                await ConsoleLogger.LogAsync("Search request returned no usable " +
                                             $"results in guild {Context.Guild.Id} for query {query}", LogLvl.TRACE);
            }

            var fields    = new List <EmbedFieldBuilder>();
            var callbacks = new List <(IEmote, Func <SocketCommandContext, SocketReaction, Task>)>();

            Emoji[] emojiNums = GlobalProperties.EmojisOneThroughNine();

            LavaPlayer player = node.HasPlayer(context.Guild)
                ? node.GetPlayer(context.Guild)
                : await node.JoinAsync(curVc);

            await ConsoleLogger.LogAsync($"Player found for guild {context.Guild.Id}. Connected to voice channel.", LogLvl.TRACE);

            #region If the track is a livestream:
            if (tracks.Any(x => x.IsStream))
            {
                LavaTrack trackSel   = tracks.First(x => x.IsStream); // Gathers the first stream from the collection.
                string    twitchName = (await ConfigProperties.TwitchApi.V5.Users.GetUserByNameAsync(trackSel.Author)).Matches[0].DisplayName;
                string    playString = player.PlayerState == PlayerState.Playing
                    ? $"Queued stream into position {player.Queue.Count}."
                    : $"Now playing `{twitchName}`'s stream.";

                if (player.PlayerState == PlayerState.Playing)
                {
                    try
                    {
                        player.Queue.Enqueue(trackSel);
                        await ConsoleLogger.LogAsync($"Enqueued livestream {trackSel.Title} in guild {context.Guild.Id}",
                                                     LogLvl.TRACE);
                    }
                    catch (Exception e)
                    {
                        await ConsoleLogger.LogAsync("An exception was thrown when trying to enqueue the livestream " +
                                                     $"{trackSel.Title} in guild {Context.Guild.Id}.\n" +
                                                     $"Exception Message: {e.Message}\n" +
                                                     $"Stack Trace: {e.StackTrace}", LogLvl.WARN);
                    }
                }
                else
                {
                    try
                    {
                        await player.PlayAsync(trackSel);

                        await ConsoleLogger.LogAsync($"Playing livestream {trackSel.Title} in guild {context.Guild.Id}",
                                                     LogLvl.TRACE);
                    }
                    catch (Exception e)
                    {
                        await ConsoleLogger.LogAsync("An exception was thrown when trying to play track " +
                                                     $"{trackSel.Title} in guild {Context.Guild.Id}.\n" +
                                                     $"Exception Message: {e.Message}\n" +
                                                     $"Stack Trace: {e.StackTrace}", LogLvl.WARN);
                    }
                }

                var field = new EmbedFieldBuilder
                {
                    Name  = $"`{twitchName}`'s Stream",
                    Value = $"{playString}\n" // We get rid of backticks for formatting.
                };

                var embed = new KaguyaEmbedBuilder
                {
                    Fields = new List <EmbedFieldBuilder>
                    {
                        field
                    }
                };

                await context.Channel.SendEmbedAsync(embed);

                return(null);
            }
            #endregion

            #region If we have chosen to only play the default track (via $play).
            if (playFirst && tracks.Any())
            {
                LavaTrack trackSel = tracks[0];
                var       field    = new EmbedFieldBuilder
                {
                    Name  = "Track #1.",
                    Value = $"Title: `{trackSel.Title.Replace("`", "")}`\n" + // We get rid of backticks for formatting.
                            $"Duration: `{trackSel.Duration.Humanize(minUnit: TimeUnit.Second, maxUnit: TimeUnit.Hour, precision: 3)}`\n" +
                            $"Uploader: `{trackSel.Author}`"
                };

                string playString = player.PlayerState == PlayerState.Playing && !player.Track.IsStream
                    ? $"Queued track #1 into position {player.Queue.Count + 1}."
                    : "Now playing track #1.";

                if (player.PlayerState == PlayerState.Playing)
                {
                    if (player.Queue.Count() == 50 && !server.IsPremium)
                    {
                        await ConsoleLogger.LogAsync($"Queue is full in {context.Guild.Id}, sending error.", LogLvl.TRACE);
                        await SendBasicErrorEmbedAsync("Your queue is full! `50 songs` is the maximum " +
                                                       $"for non [Kaguya Premium]({ConfigProperties.KAGUYA_STORE_URL}) " +
                                                       "servers.");
                    }
                    else
                    {
                        player.Queue.Enqueue(trackSel);
                        await ConsoleLogger.LogAsync($"Enqueued track {trackSel.Title} in guild {context.Guild.Id}.", LogLvl.TRACE);

                        if (player.Track.IsStream)
                        {
                            await player.SkipAsync();

                            await ConsoleLogger.LogAsync($"Skipped livestream to play incoming track in guild {context.Guild.Id}.", LogLvl.TRACE);
                        }
                    }
                }
                else
                {
                    try
                    {
                        await player.PlayAsync(trackSel);

                        await ConsoleLogger.LogAsync($"Playing track {trackSel.Title} in guild {context.Guild.Id}",
                                                     LogLvl.TRACE);
                    }
                    catch (Exception e)
                    {
                        await ConsoleLogger.LogAsync("An exception was thrown when trying to play track " +
                                                     $"{trackSel.Title} in guild {Context.Guild.Id}.\n" +
                                                     $"Exception Message: {e.Message}\n" +
                                                     $"Stack Trace: {e.StackTrace}", LogLvl.WARN);
                    }
                }

                if (player.Volume == 0 && player.PlayerState == PlayerState.Playing)
                {
                    await player.UpdateVolumeAsync(75); // Sets the volume back to default if it is muted.

                    await ConsoleLogger.LogAsync($"Automatically set player volume to 75 in guild {context.Guild.Id}.", LogLvl.TRACE);
                }

                var embed = new KaguyaEmbedBuilder
                {
                    Title        = $"Kaguya Music {Centvrio.Emoji.Music.Notes}",
                    Description  = playString,
                    ThumbnailUrl = await trackSel.FetchArtworkAsync(),
                    Fields       = new List <EmbedFieldBuilder>
                    {
                        field
                    }
                };

                await SendEmbedAsync(embed, context);

                return(null);
            }
            #endregion

            int h = tracks.Count;
            for (int i = 0; i < (h < 7 ? h : 7); i++)
            {
                int       i1       = i;
                LavaTrack trackSel = tracks[i];
                var       field    = new EmbedFieldBuilder
                {
                    Name  = $"Track {i1 + 1}.",
                    Value = $"Title: `{trackSel.Title.Replace("`", "")}`\n" + // We get rid of backticks for formatting.
                            $"Duration: `{trackSel.Duration.Humanize(minUnit: TimeUnit.Second, maxUnit: TimeUnit.Hour, precision: 3)}`\n" +
                            $"Uploader: `{trackSel.Author}`"
                };

                fields.Add(field);
                callbacks.Add((emojiNums[i], async(c, r) =>
                {
                    string playString = player.PlayerState == PlayerState.Playing && !player.Track.IsStream
                                ? $"Queued track #{i1 + 1} into position {player.Queue.Count + 1}."
                                : $"Now playing track #{i1 + 1}.";

                    if (player.PlayerState == PlayerState.Playing)
                    {
                        if (player.Queue.Count() == 50 && !server.IsPremium)
                        {
                            await ConsoleLogger.LogAsync($"Queue was full in guild {context.Guild.Id}. Sending error message.", LogLvl.TRACE);
                            await SendBasicErrorEmbedAsync("Your queue is full! `50 songs` is the maximum " +
                                                           $"for non [Kaguya Premium]({ConfigProperties.KAGUYA_STORE_URL}) " +
                                                           "servers.");

                            return;
                        }

                        player.Queue.Enqueue(trackSel);
                        await ConsoleLogger.LogAsync($"Enqueued track {trackSel} in guild {context.Guild.Id}", LogLvl.TRACE);

                        if (player.Track.IsStream)
                        {
                            await player.SkipAsync();
                            await ConsoleLogger.LogAsync("Automatically skipped livestream to play" +
                                                         $" incoming track in guild {context.Guild.Id}", LogLvl.TRACE);
                        }
                    }
                    else
                    {
                        try
                        {
                            await player.PlayAsync(trackSel);
                            await ConsoleLogger.LogAsync($"Playing track {trackSel.Title} in guild {context.Guild.Id}",
                                                         LogLvl.TRACE);
                        }
                        catch (Exception e)
                        {
                            await ConsoleLogger.LogAsync("An exception was thrown when trying to play track " +
                                                         $"{trackSel.Title} in guild {Context.Guild.Id}.\n" +
                                                         $"Exception Message: {e.Message}\n" +
                                                         $"Stack Trace: {e.StackTrace}", LogLvl.WARN);
                        }
                    }

                    if (player.Volume == 0 && player.PlayerState == PlayerState.Playing)
                    {
                        await player.UpdateVolumeAsync(75);         // Sets the volume back to default if it is muted.
                        await ConsoleLogger.LogAsync($"Automatically set volume to 75 in guild {context.Guild.Id}", LogLvl.TRACE);
                    }

                    var embed = new KaguyaEmbedBuilder
                    {
                        Title = $"Kaguya Music {Centvrio.Emoji.Music.Notes}",
                        Description = playString,
                        ThumbnailUrl = await trackSel.FetchArtworkAsync(),
                        Fields = new List <EmbedFieldBuilder>
                        {
                            field
                        }
                    };

                    await SendEmbedAsync(embed);
                }
                               ));
            }

            callbacks.Add((GlobalProperties.NoEntryEmoji(), async(c, r) =>
            {
                await c.Message.DeleteAsync();
                await r.Message.Value.DeleteAsync();
            }));

            string s = tracks.Count == 1 ? "" : "s";
            var    songDisplayEmbed = new KaguyaEmbedBuilder
            {
                Title       = "Kaguya Music Search Results",
                Description = $" I found {tracks.Count} track{s} from {provider}, " +
                              $"{(tracks.Count > 5 ? "but here are the top 5" : "here they are")}. " +
                              "Please select a track to play.",
                Fields = fields
            };

            var data = new ReactionCallbackData("", songDisplayEmbed.Build(), false, false,
                                                TimeSpan.FromSeconds(60));

            data.SetCallbacks(callbacks);

            return(data);
        }
    }
예제 #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");
                }
            }
        }
예제 #22
0
        public async Task PlayAsync([Remainder] string query)
        {
            if (string.IsNullOrWhiteSpace(query))
            {
                await ReplyAsync("Please provide search terms.");

                return;
            }

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

                return;
            }

            SearchResponse searchResponse;

            try
            {
                searchResponse = await _lavaNode.SearchAsync(query);
            }
            catch (Exception ex)
            {
                await this.LogAsync(new LogMessage(LogSeverity.Error, "Music Module", ex.Message));
                await ReplyAsync("Something happened that i can't play the music!");

                return;
            }

            if (searchResponse.LoadStatus == LoadStatus.LoadFailed ||
                searchResponse.LoadStatus == LoadStatus.NoMatches)
            {
                await ReplyAsync($"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.");
                }
                else
                {
                    var track = searchResponse.Tracks[0];
                    player.Queue.Enqueue(track);
                    await ReplyAsync($"Enqueued: {track.Title}");
                }
            }
            else
            {
                if (this.playList == null)
                {
                    this.playList = new Playlist();
                }

                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
                {
                    try
                    {
                        await player.PlayAsync(track);
                        await ReplyAsync($"Now Playing: {track.Title}");
                    }
                    catch (Exception ex)
                    {
                        await this.LogAsync(new LogMessage(LogSeverity.Error, "Music Module", ex.Message));
                        await ReplyAsync($"{track.Title} couldn't be played!");

                        return;
                    }
                }
            }
        }
예제 #23
0
    public async Task PlayAsync([Remainder] string searchQuery)
    {
        //if (Regex.IsMatch(searchQuery, @"^(spotify:|https:\/\/[a-z]+\.spotify\.com\/)")){
        if (Uri.IsWellFormedUriString(searchQuery, UriKind.Absolute) && searchQuery.Contains("spotify"))
        {
            searchQuery = await SpotifyToSearchQuery(searchQuery);
        }

        if (string.IsNullOrWhiteSpace(searchQuery))
        {
            await ReplyAsync("Please provide search terms.");

            return;
        }

        //Join the voice channel if not already in it
        if (!_lavaNode.HasPlayer(Context.Guild))
        {
            await JoinAsync();

            // Check if properly joined
            if (!_lavaNode.HasPlayer(Context.Guild))
            {
                return;
            }
        }


        var searchResponse = await _lavaNode.SearchAsync(Uri.IsWellFormedUriString(searchQuery, UriKind.Absolute)?SearchType.Direct : SearchType.YouTube, searchQuery);

        if (searchResponse.Status is SearchStatus.LoadFailed or SearchStatus.NoMatches)
        {
            await ReplyAsync($"I wasn't able to find anything for `{searchQuery}`.");

            return;
        }

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

        if (!string.IsNullOrWhiteSpace(searchResponse.Playlist.Name))
        {
            player.Queue.Enqueue(searchResponse.Tracks);
            await ReplyAsync($"Enqueued {searchResponse.Tracks.Count} songs.");
        }
        else
        {
            var track = searchResponse.Tracks.FirstOrDefault();
            player.Queue.Enqueue(track);

            await ReplyAsync($"Enqueued {track?.Title}");

            await _audioService.LogMusicToDB(track, Context);
        }

        if (player.PlayerState is PlayerState.Playing or PlayerState.Paused)
        {
            return;
        }

        player.Queue.TryDequeue(out var lavaTrack);
        await player.PlayAsync(x => {
            x.Track       = lavaTrack;
            x.ShouldPause = false;
        });
    }
예제 #24
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}`");
        }
예제 #25
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;
        }
예제 #26
0
파일: Music.cs 프로젝트: Jirubizu/MatsueNet
        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);
                }
            }
        }