diff options
author | 2021-05-15 13:31:34 -0400 | |
---|---|---|
committer | 2021-05-15 13:31:34 -0400 | |
commit | f8a179df350eb3abb7f3595aaff3dbca312f540c (patch) | |
tree | 6868ae98b81b614f8d8d68f1a9bbc06c7cb94490 /bot/exts | |
parent | chore: Make all aliases in commands tuples (diff) |
chore: Make things that are only used once constants
Diffstat (limited to 'bot/exts')
-rw-r--r-- | bot/exts/christmas/hanukkah_embed.py | 21 | ||||
-rw-r--r-- | bot/exts/easter/earth_photos.py | 4 | ||||
-rw-r--r-- | bot/exts/easter/egg_facts.py | 12 | ||||
-rw-r--r-- | bot/exts/evergreen/cheatsheet.py | 2 | ||||
-rw-r--r-- | bot/exts/evergreen/magic_8ball.py | 7 | ||||
-rw-r--r-- | bot/exts/evergreen/pythonfacts.py | 3 | ||||
-rw-r--r-- | bot/exts/halloween/halloween_facts.py | 9 | ||||
-rw-r--r-- | bot/exts/halloween/halloweenify.py | 10 | ||||
-rw-r--r-- | bot/exts/halloween/spookygif.py | 7 | ||||
-rw-r--r-- | bot/exts/pride/drag_queen_name.py | 12 | ||||
-rw-r--r-- | bot/exts/pride/pride_anthem.py | 12 | ||||
-rw-r--r-- | bot/exts/pride/pride_facts.py | 13 |
12 files changed, 45 insertions, 67 deletions
diff --git a/bot/exts/christmas/hanukkah_embed.py b/bot/exts/christmas/hanukkah_embed.py index 7a06b558..ca3146cc 100644 --- a/bot/exts/christmas/hanukkah_embed.py +++ b/bot/exts/christmas/hanukkah_embed.py @@ -11,16 +11,17 @@ from bot.utils.decorators import in_month log = logging.getLogger(__name__) +HEBCAL_URL = ( + "https://www.hebcal.com/hebcal/?v=1&cfg=json&maj=on&min=on&mod=on&nx=on&" + "year=now&month=x&ss=on&mf=on&c=on&geo=geoname&geonameid=3448439&m=50&s=on" +) + class HanukkahEmbed(commands.Cog): """A cog that returns information about Hanukkah festival.""" def __init__(self, bot: Bot): self.bot = bot - self.url = ( - "https://www.hebcal.com/hebcal/?v=1&cfg=json&maj=on&min=on&mod=on&nx=on&" - "year=now&month=x&ss=on&mf=on&c=on&geo=geoname&geonameid=3448439&m=50&s=on" - ) self.hanukkah_days = [] self.hanukkah_months = [] self.hanukkah_years = [] @@ -28,7 +29,7 @@ class HanukkahEmbed(commands.Cog): async def get_hanukkah_dates(self) -> List[str]: """Gets the dates for hanukkah festival.""" hanukkah_dates = [] - async with self.bot.http_session.get(self.url) as response: + async with self.bot.http_session.get(HEBCAL_URL) as response: json_data = await response.json() festivals = json_data["items"] for festival in festivals: @@ -57,9 +58,7 @@ class HanukkahEmbed(commands.Cog): day = str(today.day) month = str(today.month) year = str(today.year) - embed = Embed() - embed.title = "Hanukkah" - embed.colour = Colours.blue + embed = Embed(title="Hanukkah", colour=Colours.blue) if day in self.hanukkah_days and month in self.hanukkah_months and year in self.hanukkah_years: if int(day) == hanukkah_start_day: now = datetime.datetime.utcnow() @@ -74,8 +73,8 @@ class HanukkahEmbed(commands.Cog): return elif hours > hanukkah_start_hour: embed.description = ( - "It is the starting day of Hanukkah ! " - f"Its been {hours - hanukkah_start_hour} hours hanukkah started !" + "It is the starting day of Hanukkah! " + f"Its been {hours - hanukkah_start_hour} hours hanukkah started!" ) await ctx.send(embed=embed) return @@ -106,7 +105,7 @@ class HanukkahEmbed(commands.Cog): else: festival_end_month = hanukkah_end.strftime("%B") embed.description = ( - f"Looks like you missed Hanukkah !" + f"Looks like you missed Hanukkah!" f"Hanukkah ended on {hanukkah_end_day}th of {festival_end_month}." ) diff --git a/bot/exts/easter/earth_photos.py b/bot/exts/easter/earth_photos.py index 9df4f9ca..f65790af 100644 --- a/bot/exts/easter/earth_photos.py +++ b/bot/exts/easter/earth_photos.py @@ -9,6 +9,8 @@ from bot.constants import Tokens log = logging.getLogger(__name__) +API_URL = "https://api.unsplash.com/photos/random" + class EarthPhotos(commands.Cog): """This cog contains the command for earth photos.""" @@ -21,7 +23,7 @@ class EarthPhotos(commands.Cog): """Returns a random photo of earth, sourced from Unsplash.""" async with ctx.typing(): async with self.bot.http_session.get( - "https://api.unsplash.com/photos/random", + API_URL, params={"query": "planet_earth", "client_id": Tokens.unsplash_access_key} ) as r: jsondata = await r.json() diff --git a/bot/exts/easter/egg_facts.py b/bot/exts/easter/egg_facts.py index d60032f0..ee383171 100644 --- a/bot/exts/easter/egg_facts.py +++ b/bot/exts/easter/egg_facts.py @@ -12,6 +12,8 @@ from bot.utils.decorators import seasonal_task log = logging.getLogger(__name__) +EGG_FACTS = loads(Path("bot/resources/easter/easter_egg_facts.json").read_text("utf8")) + class EasterFacts(commands.Cog): """ @@ -22,16 +24,8 @@ class EasterFacts(commands.Cog): def __init__(self, bot: Bot): self.bot = bot - self.facts = self.load_json() - self.daily_fact_task = self.bot.loop.create_task(self.send_egg_fact_daily()) - @staticmethod - def load_json() -> dict: - """Load a list of easter egg facts from the resource JSON file.""" - p = Path("bot/resources/easter/easter_egg_facts.json") - return loads(p.read_text("utf8")) - @seasonal_task(Month.APRIL) async def send_egg_fact_daily(self) -> None: """A background task that sends an easter egg fact in the event channel everyday.""" @@ -51,7 +45,7 @@ class EasterFacts(commands.Cog): return discord.Embed( colour=Colours.soft_red, title="Easter Egg Fact", - description=random.choice(self.facts) + description=random.choice(EGG_FACTS) ) diff --git a/bot/exts/evergreen/cheatsheet.py b/bot/exts/evergreen/cheatsheet.py index 7ee34b1d..ae7793c9 100644 --- a/bot/exts/evergreen/cheatsheet.py +++ b/bot/exts/evergreen/cheatsheet.py @@ -12,7 +12,7 @@ from bot.bot import Bot from bot.constants import Categories, Channels, Colours, ERROR_REPLIES from bot.utils.decorators import whitelist_override -ERROR_MESSAGE = f"""\ +ERROR_MESSAGE = f""" Unknown cheat sheet. Please try to reformulate your query. **Examples**: diff --git a/bot/exts/evergreen/magic_8ball.py b/bot/exts/evergreen/magic_8ball.py index 4b3ed2a4..28ddcea0 100644 --- a/bot/exts/evergreen/magic_8ball.py +++ b/bot/exts/evergreen/magic_8ball.py @@ -9,18 +9,17 @@ from bot.bot import Bot log = logging.getLogger(__name__) +ANSWERS = json.loads(Path("bot/resources/evergreen/magic8ball.json").read_text("utf8")) + class Magic8ball(commands.Cog): """A Magic 8ball command to respond to a user's question.""" - def __init__(self): - self.answers = json.loads(Path("bot/resources/evergreen/magic8ball.json").read_text("utf8")) - @commands.command(name="8ball") async def output_answer(self, ctx: commands.Context, *, question: str) -> None: """Return a Magic 8ball answer from answers list.""" if len(question.split()) >= 3: - answer = random.choice(self.answers) + answer = random.choice(ANSWERS) await ctx.send(answer) else: await ctx.send("Usage: .8ball <question> (minimum length of 3 eg: `will I win?`)") diff --git a/bot/exts/evergreen/pythonfacts.py b/bot/exts/evergreen/pythonfacts.py index 606545ab..80a8da5d 100644 --- a/bot/exts/evergreen/pythonfacts.py +++ b/bot/exts/evergreen/pythonfacts.py @@ -10,6 +10,7 @@ with open("bot/resources/evergreen/python_facts.txt") as file: FACTS = itertools.cycle(list(file)) COLORS = itertools.cycle([Colours.python_blue, Colours.python_yellow]) +PYFACTS_DISCUSSION = "https://github.com/python-discord/meta/discussions/93" class PythonFacts(commands.Cog): @@ -25,7 +26,7 @@ class PythonFacts(commands.Cog): ) embed.add_field( name="Suggestions", - value="Suggest more facts [here!](https://github.com/python-discord/meta/discussions/93)" + value=f"Suggest more facts [here!]({PYFACTS_DISCUSSION})" ) await ctx.send(embed=embed) diff --git a/bot/exts/halloween/halloween_facts.py b/bot/exts/halloween/halloween_facts.py index 98cc2db0..5ad8cc57 100644 --- a/bot/exts/halloween/halloween_facts.py +++ b/bot/exts/halloween/halloween_facts.py @@ -25,17 +25,16 @@ SPOOKY_EMOJIS = [ PUMPKIN_ORANGE = 0xFF7518 INTERVAL = timedelta(hours=6).total_seconds() +FACTS = json.loads(Path("bot/resources/halloween/halloween_facts.json").read_text("utf8")) +FACTS = list(enumerate(FACTS)) + class HalloweenFacts(commands.Cog): """A Cog for displaying interesting facts about Halloween.""" - def __init__(self): - self.halloween_facts = json.loads(Path("bot/resources/halloween/halloween_facts.json").read_text("utf8")) - self.facts = list(enumerate(self.halloween_facts)) - def random_fact(self) -> Tuple[int, str]: """Return a random fact from the loaded facts.""" - return random.choice(self.facts) + return random.choice(FACTS) @commands.command(name="spookyfact", aliases=("halloweenfact",), brief="Get the most recent Halloween fact") async def get_random_fact(self, ctx: commands.Context) -> None: diff --git a/bot/exts/halloween/halloweenify.py b/bot/exts/halloween/halloweenify.py index e839950a..83cfbaa7 100644 --- a/bot/exts/halloween/halloweenify.py +++ b/bot/exts/halloween/halloweenify.py @@ -12,6 +12,8 @@ from bot.bot import Bot log = logging.getLogger(__name__) +HALLOWEENIFY_DATA = loads(Path("bot/resources/halloween/halloweenify.json").read_text("utf8")) + class Halloweenify(commands.Cog): """A cog to change a invokers nickname to a spooky one!""" @@ -21,12 +23,10 @@ class Halloweenify(commands.Cog): async def halloweenify(self, ctx: commands.Context) -> None: """Change your nickname into a much spookier one!""" async with ctx.typing(): - data = loads(Path("bot/resources/halloween/halloweenify.json").read_text("utf8")) - # Choose a random character from our list we loaded above and set apart the nickname and image url. - character = choice(data["characters"]) - nickname = "".join([nickname for nickname in character]) - image = "".join([character[nickname] for nickname in character]) + character = choice(HALLOWEENIFY_DATA["characters"]) + nickname = "".join(nickname for nickname in character) + image = "".join(character[nickname] for nickname in character) # Build up a Embed embed = discord.Embed() diff --git a/bot/exts/halloween/spookygif.py b/bot/exts/halloween/spookygif.py index ffb91b1b..a2146a84 100644 --- a/bot/exts/halloween/spookygif.py +++ b/bot/exts/halloween/spookygif.py @@ -8,6 +8,8 @@ from bot.constants import Tokens log = logging.getLogger(__name__) +API_URL = "http://api.giphy.com/v1/gifs/random" + class SpookyGif(commands.Cog): """A cog to fetch a random spooky gif from the web!""" @@ -21,12 +23,11 @@ class SpookyGif(commands.Cog): async with ctx.typing(): params = {"api_key": Tokens.giphy, "tag": "halloween", "rating": "g"} # Make a GET request to the Giphy API to get a random halloween gif. - async with self.bot.http_session.get("http://api.giphy.com/v1/gifs/random", params=params) as resp: + async with self.bot.http_session.get(API_URL, params=params) as resp: data = await resp.json() url = data["data"]["image_url"] - embed = discord.Embed(colour=0x9b59b6) - embed.title = "A spooooky gif!" + embed = discord.Embed(title="A spooooky gif!", colour=0x9b59b6) embed.set_image(url=url) await ctx.send(embed=embed) diff --git a/bot/exts/pride/drag_queen_name.py b/bot/exts/pride/drag_queen_name.py index 81eeaff5..15ca6576 100644 --- a/bot/exts/pride/drag_queen_name.py +++ b/bot/exts/pride/drag_queen_name.py @@ -9,22 +9,16 @@ from bot.bot import Bot log = logging.getLogger(__name__) +NAMES = json.loads(Path("bot/resources/pride/drag_queen_names.json").read_text("utf8")) + class DragNames(commands.Cog): """Gives a random drag queen name!""" - def __init__(self): - self.names = self.load_names() - - @staticmethod - def load_names() -> list: - """Loads a list of drag queen names.""" - return json.loads(Path("bot/resources/pride/drag_queen_names.json").read_text("utf8")) - @commands.command(name="dragname", aliases=("dragqueenname", "queenme")) async def dragname(self, ctx: commands.Context) -> None: """Sends a message with a drag queen name.""" - await ctx.send(random.choice(self.names)) + await ctx.send(random.choice(NAMES)) def setup(bot: Bot) -> None: diff --git a/bot/exts/pride/pride_anthem.py b/bot/exts/pride/pride_anthem.py index ce4b06af..4650595a 100644 --- a/bot/exts/pride/pride_anthem.py +++ b/bot/exts/pride/pride_anthem.py @@ -10,13 +10,12 @@ from bot.bot import Bot log = logging.getLogger(__name__) +VIDEOS = json.loads(Path("bot/resources/pride/anthems.json").read_text("utf8")) + class PrideAnthem(commands.Cog): """Embed a random youtube video for a gay anthem!""" - def __init__(self): - self.anthems = self.load_vids() - def get_video(self, genre: Optional[str] = None) -> dict: """ Picks a random anthem from the list. @@ -27,17 +26,12 @@ class PrideAnthem(commands.Cog): if not genre: return random.choice(self.anthems) else: - songs = [song for song in self.anthems if genre.casefold() in song["genre"]] + songs = [song for song in VIDEOS if genre.casefold() in song["genre"]] try: return random.choice(songs) except IndexError: log.info("No videos for that genre.") - @staticmethod - def load_vids() -> list: - """Loads a list of videos from the resources folder as dictionaries.""" - return json.loads(Path("bot/resources/pride/anthems.json").read_text("utf8")) - @commands.command(name="prideanthem", aliases=("anthem", "pridesong")) async def prideanthem(self, ctx: commands.Context, genre: str = None) -> None: """ diff --git a/bot/exts/pride/pride_facts.py b/bot/exts/pride/pride_facts.py index 5bea1d32..631e2e8b 100644 --- a/bot/exts/pride/pride_facts.py +++ b/bot/exts/pride/pride_facts.py @@ -15,21 +15,16 @@ from bot.utils.decorators import seasonal_task log = logging.getLogger(__name__) +FACTS = json.loads(Path("bot/resources/pride/facts.json").read_text("utf8")) + class PrideFacts(commands.Cog): """Provides a new fact every day during the Pride season!""" def __init__(self, bot: Bot): self.bot = bot - self.facts = self.load_facts() - self.daily_fact_task = self.bot.loop.create_task(self.send_pride_fact_daily()) - @staticmethod - def load_facts() -> dict: - """Loads a dictionary of years mapping to lists of facts.""" - return json.loads(Path("bot/resources/pride/facts.json").read_text("utf8")) - @seasonal_task(Month.JUNE) async def send_pride_fact_daily(self) -> None: """Background task to post the daily pride fact every day.""" @@ -41,8 +36,8 @@ class PrideFacts(commands.Cog): async def send_random_fact(self, ctx: commands.Context) -> None: """Provides a fact from any previous day, or today.""" now = datetime.utcnow() - previous_years_facts = (y for x, y in self.facts.items() if int(x) < now.year) - current_year_facts = self.facts.get(str(now.year), [])[:now.day] + previous_years_facts = (y for x, y in FACTS.items() if int(x) < now.year) + current_year_facts = FACTS.get(str(now.year), [])[:now.day] previous_facts = current_year_facts + [x for y in previous_years_facts for x in y] try: await ctx.send(embed=self.make_embed(random.choice(previous_facts))) |