diff options
author | 2021-05-09 19:00:16 -0700 | |
---|---|---|
committer | 2021-05-09 19:00:16 -0700 | |
commit | 24974b946bd21e6db6d5622ffa5ce1ac3c78a0e6 (patch) | |
tree | 3827245f96fcbe5049a1ac7d7e83d8fcbfd45dfc /bot/utils/converters.py | |
parent | Update return type hint to reflect new behaviour. (diff) | |
parent | Merge pull request #569 from RohanJnr/reddit_migration (diff) |
Merge branch 'main' into change-to-fetch-user
Diffstat (limited to 'bot/utils/converters.py')
-rw-r--r-- | bot/utils/converters.py | 32 |
1 files changed, 31 insertions, 1 deletions
diff --git a/bot/utils/converters.py b/bot/utils/converters.py index 228714c9..27804170 100644 --- a/bot/utils/converters.py +++ b/bot/utils/converters.py @@ -1,5 +1,6 @@ import discord -from discord.ext.commands.converter import MessageConverter +from discord.ext.commands import BadArgument, Context +from discord.ext.commands.converter import Converter, MessageConverter class WrappedMessageConverter(MessageConverter): @@ -14,3 +15,32 @@ class WrappedMessageConverter(MessageConverter): argument = argument[1:-1] return await super().convert(ctx, argument) + + +class Subreddit(Converter): + """Forces a string to begin with "r/" and checks if it's a valid subreddit.""" + + @staticmethod + async def convert(ctx: Context, sub: str) -> str: + """ + Force sub to begin with "r/" and check if it's a valid subreddit. + + If sub is a valid subreddit, return it prepended with "r/" + """ + sub = sub.lower() + + if not sub.startswith("r/"): + sub = f"r/{sub}" + + resp = await ctx.bot.http_session.get( + "https://www.reddit.com/subreddits/search.json", + params={"q": sub} + ) + + json = await resp.json() + if not json["data"]["children"]: + raise BadArgument( + f"The subreddit `{sub}` either doesn't exist, or it has no posts." + ) + + return sub |