예제 #1
0
        public static string ToUrlPartString(this RedditCategory category)
        {
            switch (category)
            {
            case RedditCategory.Controversial:
                return("controversial");

            case RedditCategory.Gilded:
                return("gilded");

            case RedditCategory.Hot:
                return("hot");

            case RedditCategory.New:
                return("new");

            case RedditCategory.Rising:
                return("rising");

            case RedditCategory.Top:
                return("top");
            }

            throw new ArgumentException("Unknown reddit category", nameof(category));
        }
예제 #2
0
 private async Task RedditPost(CommandContext ctx, string query, RedditCategory category)
 {
     if (!BotServices.CheckUserInput(query))
     {
         return;
     }
     var results = RedditService.GetEmbeddedResults(query, category);
     await ctx.RespondAsync("Search results for r/" + query, embed : results).ConfigureAwait(false);
 }
예제 #3
0
 private static string GetPostCategory(this RedditCategory category)
 {
     return(category switch
     {
         RedditCategory.Hot => "hot",
         RedditCategory.New => "new",
         RedditCategory.Top => "top",
         _ => throw new ArgumentException(Resources.ERR_REDDIT_UNKNOWN, nameof(category))
     });
예제 #4
0
        public static string GetPostCategory(this RedditCategory category)
        {
            switch (category)
            {
            case RedditCategory.Hot: return("hot");

            case RedditCategory.New: return("new");

            case RedditCategory.Top: return("top");
            }
            throw new ArgumentException("Unknown reddit category", nameof(category));
        }
예제 #5
0
 private static List <SyndicationItem> GetResults(string query, RedditCategory category)
 {
     try
     {
         query            = $"https://www.reddit.com/r/{query.ToLowerInvariant()}/{GetPostCategory(category)}.rss";
         using var reader = XmlReader.Create(query);
         return(SyndicationFeed.Load(reader).Items?.ToList());
     }
     catch
     {
         return(null);
     }
 }
예제 #6
0
 public static List <SyndicationItem> GetResults(string query, RedditCategory category)
 {
     try
     {
         query            = string.Format(Resources.URL_Reddit, query.ToLowerInvariant(), GetPostCategory(category));
         using var reader = XmlReader.Create(query);
         return(SyndicationFeed.Load(reader).Items?.ToList());
     }
     catch
     {
         return(null);
     }
 }
예제 #7
0
        private static async Task RedditPost(CommandContext ctx, string query, RedditCategory category)
        {
            if (string.IsNullOrWhiteSpace(query))
            {
                return;
            }
            await ctx.TriggerTypingAsync();

            var results = RedditService.GetResults(query, category);

            if (results is null || results.Count == 0)
            {
                await BotServices.SendResponseAsync(ctx, Resources.NOT_FOUND_COMMON, ResponseType.Missing)
                .ConfigureAwait(false);

                return;
            }

            while (results.Count > 0)
            {
                var output = new DiscordEmbedBuilder()
                             .WithFooter("Type 'next' within 10 seconds for the next five posts.")
                             .WithColor(new DiscordColor("#FF4500"));

                foreach (var result in results.Take(5))
                {
                    output.AddField(result.Authors.FirstOrDefault()?.Name,
                                    $"[{(result.Title.Text.Length < 500 ? result.Title.Text : result.Title.Text.Take(500) + "...")}]({result.Links.First().Uri})");
                    results.Remove(result);
                }

                var message = await ctx.RespondAsync("Search results for r/" + query + " on Reddit", output)
                              .ConfigureAwait(false);

                if (results.Count == 5)
                {
                    continue;
                }
                var interactivity = await BotServices.GetUserInteractivity(ctx, "next", 10).ConfigureAwait(false);

                if (interactivity.Result is null)
                {
                    break;
                }
                await BotServices.RemoveMessage(interactivity.Result).ConfigureAwait(false);

                await BotServices.RemoveMessage(message).ConfigureAwait(false);
            }
        }
예제 #8
0
        private Task SearchAndSendResultsAsync(CommandContext ctx, string sub, RedditCategory category)
        {
            if (string.IsNullOrWhiteSpace(sub))
            {
                throw new InvalidCommandUsageException(ctx, "cmd-err-sub-none");
            }

            string?url = RedditService.GetFeedURLForSubreddit(sub, category, out string?rsub);

            if (url is null || rsub is null)
            {
                if (rsub is null)
                {
                    throw new CommandFailedException(ctx, "cmd-err-sub-format");
                }
                else
                {
                    throw new CommandFailedException(ctx, "cmd-err-sub-404", rsub);
                }
            }

            IReadOnlyList <SyndicationItem>?res = RssFeedsService.GetFeedResults(url);

            if (res is null)
            {
                throw new CommandFailedException(ctx, "cmd-err-sub-fail", rsub);
            }

            if (!res.Any())
            {
                return(ctx.FailAsync("cmd-err-res-none"));
            }

            return(ctx.PaginateAsync(res, (emb, r) => {
                emb.WithTitle(r.Title.Text);
                emb.WithDescription(r.Summary, unknown: false);
                emb.WithUrl(r.Links.First().Uri);
                if (r.Content is TextSyndicationContent content)
                {
                    string?url = RedditService.GetImageUrl(content);
                    if (url is { })
                    {
                        emb.WithImageUrl(url);
                    }
                }
예제 #9
0
        private async Task SearchAndSendResultsAsync(CommandContext ctx, string sub, RedditCategory category)
        {
            string url = RedditService.GetFeedUrlForSubreddit(sub, category, out string rsub);

            if (url is null)
            {
                throw new CommandFailedException("That subreddit doesn't exist.");
            }

            var res = RssService.GetFeedResults(url);

            if (res is null)
            {
                throw new CommandFailedException($"Failed to get the data from that subreddit ({Formatter.Bold(rsub)}).");
            }

            await RssService.SendFeedResultsAsync(ctx.Channel, res);
        }
예제 #10
0
        public static string?GetFeedURLForSubreddit(string sub, RedditCategory category, out string?rsub)
        {
            rsub = null;

            if (string.IsNullOrWhiteSpace(sub))
            {
                return(null);
            }

            if (_sanitizeRegex.IsMatch(sub))
            {
                return(null);
            }

            sub  = _subPrefixRegex.Replace(sub, string.Empty);
            rsub = "/r/" + sub.ToLowerInvariant();

            string url = $"https://www.reddit.com{rsub}/{category.Humanize(LetterCasing.LowerCase)}.rss";

            return(RssFeedsService.IsValidFeedURL(url) ? url : null);
        }
예제 #11
0
        public static string GetFeedURLForSubreddit(string sub, RedditCategory category, out string rsub)
        {
            if (string.IsNullOrWhiteSpace(sub))
            {
                throw new ArgumentException("Subreddit missing", nameof(sub));
            }

            if (_sanitizeRegex.IsMatch(sub))
            {
                throw new ArgumentException("Subreddit is in invalid format (needs to be lowercase and without spaces, for example `/r/rule34`)", nameof(sub));
            }

            sub  = _subPrefixRegex.Replace(sub, string.Empty);
            rsub = "/r/" + sub.ToLowerInvariant();

            string url = $"https://www.reddit.com{rsub}/{category.ToUrlPartString()}.rss";

            if (!RssService.IsValidFeedURL(url))
            {
                return(null);
            }

            return(url);
        }
예제 #12
0
        public static DiscordEmbed GetEmbeddedResults(string query, RedditCategory category = RedditCategory.Hot)
        {
            var results = GetResults(query, category);

            if (results is null || results.Count == 0)
            {
                return new DiscordEmbedBuilder
                       {
                           Description = ":warning: No results found!",
                           Color       = new DiscordColor("#FF4500")
                       }
            }
            ;
            results = (results.Count > 5) ? results.Take(5).ToList() : results;
            var output = new DiscordEmbedBuilder {
                Color = new DiscordColor("#FF4500")
            };

            foreach (var result in results)
            {
                output.AddField(result.Title.Text.Length < 500 ? result.Title.Text : result.Title.Text.Take(500) + "...", result.Links.First().Uri.ToString());
            }
            return(output.Build());
        }