Ejemplo n.º 1
0
        private static async Task QueuePlaylistAsync(ICommandContext ctx, LavaPlayer player, IReadOnlyCollection <LavaTrack> tracks)
        {
            await ctx.Channel.EmbedAsync(new EmbedBuilder().WithDynamicColor(ctx).WithDescription($"Queuing {tracks.Count} tracks...")).ConfigureAwait(false);

            foreach (LavaTrack track in tracks)
            {
                track.Queued = ctx.User as IGuildUser;
                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($"Queued {tracks.Count} tracks")
                .WithFooter($"🔉 {player.Volume}% | {ctx.User}{FormatAutoplayAndLoop(player)}");
                IUserMessage msg = await ctx.Channel.EmbedAsync(embed).ConfigureAwait(false);

                msg.DeleteAfter(10);
            }
            else
            {
                LinkedListNode <LavaTrack> track = player.Queue.First();
                await player.PlayAsync(track).ConfigureAwait(false);

                embed.WithAuthor($"Playing song, queued {tracks.Count} tracks", "https://i.imgur.com/fGNKX6x.png")
                .WithDescription($"{track.Value.PrettyTrack()}")
                .WithFooter(track.Value.PrettyFooter(player.Volume));
                await ctx.Channel.EmbedAsync(embed).ConfigureAwait(false);
            }
        }
Ejemplo n.º 2
0
        public async Task <MusicPlayer> GetOrCreatePlayer(ulong guildId, IVoiceChannel voiceCh, ITextChannel textCh)
        {
            string GetText(string text, params object[] replacements) =>
            _strings.GetText(text, _localization.GetCultureInfo(textCh.Guild), "Music".ToLowerInvariant(), replacements);

            if (voiceCh == null || voiceCh.Guild != textCh.Guild)
            {
                if (textCh != null)
                {
                    await textCh.SendErrorAsync(GetText("must_be_in_voice")).ConfigureAwait(false);
                }
                throw new NotInVoiceChannelException();
            }
            return(MusicPlayers.GetOrAdd(guildId, _ =>
            {
                var vol = GetDefaultVolume(guildId);
                if (!_musicSettings.TryGetValue(guildId, out var ms))
                {
                    ms = new MusicSettings();
                }

                var mp = new MusicPlayer(this, ms, _google, voiceCh, textCh, vol);

                IUserMessage playingMessage = null;
                IUserMessage lastFinishedMessage = null;

                mp.OnCompleted += async(s, song) =>
                {
                    try
                    {
                        lastFinishedMessage?.DeleteAfter(0);

                        try
                        {
                            lastFinishedMessage = await mp.OutputTextChannel.EmbedAsync(new EmbedBuilder().WithOkColor()
                                                                                        .WithAuthor(eab => eab.WithName(GetText("finished_song")).WithMusicIcon())
                                                                                        .WithDescription(song.PrettyName)
                                                                                        .WithFooter(ef => ef.WithText(song.PrettyInfo)))
                                                  .ConfigureAwait(false);
                        }
                        catch
                        {
                            // ignored
                        }

                        var(Index, Current) = mp.Current;
                        if (Current == null &&
                            !mp.RepeatCurrentSong &&
                            !mp.RepeatPlaylist &&
                            !mp.FairPlay &&
                            AutoDcServers.Contains(guildId))
                        {
                            await DestroyPlayer(guildId).ConfigureAwait(false);
                        }
                    }
                    catch
                    {
                        // ignored
                    }
                };
                mp.OnStarted += async(player, song) =>
                {
                    //try { await mp.UpdateSongDurationsAsync().ConfigureAwait(false); }
                    //catch
                    //{
                    //    // ignored
                    //}
                    var sender = player;
                    if (sender == null)
                    {
                        return;
                    }
                    try
                    {
                        playingMessage?.DeleteAfter(0);

                        playingMessage = await mp.OutputTextChannel.EmbedAsync(new EmbedBuilder().WithOkColor()
                                                                               .WithAuthor(eab => eab.WithName(GetText("playing_song", song.Index + 1)).WithMusicIcon())
                                                                               .WithDescription(song.Song.PrettyName)
                                                                               .WithFooter(ef => ef.WithText(mp.PrettyVolume + " | " + song.Song.PrettyInfo)))
                                         .ConfigureAwait(false);
                    }
                    catch
                    {
                        // ignored
                    }
                };
                mp.OnPauseChanged += async(player, paused) =>
                {
                    try
                    {
                        IUserMessage msg;
                        if (paused)
                        {
                            msg = await mp.OutputTextChannel.SendConfirmAsync(GetText("paused")).ConfigureAwait(false);
                        }
                        else
                        {
                            msg = await mp.OutputTextChannel.SendConfirmAsync(GetText("resumed")).ConfigureAwait(false);
                        }

                        msg?.DeleteAfter(10);
                    }
                    catch
                    {
                        // ignored
                    }
                };
                _log.Info("Done creating");
                return mp;
            }));
        }
Ejemplo n.º 3
0
        public static async Task QueueSong(IGuildUser queuer, ITextChannel textCh, IVoiceChannel voiceCh, string query, bool silent = false, MusicType musicType = MusicType.Normal)
        {
            if (voiceCh == null || voiceCh.Guild != textCh.Guild)
            {
                if (!silent)
                {
                    await textCh.SendErrorAsync($"💢 You need to be in a voice channel on this server.").ConfigureAwait(false);
                }
                throw new ArgumentNullException(nameof(voiceCh));
            }
            if (string.IsNullOrWhiteSpace(query) || query.Length < 3)
            {
                throw new ArgumentException("💢 Invalid query for queue song.", nameof(query));
            }

            var musicPlayer = MusicPlayers.GetOrAdd(textCh.Guild.Id, server =>
            {
                float vol = 1;// SpecificConfigurations.Default.Of(server.Id).DefaultMusicVolume;
                using (var uow = DbHandler.UnitOfWork())
                {
                    vol = uow.GuildConfigs.For(textCh.Guild.Id, set => set).DefaultMusicVolume;
                }
                var mp = new MusicPlayer(voiceCh, textCh, vol);
                IUserMessage playingMessage      = null;
                IUserMessage lastFinishedMessage = null;
                mp.OnCompleted += async(s, song) =>
                {
                    try
                    {
                        lastFinishedMessage?.DeleteAfter(0);

                        try
                        {
                            lastFinishedMessage = await mp.OutputTextChannel.EmbedAsync(new EmbedBuilder().WithOkColor()
                                                                                        .WithAuthor(eab => eab.WithName("Finished Song").WithMusicIcon())
                                                                                        .WithDescription(song.PrettyName)
                                                                                        .WithFooter(ef => ef.WithText(song.PrettyInfo)))
                                                  .ConfigureAwait(false);
                        }
                        catch
                        {
                            // ignored
                        }

                        if (mp.Autoplay && mp.Playlist.Count == 0 && song.SongInfo.ProviderType == MusicType.Normal)
                        {
                            var relatedVideos = (await NadekoBot.Google.GetRelatedVideosAsync(song.SongInfo.Query, 4)).ToList();
                            if (relatedVideos.Count > 0)
                            {
                                await QueueSong(await queuer.Guild.GetCurrentUserAsync(),
                                                textCh,
                                                voiceCh,
                                                relatedVideos[new NadekoRandom().Next(0, relatedVideos.Count)],
                                                true).ConfigureAwait(false);
                            }
                        }
                    }
                    catch { }
                };

                mp.OnStarted += async(player, song) =>
                {
                    try { await mp.UpdateSongDurationsAsync().ConfigureAwait(false); }
                    catch
                    {
                        // ignored
                    }
                    var sender = player as MusicPlayer;
                    if (sender == null)
                    {
                        return;
                    }
                    try
                    {
                        playingMessage?.DeleteAfter(0);

                        playingMessage = await mp.OutputTextChannel.EmbedAsync(new EmbedBuilder().WithOkColor()
                                                                               .WithAuthor(eab => eab.WithName("Playing Song").WithMusicIcon())
                                                                               .WithDescription(song.PrettyName)
                                                                               .WithFooter(ef => ef.WithText(song.PrettyInfo)))
                                         .ConfigureAwait(false);
                    }
                    catch { }
                };
                mp.OnPauseChanged += async(paused) =>
                {
                    try
                    {
                        IUserMessage msg;
                        if (paused)
                        {
                            msg = await mp.OutputTextChannel.SendConfirmAsync("🎵 Music playback **paused**.").ConfigureAwait(false);
                        }
                        else
                        {
                            msg = await mp.OutputTextChannel.SendConfirmAsync("🎵 Music playback **resumed**.").ConfigureAwait(false);
                        }

                        msg?.DeleteAfter(10);
                    }
                    catch { }
                };

                mp.SongRemoved += async(song, index) =>
                {
                    try
                    {
                        var embed = new EmbedBuilder()
                                    .WithAuthor(eab => eab.WithName("Removed song #" + (index + 1)).WithMusicIcon())
                                    .WithDescription(song.PrettyName)
                                    .WithFooter(ef => ef.WithText(song.PrettyInfo))
                                    .WithErrorColor();

                        await mp.OutputTextChannel.EmbedAsync(embed).ConfigureAwait(false);
                    }
                    catch
                    {
                        // ignored
                    }
                };
                return(mp);
            });
            Song resolvedSong;

            try
            {
                musicPlayer.ThrowIfQueueFull();
                resolvedSong = await SongHandler.ResolveSong(query, musicType).ConfigureAwait(false);

                if (resolvedSong == null)
                {
                    throw new SongNotFoundException();
                }

                musicPlayer.AddSong(resolvedSong, queuer.Username);
            }
            catch (PlaylistFullException)
            {
                try { await textCh.SendConfirmAsync($"🎵 Queue is full at **{musicPlayer.MaxQueueSize}/{musicPlayer.MaxQueueSize}**."); } catch { }
                throw;
            }
            if (!silent)
            {
                try
                {
                    //var queuedMessage = await textCh.SendConfirmAsync($"🎵 Queued **{resolvedSong.SongInfo.Title}** at `#{musicPlayer.Playlist.Count + 1}`").ConfigureAwait(false);
                    var queuedMessage = await textCh.EmbedAsync(new EmbedBuilder().WithOkColor()
                                                                .WithAuthor(eab => eab.WithName("Queued Song #" + (musicPlayer.Playlist.Count + 1)).WithMusicIcon())
                                                                .WithDescription($"{resolvedSong.PrettyName}\nQueue ")
                                                                .WithThumbnailUrl(resolvedSong.Thumbnail)
                                                                .WithFooter(ef => ef.WithText(resolvedSong.PrettyProvider)))
                                        .ConfigureAwait(false);

                    queuedMessage?.DeleteAfter(10);
                }
                catch
                {
                    // ignored
                } // if queued message sending fails, don't attempt to delete it
            }
        }
Ejemplo n.º 4
0
        public async Task QueueAsync(ICommandContext ctx, string query)
        {
            LavaPlayer player = _lavaNode.GetPlayer(ctx.Guild);

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

                return;
            }

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

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

            SearchResponse result;

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

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

                return;
            }

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

                return;
            }

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

                return;
            }

            LavaTrack track = result.Tracks[0];

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

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

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

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

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

            await ctx.Message.DeleteAsync().ConfigureAwait(false);
        }