Example #1
0
        public async Task LastFmTracks(ICommand command)
        {
            try
            {
                var(settings, user) = await GetLastFmSettings(command["User"], (IGuildUser)command.Author);

                var period = command["Period"].HasValue ? ParseStatsPeriod(command["Period"]) : LastFmDataPeriod.Overall;
                var client = new LastFmClient(settings.LastFmUsername, _integrationOptions.Value.LastFmKey);

                const int NumDisplayed  = 100;
                var       playcountTask = client.GetTotalPlaycount(period);
                var       results       = (await client.GetTrackScores(period, NumDisplayed, playcountTask)).ToList();
                if (!results.Any())
                {
                    throw new AbortException(GetNoScrobblesTimePeriodMessage((await command["User"].AsGuildUserOrName)?.Item2));
                }

                var pages = new PageCollectionBuilder();
                var place = 1;
                foreach (var entry in results.Take(NumDisplayed))
                {
                    pages.AppendLine($"`#{place++}` **{FormatTrackLink(entry.Entity, true)}** by **{FormatArtistLink(entry.Entity.Artist, true)}**_ – {FormatPercent(entry.Score)} ({entry.Entity.Playcount} plays)_");
                }

                var playsTotal   = await playcountTask;
                var embedFactory = new Func <EmbedBuilder>(() =>
                {
                    var author = new EmbedAuthorBuilder()
                                 .WithIconUrl(_websiteWalker.LfIconUrl)
                                 .WithName($"{user}'s top tracks {FormatStatsPeriod(period)}");

                    if (!settings.Anonymous)
                    {
                        author.WithUrl($"https://www.last.fm/user/{settings.LastFmUsername}");
                    }

                    return(new EmbedBuilder()
                           .WithColor(0xd9, 0x23, 0x23)
                           .WithAuthor(author)
                           .WithFooter($"{playsTotal} plays in total"));
                });

                await command.Reply(pages.BuildEmbedCollection(embedFactory, 10), true);
            }
            catch (WebException e) when((e.Response as HttpWebResponse)?.StatusCode == HttpStatusCode.NotFound)
            {
                ThrowUserNotFound((await command["User"].AsGuildUserOrName)?.Item2);
            }
            catch (WebException e) when((e.Response as HttpWebResponse)?.StatusCode == HttpStatusCode.Forbidden)
            {
                throw new CommandException("The bot can't access your recently listened tracks. \n\nPlease make sure you don't have `Hide recent listening information` checked in your Last.fm settings (Settings -> Privacy -> Recent listening).");
            }
            catch (WebException e)
            {
                await command.Reply($"Last.fm is down (error {(e.Response as HttpWebResponse)?.StatusCode.ToString() ?? e.Status.ToString()}). Please try again in a few seconds.");
            }
        }
Example #2
0
        private Compositor(int generation, int startingID)
        {
            _generation = generation;
            _startID    = _id = startingID;

            _catalogReference = IndirectObject(_catalog = Dictionary("Catalog"));
            _rootCollection   = new PageCollectionBuilder(this);
            _catalog.Set("Pages", _rootCollection.Reference);

            FontID = 1;
        }
Example #3
0
            public PageBuilder(PageCollectionBuilder parent)
            {
                _parent = parent;

                IndirectObject pageRef = _parent.Compositor.IndirectObject(
                    _dictionary = parent.Compositor.Dictionary("Page")
                                  .Set("Parent", parent.Reference)
                    );

                parent.Kids.Add(pageRef);

                _dictionary.Set("Contents", parent.Compositor.StreamObject(_stream = new TextCommandStream()));
            }
Example #4
0
        public async Task Artists(ICommand command)
        {
            try
            {
                var period = command["Period"].HasValue ? ParseStatsPeriod(command["Period"]) : TimeRangeType.LongTerm;

                var user   = command["User"].HasValue ? await command["User"].AsGuildUser : (IGuildUser)command.Author;
                var client = await GetClient(user.Id, command.Channel, user.Id != command.Author.Id);

                const int NumDisplayed = 100;

                var results = await client.GetUsersTopArtistsAsync(period, 50);

                if (!results?.Items?.Any() ?? true)
                {
                    throw new AbortException("Looks like this user hasn't listened to anything in this time range.");
                }

                var pages = new PageCollectionBuilder();
                var place = 1;
                var now   = DateTime.UtcNow;
                foreach (var item in results.Items.Take(NumDisplayed))
                {
                    pages.AppendLine($"`#{place++}` **{FormatLink(item.Name, item.ExternalUrls, false)}**");
                }

                var embedFactory = new Func <EmbedBuilder>(() =>
                {
                    var author = new EmbedAuthorBuilder()
                                 .WithIconUrl(_websiteWalker.SpotifyIconUrl)
                                 .WithName($"{user.Nickname ?? user.Username}'s top artists {FormatStatsPeriod(period)}");

                    var embed = new EmbedBuilder()
                                .WithAuthor(author)
                                .WithColor(0x31, 0xd9, 0x64)
                                .WithFooter($"Recent listens hold more weight")
                                .WithThumbnailUrl(results.Items.First().Images.FirstOrDefault()?.Url);

                    return(embed);
                });

                await command.Reply(pages.BuildEmbedCollection(embedFactory, 10), true);
            }
            catch (WebException ex) when(ex.Response is HttpWebResponse r && r.StatusCode == HttpStatusCode.ServiceUnavailable)
            {
                await command.Reply($"Spotify API is currently unavailable. Please try again in a few seconds.");
            }
        }
Example #5
0
        public async Task ListBlacklistRaidProtection(ICommand command)
        {
            var settings = await _settings.Read <RaidProtectionSettings>(command.GuildId);

            if (!settings.PhraseBlacklistRule.Blacklist.Any())
            {
                await command.Reply("No blacklisted phrases have been added for this server.");

                return;
            }

            var builder = new PageCollectionBuilder(settings.PhraseBlacklistRule.Blacklist.Select(x => $"`{x}`"));
            var pages   = builder.BuildEmbedCollection(() => new EmbedBuilder().WithTitle("Blacklisted phrases"), 25);

            await command.Reply(pages);
        }
Example #6
0
        public async Task Recent(ICommand command)
        {
            try
            {
                var user   = command["User"].HasValue ? await command["User"].AsGuildUser : (IGuildUser)command.Author;
                var client = await GetClient(user.Id, command.Channel, user.Id != command.Author.Id);

                const int NumDisplayed = 100;

                var results = await client.GetUsersRecentlyPlayedTracksAsync(50);

                if (!results?.Items?.Any() ?? true)
                {
                    throw new AbortException("Looks like this user hasn't listened to anything recently.");
                }

                var pages = new PageCollectionBuilder();
                var place = 1;
                var now   = DateTime.UtcNow;
                foreach (var item in results.Items.Take(NumDisplayed))
                {
                    var track = item.Track;
                    var when  = now - item.PlayedAt;

                    pages.AppendLine($"`{place++}>` **{FormatLink(track.Name, track.ExternUrls)}** by {BuildArtistsString(track.Artists)}_ – {when.SimpleFormat()} ago_");
                }

                var embedFactory = new Func <EmbedBuilder>(() =>
                {
                    var author = new EmbedAuthorBuilder()
                                 .WithIconUrl(_websiteWalker.SpotifyIconUrl)
                                 .WithName($"{user.Nickname ?? user.Username} last listened to...");

                    var embed = new EmbedBuilder()
                                .WithAuthor(author)
                                .WithColor(0x31, 0xd9, 0x64);

                    return(embed);
                });

                await command.Reply(pages.BuildEmbedCollection(embedFactory, 10), true);
            }
            catch (WebException ex) when(ex.Response is HttpWebResponse r && r.StatusCode == HttpStatusCode.ServiceUnavailable)
            {
                await command.Reply($"Spotify API is currently unavailable. Please try again in a few seconds.");
            }
        }
Example #7
0
        public async Task ShowReactionStats(ICommand command)
        {
            var settings = await _settings.Read <ReactionsSettings>(command.GuildId, false);

            if (settings == null || !settings.Reactions.Any())
            {
                await command.Reply("No reactions have been set up on this server.");

                return;
            }

            IEnumerable <Reaction> reactions;

            if (command["IdOrTrigger"].HasValue)
            {
                reactions = FindReactions(settings, command["IdOrTrigger"]);
            }
            else
            {
                reactions = settings.Reactions;
            }

            var stats = reactions
                        .GroupBy(x => x.Trigger)
                        .Select(x => (Trigger: x.Key, TriggerCount: x.Sum(y => y.TriggerCount)))
                        .OrderByDescending(x => x.TriggerCount)
                        .ThenBy(x => x.Trigger);

            var pages = new PageCollectionBuilder();
            var place = 1;

            foreach (var reaction in stats.Take(100))
            {
                pages.AppendLine($"`#{place++}` **{reaction.Trigger.Truncate(30)}** – triggered **{reaction.TriggerCount}** time{(reaction.TriggerCount != 1 ? "s" : "")}");
            }

            var embedFactory = new Func <EmbedBuilder>(() => new EmbedBuilder()
                                                       .WithTitle("Reaction statistics")
                                                       .WithFooter($"{settings.Reactions.Count} reactions in total"));

            await command.Reply(pages.BuildEmbedCollection(embedFactory, 10), true);
        }
Example #8
0
        public async Task LastFmRecent(ICommand command)
        {
            try
            {
                var(settings, user) = await GetLastFmSettings(command["User"], (IGuildUser)command.Author);

                var client = new LastFmClient(settings.LastFmUsername, _integrationOptions.Value.LastFmKey);

                const int NumDisplayed = 100;
                var       userInfoTask = client.GetUserInfo();
                var       results      = await client.GetRecentTracks(count : NumDisplayed);

                if (!results.Any())
                {
                    throw new AbortException("This user hasn't scrobbled anything recently.");
                }

                var nowPlaying = results.First().NowPlaying;
                var pages      = new PageCollectionBuilder();
                var place      = 1;
                foreach (var track in results.Take(NumDisplayed))
                {
                    string when = null;
                    if (nowPlaying)
                    {
                        nowPlaying = false;
                        when       = "now playing";
                    }
                    else if (track.Timestamp.HasValue)
                    {
                        when = (track.Timestamp.Value - DateTimeOffset.UtcNow).SimpleFormat();
                    }

                    pages.AppendLine($"`{place++}>` **{FormatTrackLink(track.ToTrack(), true)}** by **{FormatArtistLink(track.Artist, true)}**" + (when != null ? $"_ – {when}_" : string.Empty));
                }

                var userInfo     = await userInfoTask;
                var embedFactory = new Func <EmbedBuilder>(() =>
                {
                    var author = new EmbedAuthorBuilder()
                                 .WithIconUrl(_websiteWalker.LfIconUrl)
                                 .WithName($"{user} last listened to...");

                    if (!settings.Anonymous)
                    {
                        author.WithUrl($"https://www.last.fm/user/{settings.LastFmUsername}");
                    }

                    var embed = new EmbedBuilder()
                                .WithColor(0xd9, 0x23, 0x23)
                                .WithAuthor(author);

                    if (userInfo?.Playcount != null)
                    {
                        embed.WithFooter($"{userInfo.Playcount} plays in total");
                    }

                    return(embed);
                });

                await command.Reply(pages.BuildEmbedCollection(embedFactory, 10), true);
            }
            catch (WebException e) when((e.Response as HttpWebResponse)?.StatusCode == HttpStatusCode.NotFound)
            {
                ThrowUserNotFound((await command["User"].AsGuildUserOrName)?.Item2);
            }
            catch (WebException e) when((e.Response as HttpWebResponse)?.StatusCode == HttpStatusCode.Forbidden)
            {
                throw new CommandException("The bot can't access your recently listened tracks. \n\nPlease make sure you don't have `Hide recent listening information` checked in your Last.fm settings (Settings -> Privacy -> Recent listening).");
            }
            catch (WebException e)
            {
                await command.Reply($"Last.fm is down (error {(e.Response as HttpWebResponse)?.StatusCode.ToString() ?? e.Status.ToString()}). Please try again in a few seconds.");
            }
        }