From a6cc40ff3b323dff112d7f8c339e124f3a6d9980 Mon Sep 17 00:00:00 2001 From: ToxicKidz <78174417+ToxicKidz@users.noreply.github.com> Date: Tue, 4 May 2021 12:57:03 -0400 Subject: chore: Prefer double quotes over single quotes --- bot/exts/evergreen/snakes/_utils.py | 34 +++++++++++++++++----------------- 1 file changed, 17 insertions(+), 17 deletions(-) (limited to 'bot/exts/evergreen/snakes/_utils.py') diff --git a/bot/exts/evergreen/snakes/_utils.py b/bot/exts/evergreen/snakes/_utils.py index 7d6caf04..d58ee279 100644 --- a/bot/exts/evergreen/snakes/_utils.py +++ b/bot/exts/evergreen/snakes/_utils.py @@ -321,7 +321,7 @@ def create_snek_frame( image_dimensions[Y] / 2 - (dimension_range[Y] / 2 + min_dimensions[Y]) ) - image = Image.new(mode='RGB', size=image_dimensions, color=bg_color) + image = Image.new(mode="RGB", size=image_dimensions, color=bg_color) draw = ImageDraw(image) for index in range(1, len(points)): point = points[index] @@ -345,7 +345,7 @@ def create_snek_frame( def frame_to_png_bytes(image: Image) -> io.BytesIO: """Convert image to byte stream.""" stream = io.BytesIO() - image.save(stream, format='PNG') + image.save(stream, format="PNG") stream.seek(0) return stream @@ -373,7 +373,7 @@ class SnakeAndLaddersGame: self.snakes = snakes self.ctx = context self.channel = self.ctx.channel - self.state = 'booting' + self.state = "booting" self.started = False self.author = self.ctx.author self.players = [] @@ -413,7 +413,7 @@ class SnakeAndLaddersGame: "**Snakes and Ladders**: A new game is about to start!", file=File( str(SNAKE_RESOURCES / "snakes_and_ladders" / "banner.jpg"), - filename='Snakes and Ladders.jpg' + filename="Snakes and Ladders.jpg" ) ) startup = await self.channel.send( @@ -423,7 +423,7 @@ class SnakeAndLaddersGame: for emoji in STARTUP_SCREEN_EMOJI: await startup.add_reaction(emoji) - self.state = 'waiting' + self.state = "waiting" while not self.started: try: @@ -460,7 +460,7 @@ class SnakeAndLaddersGame: self.players.append(user) self.player_tiles[user.id] = 1 - avatar_bytes = await user.avatar_url_as(format='jpeg', size=PLAYER_ICON_IMAGE_SIZE).read() + avatar_bytes = await user.avatar_url_as(format="jpeg", size=PLAYER_ICON_IMAGE_SIZE).read() im = Image.open(io.BytesIO(avatar_bytes)).resize((BOARD_PLAYER_SIZE, BOARD_PLAYER_SIZE)) self.avatar_images[user.id] = im @@ -475,7 +475,7 @@ class SnakeAndLaddersGame: if user == p: await self.channel.send(user.mention + " You are already in the game.", delete_after=10) return - if self.state != 'waiting': + if self.state != "waiting": await self.channel.send(user.mention + " You cannot join at this time.", delete_after=10) return if len(self.players) is MAX_PLAYERS: @@ -510,7 +510,7 @@ class SnakeAndLaddersGame: delete_after=10 ) - if self.state != 'waiting' and len(self.players) == 0: + if self.state != "waiting" and len(self.players) == 0: await self.channel.send("**Snakes and Ladders**: The game has been surrendered!") is_surrendered = True self._destruct() @@ -535,12 +535,12 @@ class SnakeAndLaddersGame: await self.channel.send(user.mention + " Only the author of the game can start it.", delete_after=10) return - if not self.state == 'waiting': + if not self.state == "waiting": await self.channel.send(user.mention + " The game cannot be started at this time.", delete_after=10) return - self.state = 'starting' - player_list = ', '.join(user.mention for user in self.players) + self.state = "starting" + player_list = ", ".join(user.mention for user in self.players) await self.channel.send("**Snakes and Ladders**: The game is starting!\nPlayers: " + player_list) await self.start_round() @@ -556,7 +556,7 @@ class SnakeAndLaddersGame: )) ) - self.state = 'roll' + self.state = "roll" for user in self.players: self.round_has_rolled[user.id] = False board_img = Image.open(str(SNAKE_RESOURCES / "snakes_and_ladders" / "board.jpg")) @@ -574,8 +574,8 @@ class SnakeAndLaddersGame: board_img.paste(self.avatar_images[player.id], box=(x_offset, y_offset)) - board_file = File(frame_to_png_bytes(board_img), filename='Board.jpg') - player_list = '\n'.join((user.mention + ": Tile " + str(self.player_tiles[user.id])) for user in self.players) + board_file = File(frame_to_png_bytes(board_img), filename="Board.jpg") + player_list = "\n".join((user.mention + ": Tile " + str(self.player_tiles[user.id])) for user in self.players) # Store and send new messages temp_board = await self.channel.send( @@ -644,7 +644,7 @@ class SnakeAndLaddersGame: if user.id not in self.player_tiles: await self.channel.send(user.mention + " You are not in the match.", delete_after=10) return - if self.state != 'roll': + if self.state != "roll": await self.channel.send(user.mention + " You may not roll at this time.", delete_after=10) return if self.round_has_rolled[user.id]: @@ -673,7 +673,7 @@ class SnakeAndLaddersGame: async def _complete_round(self) -> None: """At the conclusion of a round check to see if there's been a winner.""" - self.state = 'post_round' + self.state = "post_round" # check for winner winner = self._check_winner() @@ -688,7 +688,7 @@ class SnakeAndLaddersGame: def _check_winner(self) -> Member: """Return a winning member if we're in the post-round state and there's a winner.""" - if self.state != 'post_round': + if self.state != "post_round": return None return next((player for player in self.players if self.player_tiles[player.id] == 100), None) -- cgit v1.2.3 From d5f01153aac59cfbc043d894ebf6e1173c1efb48 Mon Sep 17 00:00:00 2001 From: ToxicKidz Date: Fri, 7 May 2021 13:41:23 -0400 Subject: chore: Reformat the code to follow the style guild --- bot/__init__.py | 2 +- bot/exts/christmas/advent_of_code/_cog.py | 18 ++++++++++------ bot/exts/christmas/hanukkah_embed.py | 34 ++++++++++++++++++++----------- bot/exts/evergreen/cheatsheet.py | 20 ++++++++++-------- bot/exts/evergreen/connect_four.py | 6 ++++-- bot/exts/evergreen/game.py | 15 +++++++------- bot/exts/evergreen/pythonfacts.py | 14 ++++++++----- bot/exts/evergreen/snakes/_snakes_cog.py | 26 ++++++++++++++++------- bot/exts/evergreen/snakes/_utils.py | 7 +++++-- 9 files changed, 92 insertions(+), 50 deletions(-) (limited to 'bot/exts/evergreen/snakes/_utils.py') diff --git a/bot/__init__.py b/bot/__init__.py index 669f9f5d..e5ed9d92 100644 --- a/bot/__init__.py +++ b/bot/__init__.py @@ -69,7 +69,7 @@ logging.basicConfig( level=logging.TRACE if Client.debug else logging.DEBUG, handlers=[console_handler, file_handler], ) -logging.getLogger().info('Logging initialization complete') +logging.getLogger().info("Logging initialization complete") # On Windows, the selector event loop is required for aiodns. diff --git a/bot/exts/christmas/advent_of_code/_cog.py b/bot/exts/christmas/advent_of_code/_cog.py index da1cf28d..863d2a21 100644 --- a/bot/exts/christmas/advent_of_code/_cog.py +++ b/bot/exts/christmas/advent_of_code/_cog.py @@ -72,11 +72,15 @@ class AdventOfCode(commands.Cog): if role not in ctx.author.roles: await ctx.author.add_roles(role) - await ctx.send("Okay! You have been __subscribed__ to notifications about new Advent of Code tasks. " - f"You can run `{unsubscribe_command}` to disable them again for you.") + await ctx.send( + "Okay! You have been __subscribed__ to notifications about new Advent of Code tasks. " + f"You can run `{unsubscribe_command}` to disable them again for you." + ) else: - await ctx.send("Hey, you already are receiving notifications about new Advent of Code tasks. " - f"If you don't want them any more, run `{unsubscribe_command}` instead.") + await ctx.send( + "Hey, you already are receiving notifications about new Advent of Code tasks. " + f"If you don't want them any more, run `{unsubscribe_command}` instead." + ) @in_month(Month.DECEMBER) @adventofcode_group.command(name="unsubscribe", aliases=("unsub",), brief="Notifications for new days") @@ -110,8 +114,10 @@ class AdventOfCode(commands.Cog): else: delta_str = f"{delta.days} days" - await ctx.send(f"The Advent of Code event is not currently running. " - f"The next event will start in {delta_str}.") + await ctx.send( + f"The Advent of Code event is not currently running. " + f"The next event will start in {delta_str}." + ) return tomorrow, time_left = _helpers.time_left_to_est_midnight() diff --git a/bot/exts/christmas/hanukkah_embed.py b/bot/exts/christmas/hanukkah_embed.py index 214044b8..af5cfccf 100644 --- a/bot/exts/christmas/hanukkah_embed.py +++ b/bot/exts/christmas/hanukkah_embed.py @@ -17,8 +17,10 @@ class HanukkahEmbed(commands.Cog): 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.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 = [] @@ -64,13 +66,17 @@ class HanukkahEmbed(commands.Cog): hours = now.hour + 4 # using only hours hanukkah_start_hour = 18 if hours < hanukkah_start_hour: - embed.description = (f"Hanukkah hasnt started yet, " - f"it will start in about {hanukkah_start_hour - hours} hour/s.") + embed.description = ( + f"Hanukkah hasnt started yet, " + f"it will start in about {hanukkah_start_hour - hours} hour/s." + ) await ctx.send(embed=embed) return elif hours > hanukkah_start_hour: - embed.description = (f"It is the starting day of Hanukkah ! " - f"Its been {hours - hanukkah_start_hour} hours hanukkah started !") + embed.description = ( + f"It is the starting day of Hanukkah ! " + f"Its been {hours - hanukkah_start_hour} hours hanukkah started !" + ) await ctx.send(embed=embed) return festival_day = self.hanukkah_days.index(day) @@ -87,18 +93,22 @@ class HanukkahEmbed(commands.Cog): message = "" for _ in range(1, festival_day + 1): message += ":menorah:" - embed.description = f"It is the {festival_day}{suffix} day of Hanukkah ! \n {message}" + embed.description = f"It is the {festival_day}{suffix} day of Hanukkah!\n{message}" await ctx.send(embed=embed) else: if today < hanukkah_start: festival_starting_month = hanukkah_start.strftime("%B") - embed.description = (f"Hanukkah has not started yet. " - f"Hanukkah will start at sundown on {hanukkah_start_day}th " - f"of {festival_starting_month}.") + embed.description = ( + f"Hanukkah has not started yet. " + f"Hanukkah will start at sundown on {hanukkah_start_day}th " + f"of {festival_starting_month}." + ) else: festival_end_month = hanukkah_end.strftime("%B") - embed.description = (f"Looks like you missed Hanukkah !" - f"Hanukkah ended on {hanukkah_end_day}th of {festival_end_month}.") + embed.description = ( + f"Looks like you missed Hanukkah !" + f"Hanukkah ended on {hanukkah_end_day}th of {festival_end_month}." + ) await ctx.send(embed=embed) diff --git a/bot/exts/evergreen/cheatsheet.py b/bot/exts/evergreen/cheatsheet.py index 86fae167..7ee34b1d 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**: @@ -61,14 +61,18 @@ class CheatSheet(commands.Cog): body_space = min(1986 - len(url), 1000) if len(body_text) > body_space: - description = (f"**Result Of cht.sh**\n" - f"```python\n{body_text[:body_space]}\n" - f"... (truncated - too many lines)```\n" - f"Full results: {url} ") + description = ( + f"**Result Of cht.sh**\n" + f"```python\n{body_text[:body_space]}\n" + f"... (truncated - too many lines)```\n" + f"Full results: {url} " + ) else: - description = (f"**Result Of cht.sh**\n" - f"```python\n{body_text}```\n" - f"{url}") + description = ( + f"**Result Of cht.sh**\n" + f"```python\n{body_text}```\n" + f"{url}" + ) return False, description @commands.command( diff --git a/bot/exts/evergreen/connect_four.py b/bot/exts/evergreen/connect_four.py index 929a15d8..dc365a70 100644 --- a/bot/exts/evergreen/connect_four.py +++ b/bot/exts/evergreen/connect_four.py @@ -277,8 +277,10 @@ class ConnectFour(commands.Cog): return False if not self.min_board_size <= board_size <= self.max_board_size: - await ctx.send(f"{board_size} is not a valid board size. A valid board size is " - f"between `{self.min_board_size}` and `{self.max_board_size}`.") + await ctx.send( + f"{board_size} is not a valid board size. A valid board size is " + f"between `{self.min_board_size}` and `{self.max_board_size}`." + ) return False return True diff --git a/bot/exts/evergreen/game.py b/bot/exts/evergreen/game.py index 4da33259..6f01d81c 100644 --- a/bot/exts/evergreen/game.py +++ b/bot/exts/evergreen/game.py @@ -335,13 +335,14 @@ class Games(Cog): return await ctx.send("Successfully refreshed genres.") - async def get_games_list(self, - amount: int, - genre: Optional[str] = None, - sort: Optional[str] = None, - additional_body: str = "", - offset: int = 0 - ) -> List[Dict[str, Any]]: + async def get_games_list( + self, + amount: int, + genre: Optional[str] = None, + sort: Optional[str] = None, + additional_body: str = "", + offset: int = 0 + ) -> List[Dict[str, Any]]: """ Get list of games from IGDB API by parameters that is provided. diff --git a/bot/exts/evergreen/pythonfacts.py b/bot/exts/evergreen/pythonfacts.py index c0086c20..e162c9bd 100644 --- a/bot/exts/evergreen/pythonfacts.py +++ b/bot/exts/evergreen/pythonfacts.py @@ -18,11 +18,15 @@ class PythonFacts(commands.Cog): @commands.command(name="pythonfact", aliases=["pyfact"]) async def get_python_fact(self, ctx: commands.Context) -> None: """Sends a Random fun fact about Python.""" - embed = discord.Embed(title="Python Facts", - description=next(FACTS), - colour=next(COLORS)) - embed.add_field(name="Suggestions", - value="Suggest more facts [here!](https://github.com/python-discord/meta/discussions/93)") + embed = discord.Embed( + title="Python Facts", + description=next(FACTS), + colour=next(COLORS) + ) + embed.add_field( + name="Suggestions", + value="Suggest more facts [here!](https://github.com/python-discord/meta/discussions/93)" + ) await ctx.send(embed=embed) diff --git a/bot/exts/evergreen/snakes/_snakes_cog.py b/bot/exts/evergreen/snakes/_snakes_cog.py index 62795aef..6278c883 100644 --- a/bot/exts/evergreen/snakes/_snakes_cog.py +++ b/bot/exts/evergreen/snakes/_snakes_cog.py @@ -497,9 +497,11 @@ class Snakes(Cog): for i in range(0, 10): page_guess_list.append(f"{HOLE_EMOJI} {HOLE_EMOJI} {HOLE_EMOJI} {HOLE_EMOJI}") page_result_list.append(f"{CROSS_EMOJI} {CROSS_EMOJI} {CROSS_EMOJI} {CROSS_EMOJI}") - board.append(f"`{i+1:02d}` " - f"{page_guess_list[i]} - " - f"{page_result_list[i]}") + board.append( + f"`{i+1:02d}` " + f"{page_guess_list[i]} - " + f"{page_result_list[i]}" + ) board.append(EMPTY_UNICODE) antidote_embed.add_field(name="10 guesses remaining", value="\n".join(board)) board_id = await ctx.send(embed=antidote_embed) # Display board @@ -667,8 +669,14 @@ class Snakes(Cog): ) emoji = "https://emojipedia-us.s3.amazonaws.com/thumbs/60/google/3/snake_1f40d.png" - image = next((url for url in data["image_list"] - if url.endswith(self.valid_image_extensions)), emoji) + + _iter = ( + url + for url in data["image_list"] + if url.endswith(self.valid_image_extensions) + ) + image = next(_iter, emoji) + embed.set_image(url=image) await ctx.send(embed=embed) @@ -693,8 +701,12 @@ class Snakes(Cog): data = await self._get_snek(snake) - image = next((url for url in data["image_list"] - if url.endswith(self.valid_image_extensions)), None) + _iter = ( + url + for url in data["image_list"] + if url.endswith(self.valid_image_extensions) + ) + image = next(_iter, None) embed = Embed( title="Which of the following is the snake in the image?", diff --git a/bot/exts/evergreen/snakes/_utils.py b/bot/exts/evergreen/snakes/_utils.py index d58ee279..998c13a9 100644 --- a/bot/exts/evergreen/snakes/_utils.py +++ b/bot/exts/evergreen/snakes/_utils.py @@ -191,8 +191,11 @@ class PerlinNoiseFactory(object): def get_plain_noise(self, *point) -> float: """Get plain noise for a single point, without taking into account either octaves or tiling.""" if len(point) != self.dimension: - raise ValueError("Expected {0} values, got {1}".format( - self.dimension, len(point))) + raise ValueError( + "Expected {0} values, got {1}".format( + self.dimension, len(point) + ) + ) # Build a list of the (min, max) bounds in each dimension grid_coords = [] -- cgit v1.2.3 From 4ba9c941fc8ceb50cf61cfcb5ae15afc6216c7b2 Mon Sep 17 00:00:00 2001 From: ToxicKidz Date: Mon, 10 May 2021 09:28:43 -0400 Subject: chore: Apply more suggested changes --- bot/exts/easter/bunny_name_generator.py | 1 + bot/exts/evergreen/help.py | 12 +++++++++--- bot/exts/evergreen/snakes/_utils.py | 4 +--- bot/exts/valentines/be_my_valentine.py | 18 ++++++------------ 4 files changed, 17 insertions(+), 18 deletions(-) (limited to 'bot/exts/evergreen/snakes/_utils.py') diff --git a/bot/exts/easter/bunny_name_generator.py b/bot/exts/easter/bunny_name_generator.py index 19a0b0f6..b6523ff6 100644 --- a/bot/exts/easter/bunny_name_generator.py +++ b/bot/exts/easter/bunny_name_generator.py @@ -23,6 +23,7 @@ class BunnyNameGenerator(commands.Cog): new_name = re.split(r"[_.\s]", displayname) if displayname not in new_name: return new_name + return None def find_vowels(self, displayname: str) -> str: """ diff --git a/bot/exts/evergreen/help.py b/bot/exts/evergreen/help.py index bfaf25f1..7e3fdad4 100644 --- a/bot/exts/evergreen/help.py +++ b/bot/exts/evergreen/help.py @@ -2,9 +2,8 @@ import asyncio import itertools import logging -from collections import namedtuple from contextlib import suppress -from typing import Union +from typing import List, NamedTuple, Union from discord import Colour, Embed, HTTPException, Message, Reaction, User from discord.ext import commands @@ -29,7 +28,14 @@ REACTIONS = { DELETE_EMOJI: "stop", } -Cog = namedtuple("Cog", ["name", "description", "commands"]) + +class Cog(NamedTuple): + """Show information about a Cog's name, description and commands.""" + + name: str + description: str + commands: List[Command] + log = logging.getLogger(__name__) diff --git a/bot/exts/evergreen/snakes/_utils.py b/bot/exts/evergreen/snakes/_utils.py index 998c13a9..9b38ffa2 100644 --- a/bot/exts/evergreen/snakes/_utils.py +++ b/bot/exts/evergreen/snakes/_utils.py @@ -192,9 +192,7 @@ class PerlinNoiseFactory(object): """Get plain noise for a single point, without taking into account either octaves or tiling.""" if len(point) != self.dimension: raise ValueError( - "Expected {0} values, got {1}".format( - self.dimension, len(point) - ) + f"Expected {self.dimension} values, got {len(point)}" ) # Build a list of the (min, max) bounds in each dimension diff --git a/bot/exts/valentines/be_my_valentine.py b/bot/exts/valentines/be_my_valentine.py index b9cf6738..d1eea388 100644 --- a/bot/exts/valentines/be_my_valentine.py +++ b/bot/exts/valentines/be_my_valentine.py @@ -151,21 +151,17 @@ class BeMyValentine(commands.Cog): def valentine_check(self, valentine_type: str) -> Tuple[str, str]: """Return the appropriate Valentine type & title based on the invoking user's input.""" if valentine_type is None: - valentine, title = self.random_valentine() + return self.random_valentine() elif valentine_type.lower() in ["p", "poem"]: - valentine = self.valentine_poem() - title = "A poem dedicated to" + return self.valentine_poem(), "A poem dedicated to" elif valentine_type.lower() in ["c", "compliment"]: - valentine = self.valentine_compliment() - title = "A compliment for" + return self.valentine_compliment(), "A compliment for" else: # in this case, the user decides to type his own valentine. - valentine = valentine_type - title = "A message for" - return valentine, title + return valentine_type, "A message for" @staticmethod def random_emoji() -> Tuple[str, str]: @@ -187,13 +183,11 @@ class BeMyValentine(commands.Cog): def valentine_poem(self) -> str: """Grabs a random poem.""" - valentine_poem = random.choice(self.valentines["valentine_poems"]) - return valentine_poem + return random.choice(self.valentines["valentine_poems"]) def valentine_compliment(self) -> str: """Grabs a random compliment.""" - valentine_compliment = random.choice(self.valentines["valentine_compliments"]) - return valentine_compliment + return random.choice(self.valentines["valentine_compliments"]) def setup(bot: Bot) -> None: -- cgit v1.2.3 From 2aa1916d5c8e4832f26f6da4094238e9a0021d1c Mon Sep 17 00:00:00 2001 From: ToxicKidz Date: Thu, 13 May 2021 13:34:06 -0400 Subject: chore: Use pathlib.Path.read_text & write_text over open --- bot/exts/christmas/advent_of_code/_cog.py | 3 +-- bot/exts/easter/april_fools_vids.py | 6 +++--- bot/exts/easter/bunny_name_generator.py | 3 +-- bot/exts/easter/easter_riddle.py | 5 ++--- bot/exts/easter/egg_decorating.py | 6 ++---- bot/exts/easter/egg_facts.py | 5 ++--- bot/exts/easter/egghead_quiz.py | 5 ++--- bot/exts/easter/save_the_planet.py | 4 +--- bot/exts/easter/traditions.py | 3 +-- bot/exts/evergreen/avatar_modification/avatar_modify.py | 4 ++-- bot/exts/evergreen/fun.py | 3 +-- bot/exts/evergreen/magic_8ball.py | 3 +-- bot/exts/evergreen/recommend_game.py | 3 +-- bot/exts/evergreen/snakes/_converter.py | 7 ++----- bot/exts/evergreen/snakes/_utils.py | 5 ++--- bot/exts/evergreen/speedrun.py | 4 ++-- bot/exts/evergreen/trivia_quiz.py | 4 +--- bot/exts/halloween/8ball.py | 3 +-- bot/exts/halloween/halloween_facts.py | 3 +-- bot/exts/halloween/halloweenify.py | 5 ++--- bot/exts/halloween/monsterbio.py | 5 +++-- bot/exts/halloween/monstersurvey.py | 6 ++---- bot/exts/halloween/spookynamerate.py | 3 +-- bot/exts/halloween/spookyrating.py | 6 +++--- bot/exts/pride/drag_queen_name.py | 3 +-- bot/exts/pride/pride_anthem.py | 4 +--- bot/exts/pride/pride_facts.py | 3 +-- bot/exts/valentines/be_my_valentine.py | 6 ++---- bot/exts/valentines/lovecalculator.py | 5 ++--- bot/exts/valentines/myvalenstate.py | 3 +-- bot/exts/valentines/pickuplines.py | 9 ++++----- bot/exts/valentines/savethedate.py | 5 ++--- bot/exts/valentines/valentine_zodiac.py | 16 ++++++++-------- bot/exts/valentines/whoisvalentine.py | 3 +-- 34 files changed, 63 insertions(+), 98 deletions(-) (limited to 'bot/exts/evergreen/snakes/_utils.py') diff --git a/bot/exts/christmas/advent_of_code/_cog.py b/bot/exts/christmas/advent_of_code/_cog.py index 863d2a21..ce6a4cb6 100644 --- a/bot/exts/christmas/advent_of_code/_cog.py +++ b/bot/exts/christmas/advent_of_code/_cog.py @@ -279,8 +279,7 @@ class AdventOfCode(commands.Cog): def _build_about_embed(self) -> discord.Embed: """Build and return the informational "About AoC" embed from the resources file.""" - with self.about_aoc_filepath.open("r", encoding="utf8") as f: - embed_fields = json.load(f) + embed_fields = json.loads(self.about_aoc_filepath.read_text("utf8")) about_embed = discord.Embed( title=self._base_url, diff --git a/bot/exts/easter/april_fools_vids.py b/bot/exts/easter/april_fools_vids.py index 3ce1f72a..5ef40704 100644 --- a/bot/exts/easter/april_fools_vids.py +++ b/bot/exts/easter/april_fools_vids.py @@ -1,6 +1,7 @@ import logging import random -from json import load +from json import loads +from pathlib import Path from discord.ext import commands @@ -8,8 +9,7 @@ from bot.bot import Bot log = logging.getLogger(__name__) -with open("bot/resources/easter/april_fools_vids.json", encoding="utf-8") as f: - ALL_VIDS = load(f) +ALL_VIDS = loads(Path("bot/resources/easter/april_fools_vids.json").read_text("utf-8")) class AprilFoolVideos(commands.Cog): diff --git a/bot/exts/easter/bunny_name_generator.py b/bot/exts/easter/bunny_name_generator.py index 5e3b014d..adde8704 100644 --- a/bot/exts/easter/bunny_name_generator.py +++ b/bot/exts/easter/bunny_name_generator.py @@ -11,8 +11,7 @@ from bot.bot import Bot log = logging.getLogger(__name__) -with Path("bot/resources/easter/bunny_names.json").open("r", encoding="utf8") as f: - BUNNY_NAMES = json.load(f) +BUNNY_NAMES = json.loads(Path("bot/resources/easter/bunny_names.json").read_text("utf8")) class BunnyNameGenerator(commands.Cog): diff --git a/bot/exts/easter/easter_riddle.py b/bot/exts/easter/easter_riddle.py index 9a253a6a..01b956f1 100644 --- a/bot/exts/easter/easter_riddle.py +++ b/bot/exts/easter/easter_riddle.py @@ -1,7 +1,7 @@ import asyncio import logging import random -from json import load +from json import loads from pathlib import Path import discord @@ -12,8 +12,7 @@ from bot.constants import Colours, NEGATIVE_REPLIES log = logging.getLogger(__name__) -with Path("bot/resources/easter/easter_riddle.json").open("r", encoding="utf8") as f: - RIDDLE_QUESTIONS = load(f) +RIDDLE_QUESTIONS = loads(Path("bot/resources/easter/easter_riddle.json").read_text("utf8")) TIMELIMIT = 10 diff --git a/bot/exts/easter/egg_decorating.py b/bot/exts/easter/egg_decorating.py index 3744989d..7448f702 100644 --- a/bot/exts/easter/egg_decorating.py +++ b/bot/exts/easter/egg_decorating.py @@ -15,11 +15,9 @@ from bot.utils import helpers log = logging.getLogger(__name__) -with open(Path("bot/resources/evergreen/html_colours.json"), encoding="utf8") as f: - HTML_COLOURS = json.load(f) +HTML_COLOURS = json.loads(Path("bot/resources/evergreen/html_colours.json").read_text("utf8")) -with open(Path("bot/resources/evergreen/xkcd_colours.json"), encoding="utf8") as f: - XKCD_COLOURS = json.load(f) +XKCD_COLOURS = json.loads(Path("bot/resources/evergreen/xkcd_colours.json").read_text("utf8")) COLOURS = [ (255, 0, 0, 255), (255, 128, 0, 255), (255, 255, 0, 255), (0, 255, 0, 255), diff --git a/bot/exts/easter/egg_facts.py b/bot/exts/easter/egg_facts.py index 8c93ca7b..c1c43f80 100644 --- a/bot/exts/easter/egg_facts.py +++ b/bot/exts/easter/egg_facts.py @@ -1,6 +1,6 @@ import logging import random -from json import load +from json import loads from pathlib import Path import discord @@ -30,8 +30,7 @@ class EasterFacts(commands.Cog): 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") - with p.open(encoding="utf8") as f: - return load(f) + return loads(p.read_text("utf8")) @seasonal_task(Month.APRIL) async def send_egg_fact_daily(self) -> None: diff --git a/bot/exts/easter/egghead_quiz.py b/bot/exts/easter/egghead_quiz.py index b6b1593d..4b67310f 100644 --- a/bot/exts/easter/egghead_quiz.py +++ b/bot/exts/easter/egghead_quiz.py @@ -1,7 +1,7 @@ import asyncio import logging import random -from json import load +from json import loads from pathlib import Path from typing import Union @@ -13,8 +13,7 @@ from bot.constants import Colours log = logging.getLogger(__name__) -with open(Path("bot/resources/easter/egghead_questions.json"), "r", encoding="utf8") as f: - EGGHEAD_QUESTIONS = load(f) +EGGHEAD_QUESTIONS = loads(Path("bot/resources/easter/egghead_questions.json").read_text("utf8")) EMOJIS = [ diff --git a/bot/exts/easter/save_the_planet.py b/bot/exts/easter/save_the_planet.py index 444bb030..1bd515f2 100644 --- a/bot/exts/easter/save_the_planet.py +++ b/bot/exts/easter/save_the_planet.py @@ -7,9 +7,7 @@ from discord.ext import commands from bot.bot import Bot from bot.utils.randomization import RandomCycle - -with Path("bot/resources/easter/save_the_planet.json").open("r", encoding="utf8") as f: - EMBED_DATA = RandomCycle(json.load(f)) +EMBED_DATA = RandomCycle(json.loads(Path("bot/resources/easter/save_the_planet.json").read_text("utf8"))) class SaveThePlanet(commands.Cog): diff --git a/bot/exts/easter/traditions.py b/bot/exts/easter/traditions.py index cb70f2d0..93404f3e 100644 --- a/bot/exts/easter/traditions.py +++ b/bot/exts/easter/traditions.py @@ -9,8 +9,7 @@ from bot.bot import Bot log = logging.getLogger(__name__) -with open(Path("bot/resources/easter/traditions.json"), "r", encoding="utf8") as f: - traditions = json.load(f) +traditions = json.loads(Path("bot/resources/easter/traditions.json").read_text("utf8")) class Traditions(commands.Cog): diff --git a/bot/exts/evergreen/avatar_modification/avatar_modify.py b/bot/exts/evergreen/avatar_modification/avatar_modify.py index 5685b2c1..199b6dcb 100644 --- a/bot/exts/evergreen/avatar_modification/avatar_modify.py +++ b/bot/exts/evergreen/avatar_modification/avatar_modify.py @@ -6,6 +6,7 @@ import string import typing as t import unicodedata from concurrent.futures import ThreadPoolExecutor +from pathlib import Path import discord from aiohttp import client_exceptions @@ -27,8 +28,7 @@ MAX_SQUARES = 10_000 T = t.TypeVar("T") -with open("bot/resources/pride/gender_options.json") as f: - GENDER_OPTIONS = json.load(f) +GENDER_OPTIONS = json.loads(Path("bot/resources/pride/gender_options.json").read_text("utf8")) async def in_executor(func: t.Callable[..., T], *args) -> T: diff --git a/bot/exts/evergreen/fun.py b/bot/exts/evergreen/fun.py index ed51358c..3b266e1b 100644 --- a/bot/exts/evergreen/fun.py +++ b/bot/exts/evergreen/fun.py @@ -56,8 +56,7 @@ class Fun(Cog): def __init__(self, bot: Bot) -> None: self.bot = bot - with Path("bot/resources/evergreen/caesar_info.json").open("r", encoding="UTF-8") as f: - self._caesar_cipher_embed = json.load(f) + self._caesar_cipher_embed = json.loads(Path("bot/resources/evergreen/caesar_info.json").read_text("UTF-8")) @staticmethod def _get_random_die() -> str: diff --git a/bot/exts/evergreen/magic_8ball.py b/bot/exts/evergreen/magic_8ball.py index 7c9b929d..4b3ed2a4 100644 --- a/bot/exts/evergreen/magic_8ball.py +++ b/bot/exts/evergreen/magic_8ball.py @@ -14,8 +14,7 @@ class Magic8ball(commands.Cog): """A Magic 8ball command to respond to a user's question.""" def __init__(self): - with open(Path("bot/resources/evergreen/magic8ball.json"), "r", encoding="utf8") as file: - self.answers = json.load(file) + 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: diff --git a/bot/exts/evergreen/recommend_game.py b/bot/exts/evergreen/recommend_game.py index 340a42d3..56596020 100644 --- a/bot/exts/evergreen/recommend_game.py +++ b/bot/exts/evergreen/recommend_game.py @@ -13,8 +13,7 @@ game_recs = [] # Populate the list `game_recs` with resource files for rec_path in Path("bot/resources/evergreen/game_recs").glob("*.json"): - with rec_path.open(encoding="utf8") as file: - data = json.load(file) + data = json.loads(rec_path.read_text("utf8")) game_recs.append(data) shuffle(game_recs) diff --git a/bot/exts/evergreen/snakes/_converter.py b/bot/exts/evergreen/snakes/_converter.py index 0ca10d6c..26bde611 100644 --- a/bot/exts/evergreen/snakes/_converter.py +++ b/bot/exts/evergreen/snakes/_converter.py @@ -63,13 +63,10 @@ class Snake(Converter): """Build list of snakes from the static snake resources.""" # Get all the snakes if cls.snakes is None: - with (SNAKE_RESOURCES / "snake_names.json").open(encoding="utf8") as snakefile: - cls.snakes = json.load(snakefile) - + cls.snakes = json.loads((SNAKE_RESOURCES / "snake_names.json").read_text("utf8")) # Get the special cases if cls.special_cases is None: - with (SNAKE_RESOURCES / "special_snakes.json").open(encoding="utf8") as snakefile: - special_cases = json.load(snakefile) + special_cases = json.loads((SNAKE_RESOURCES / "special_snakes.json").read_text("utf8")) cls.special_cases = {snake["name"].lower(): snake for snake in special_cases} @classmethod diff --git a/bot/exts/evergreen/snakes/_utils.py b/bot/exts/evergreen/snakes/_utils.py index 9b38ffa2..8b39f217 100644 --- a/bot/exts/evergreen/snakes/_utils.py +++ b/bot/exts/evergreen/snakes/_utils.py @@ -114,8 +114,7 @@ ANGLE_RANGE = math.pi * 2 def get_resource(file: str) -> List[dict]: """Load Snake resources JSON.""" - with (SNAKE_RESOURCES / f"{file}.json").open(encoding="utf-8") as snakefile: - return json.load(snakefile) + return json.loads((SNAKE_RESOURCES / f"{file}.json").read_text("utf-8")) def smoothstep(t: float) -> float: @@ -560,7 +559,7 @@ class SnakeAndLaddersGame: self.state = "roll" for user in self.players: self.round_has_rolled[user.id] = False - board_img = Image.open(str(SNAKE_RESOURCES / "snakes_and_ladders" / "board.jpg")) + board_img = Image.open(SNAKE_RESOURCES / "snakes_and_ladders" / "board.jpg") player_row_size = math.ceil(MAX_PLAYERS / 2) for i, player in enumerate(self.players): diff --git a/bot/exts/evergreen/speedrun.py b/bot/exts/evergreen/speedrun.py index d9820287..774eff81 100644 --- a/bot/exts/evergreen/speedrun.py +++ b/bot/exts/evergreen/speedrun.py @@ -8,8 +8,8 @@ from discord.ext import commands from bot.bot import Bot log = logging.getLogger(__name__) -with Path("bot/resources/evergreen/speedrun_links.json").open(encoding="utf8") as file: - LINKS = json.load(file) + +LINKS = json.loads(Path("bot/resources/evergreen/speedrun_links.json").read_text("utf8")) class Speedrun(commands.Cog): diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index 1953253b..9db201ef 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -41,9 +41,7 @@ class TriviaQuiz(commands.Cog): def load_questions() -> dict: """Load the questions from the JSON file.""" p = Path("bot", "resources", "evergreen", "trivia_quiz.json") - with p.open(encoding="utf8") as json_data: - questions = json.load(json_data) - return questions + return json.loads(p.read_text("utf8")) @commands.group(name="quiz", aliases=["trivia"], invoke_without_command=True) async def quiz_game(self, ctx: commands.Context, category: str = None) -> None: diff --git a/bot/exts/halloween/8ball.py b/bot/exts/halloween/8ball.py index d6c5a299..a2431190 100644 --- a/bot/exts/halloween/8ball.py +++ b/bot/exts/halloween/8ball.py @@ -10,8 +10,7 @@ from bot.bot import Bot log = logging.getLogger(__name__) -with Path("bot/resources/halloween/responses.json").open("r", encoding="utf8") as f: - RESPONSES = json.load(f) +RESPONSES = json.loads(Path("bot/resources/halloween/responses.json").read_text("utf8")) class SpookyEightBall(commands.Cog): diff --git a/bot/exts/halloween/halloween_facts.py b/bot/exts/halloween/halloween_facts.py index 3a89b5aa..98cc2db0 100644 --- a/bot/exts/halloween/halloween_facts.py +++ b/bot/exts/halloween/halloween_facts.py @@ -30,8 +30,7 @@ class HalloweenFacts(commands.Cog): """A Cog for displaying interesting facts about Halloween.""" def __init__(self): - with Path("bot/resources/halloween/halloween_facts.json").open("r", encoding="utf8") as file: - self.halloween_facts = json.load(file) + 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]: diff --git a/bot/exts/halloween/halloweenify.py b/bot/exts/halloween/halloweenify.py index df55b55d..e839950a 100644 --- a/bot/exts/halloween/halloweenify.py +++ b/bot/exts/halloween/halloweenify.py @@ -1,5 +1,5 @@ import logging -from json import load +from json import loads from pathlib import Path from random import choice @@ -21,8 +21,7 @@ class Halloweenify(commands.Cog): async def halloweenify(self, ctx: commands.Context) -> None: """Change your nickname into a much spookier one!""" async with ctx.typing(): - with open(Path("bot/resources/halloween/halloweenify.json"), "r", encoding="utf8") as f: - data = load(f) + 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"]) diff --git a/bot/exts/halloween/monsterbio.py b/bot/exts/halloween/monsterbio.py index 1aaba7bb..69e898cb 100644 --- a/bot/exts/halloween/monsterbio.py +++ b/bot/exts/halloween/monsterbio.py @@ -11,8 +11,9 @@ from bot.constants import Colours log = logging.getLogger(__name__) -with open(Path("bot/resources/halloween/monster.json"), "r", encoding="utf8") as f: - TEXT_OPTIONS = json.load(f) # Data for a mad-lib style generation of text +TEXT_OPTIONS = json.loads( + Path("bot/resources/halloween/monster.json").read_text("utf8") +) # Data for a mad-lib style generation of text class MonsterBio(commands.Cog): diff --git a/bot/exts/halloween/monstersurvey.py b/bot/exts/halloween/monstersurvey.py index 231454ea..240a97db 100644 --- a/bot/exts/halloween/monstersurvey.py +++ b/bot/exts/halloween/monstersurvey.py @@ -26,14 +26,12 @@ class MonsterSurvey(Cog): def __init__(self): """Initializes values for the bot to use within the voting commands.""" self.registry_path = pathlib.Path("bot", "resources", "halloween", "monstersurvey.json") - with self.registry_path.open(encoding="utf8") as data: - self.voter_registry = json.load(data) + self.voter_registry = json.loads(self.registry_path.read_text("utf8")) def json_write(self) -> None: """Write voting results to a local JSON file.""" log.info("Saved Monster Survey Results") - with self.registry_path.open("w", encoding="utf8") as data: - json.dump(self.voter_registry, data, indent=2) + self.registry_path.write_text(json.dumps(self.voter_registry, indent=2)) def cast_vote(self, id: int, monster: str) -> None: """ diff --git a/bot/exts/halloween/spookynamerate.py b/bot/exts/halloween/spookynamerate.py index 87172922..63040289 100644 --- a/bot/exts/halloween/spookynamerate.py +++ b/bot/exts/halloween/spookynamerate.py @@ -371,8 +371,7 @@ class SpookyNameRate(Cog): @staticmethod def load_json(file: Path) -> Dict[str, str]: """Loads a JSON file and returns its contents.""" - with file.open("r", encoding="utf-8") as f: - return json.load(f) + return json.loads(file.read_text("utf8")) @staticmethod def in_allowed_month() -> bool: diff --git a/bot/exts/halloween/spookyrating.py b/bot/exts/halloween/spookyrating.py index 6c79fbed..105d2164 100644 --- a/bot/exts/halloween/spookyrating.py +++ b/bot/exts/halloween/spookyrating.py @@ -3,6 +3,7 @@ import json import logging import random from pathlib import Path +from typing import Dict import discord from discord.ext import commands @@ -12,9 +13,8 @@ from bot.constants import Colours log = logging.getLogger(__name__) -with Path("bot/resources/halloween/spooky_rating.json").open(encoding="utf8") as file: - data = json.load(file) - SPOOKY_DATA = sorted((int(key), value) for key, value in data.items()) +data: Dict[str, Dict[str, str]] = json.loads(Path("bot/resources/halloween/spooky_rating.json").read_text("utf8")) +SPOOKY_DATA = sorted((int(key), value) for key, value in data.items()) class SpookyRating(commands.Cog): diff --git a/bot/exts/pride/drag_queen_name.py b/bot/exts/pride/drag_queen_name.py index d9424001..6bf43913 100644 --- a/bot/exts/pride/drag_queen_name.py +++ b/bot/exts/pride/drag_queen_name.py @@ -19,8 +19,7 @@ class DragNames(commands.Cog): @staticmethod def load_names() -> list: """Loads a list of drag queen names.""" - with Path("bot/resources/pride/drag_queen_names.json").open(encoding="utf8") as f: - return json.load(f) + 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: diff --git a/bot/exts/pride/pride_anthem.py b/bot/exts/pride/pride_anthem.py index a7f8d7ef..21b7e468 100644 --- a/bot/exts/pride/pride_anthem.py +++ b/bot/exts/pride/pride_anthem.py @@ -36,9 +36,7 @@ class PrideAnthem(commands.Cog): @staticmethod def load_vids() -> list: """Loads a list of videos from the resources folder as dictionaries.""" - with open(Path("bot/resources/pride/anthems.json"), "r", encoding="utf8") as f: - anthems = json.load(f) - return anthems + 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 6d06cf64..47e69a03 100644 --- a/bot/exts/pride/pride_facts.py +++ b/bot/exts/pride/pride_facts.py @@ -28,8 +28,7 @@ class PrideFacts(commands.Cog): @staticmethod def load_facts() -> dict: """Loads a dictionary of years mapping to lists of facts.""" - with open(Path("bot/resources/pride/facts.json"), "r", encoding="utf8") as f: - return json.load(f) + return json.loads(Path("bot/resources/pride/facts.json").read_text("utf8")) @seasonal_task(Month.JUNE) async def send_pride_fact_daily(self) -> None: diff --git a/bot/exts/valentines/be_my_valentine.py b/bot/exts/valentines/be_my_valentine.py index d1eea388..8b522a72 100644 --- a/bot/exts/valentines/be_my_valentine.py +++ b/bot/exts/valentines/be_my_valentine.py @@ -1,6 +1,6 @@ import logging import random -from json import load +from json import loads from pathlib import Path from typing import Tuple @@ -28,9 +28,7 @@ class BeMyValentine(commands.Cog): def load_json() -> dict: """Load Valentines messages from the static resources.""" p = Path("bot/resources/valentines/bemyvalentine_valentines.json") - with p.open(encoding="utf8") as json_data: - valentines = load(json_data) - return valentines + return loads(p.read_text("utf8")) @in_month(Month.FEBRUARY) @commands.group(name="lovefest") diff --git a/bot/exts/valentines/lovecalculator.py b/bot/exts/valentines/lovecalculator.py index 8a4c71eb..b10b7bca 100644 --- a/bot/exts/valentines/lovecalculator.py +++ b/bot/exts/valentines/lovecalculator.py @@ -15,9 +15,8 @@ from bot.bot import Bot log = logging.getLogger(__name__) -with Path("bot/resources/valentines/love_matches.json").open(encoding="utf8") as file: - LOVE_DATA = json.load(file) - LOVE_DATA = sorted((int(key), value) for key, value in LOVE_DATA.items()) +LOVE_DATA = json.loads(Path("bot/resources/valentines/love_matches.json").read_text("utf8")) +LOVE_DATA = sorted((int(key), value) for key, value in LOVE_DATA.items()) class LoveCalculator(Cog): diff --git a/bot/exts/valentines/myvalenstate.py b/bot/exts/valentines/myvalenstate.py index 1c67984b..d2409dcc 100644 --- a/bot/exts/valentines/myvalenstate.py +++ b/bot/exts/valentines/myvalenstate.py @@ -12,8 +12,7 @@ from bot.constants import Colours log = logging.getLogger(__name__) -with open(Path("bot/resources/valentines/valenstates.json"), "r", encoding="utf8") as file: - STATES = json.load(file) +STATES = json.loads(Path("bot/resources/valentines/valenstates.json").read_text("utf8")) class MyValenstate(commands.Cog): diff --git a/bot/exts/valentines/pickuplines.py b/bot/exts/valentines/pickuplines.py index 909169e6..00741a72 100644 --- a/bot/exts/valentines/pickuplines.py +++ b/bot/exts/valentines/pickuplines.py @@ -1,6 +1,6 @@ import logging import random -from json import load +from json import loads from pathlib import Path import discord @@ -11,8 +11,7 @@ from bot.constants import Colours log = logging.getLogger(__name__) -with open(Path("bot/resources/valentines/pickup_lines.json"), "r", encoding="utf8") as f: - pickup_lines = load(f) +PICKUP_LINES = loads(Path("bot/resources/valentines/pickup_lines.json").read_text("utf8")) class PickupLine(commands.Cog): @@ -25,14 +24,14 @@ class PickupLine(commands.Cog): Note that most of them are very cheesy. """ - random_line = random.choice(pickup_lines["lines"]) + random_line = random.choice(PICKUP_LINES["lines"]) embed = discord.Embed( title=":cheese: Your pickup line :cheese:", description=random_line["line"], color=Colours.pink ) embed.set_thumbnail( - url=random_line.get("image", pickup_lines["placeholder"]) + url=random_line.get("image", PICKUP_LINES["placeholder"]) ) await ctx.send(embed=embed) diff --git a/bot/exts/valentines/savethedate.py b/bot/exts/valentines/savethedate.py index cc16f5c9..ffe559d6 100644 --- a/bot/exts/valentines/savethedate.py +++ b/bot/exts/valentines/savethedate.py @@ -1,6 +1,6 @@ import logging import random -from json import load +from json import loads from pathlib import Path import discord @@ -13,8 +13,7 @@ log = logging.getLogger(__name__) HEART_EMOJIS = [":heart:", ":gift_heart:", ":revolving_hearts:", ":sparkling_heart:", ":two_hearts:"] -with open(Path("bot/resources/valentines/date_ideas.json"), "r", encoding="utf8") as f: - VALENTINES_DATES = load(f) +VALENTINES_DATES = loads(Path("bot/resources/valentines/date_ideas.json").read_text("utf8")) class SaveTheDate(commands.Cog): diff --git a/bot/exts/valentines/valentine_zodiac.py b/bot/exts/valentines/valentine_zodiac.py index a444a355..45d1edd5 100644 --- a/bot/exts/valentines/valentine_zodiac.py +++ b/bot/exts/valentines/valentine_zodiac.py @@ -29,14 +29,14 @@ class ValentineZodiac(commands.Cog): """Load zodiac compatibility from static JSON resource.""" explanation_file = Path("bot/resources/valentines/zodiac_explanation.json") compatibility_file = Path("bot/resources/valentines/zodiac_compatibility.json") - with explanation_file.open(encoding="utf8") as json_data: - zodiac_fact = json.load(json_data) - for zodiac_data in zodiac_fact.values(): - zodiac_data["start_at"] = datetime.fromisoformat(zodiac_data["start_at"]) - zodiac_data["end_at"] = datetime.fromisoformat(zodiac_data["end_at"]) - - with compatibility_file.open(encoding="utf8") as json_data: - zodiacs = json.load(json_data) + + zodiac_fact = json.loads(explanation_file.read_text("utf8")) + + for zodiac_data in zodiac_fact.values(): + zodiac_data["start_at"] = datetime.fromisoformat(zodiac_data["start_at"]) + zodiac_data["end_at"] = datetime.fromisoformat(zodiac_data["end_at"]) + + zodiacs = json.loads(compatibility_file.read_text("utf8")) return zodiacs, zodiac_fact diff --git a/bot/exts/valentines/whoisvalentine.py b/bot/exts/valentines/whoisvalentine.py index 3f23201f..211b1f27 100644 --- a/bot/exts/valentines/whoisvalentine.py +++ b/bot/exts/valentines/whoisvalentine.py @@ -11,8 +11,7 @@ from bot.constants import Colours log = logging.getLogger(__name__) -with open(Path("bot/resources/valentines/valentine_facts.json"), "r", encoding="utf8") as file: - FACTS = json.load(file) +FACTS = json.loads(Path("bot/resources/valentines/valentine_facts.json").read_text("utf8")) class ValentineFacts(commands.Cog): -- cgit v1.2.3 From 92c33d625068b9b39564dbf4fb9f6c1102711955 Mon Sep 17 00:00:00 2001 From: ToxicKidz Date: Fri, 14 May 2021 12:34:30 -0400 Subject: chore: Refactor more code to follow our style guide --- bot/exts/evergreen/avatar_modification/_effects.py | 6 +- bot/exts/evergreen/connect_four.py | 70 +++++++++++----------- bot/exts/evergreen/game.py | 6 +- bot/exts/evergreen/issues.py | 16 ++--- bot/exts/evergreen/minesweeper.py | 12 ++-- bot/exts/evergreen/movie.py | 6 +- bot/exts/evergreen/snakes/_snakes_cog.py | 10 +++- bot/exts/evergreen/snakes/_utils.py | 16 ++--- bot/exts/evergreen/wolfram.py | 16 +++-- bot/exts/halloween/candy_collection.py | 8 ++- bot/exts/halloween/monstersurvey.py | 23 +++---- bot/exts/valentines/movie_generator.py | 6 +- bot/utils/__init__.py | 11 +++- bot/utils/checks.py | 30 ++++++---- 14 files changed, 136 insertions(+), 100 deletions(-) (limited to 'bot/exts/evergreen/snakes/_utils.py') diff --git a/bot/exts/evergreen/avatar_modification/_effects.py b/bot/exts/evergreen/avatar_modification/_effects.py index d2370b4b..9339ecc4 100644 --- a/bot/exts/evergreen/avatar_modification/_effects.py +++ b/bot/exts/evergreen/avatar_modification/_effects.py @@ -251,7 +251,7 @@ class PfpEffects: total_width = multiplier * single_wdith total_height = multiplier * single_height - new_image = Image.new('RGBA', (total_width, total_height), (250, 250, 250)) + new_image = Image.new("RGBA", (total_width, total_height), (250, 250, 250)) width_multiplier = 0 height = 0 @@ -275,13 +275,13 @@ class PfpEffects: def mosaic_effect(img_bytes: bytes, squares: int, file_name: str) -> discord.File: """Seperate function run from an executor which turns an image into a mosaic.""" avatar = Image.open(BytesIO(img_bytes)) - avatar = avatar.convert('RGBA').resize((1024, 1024)) + avatar = avatar.convert("RGBA").resize((1024, 1024)) img_squares = PfpEffects.split_image(avatar, squares) new_img = PfpEffects.join_images(img_squares) bufferedio = BytesIO() - new_img.save(bufferedio, format='PNG') + new_img.save(bufferedio, format="PNG") bufferedio.seek(0) return discord.File(bufferedio, filename=file_name) diff --git a/bot/exts/evergreen/connect_four.py b/bot/exts/evergreen/connect_four.py index dc365a70..7a39d442 100644 --- a/bot/exts/evergreen/connect_four.py +++ b/bot/exts/evergreen/connect_four.py @@ -22,13 +22,13 @@ class Game: """A Connect 4 Game.""" def __init__( - self, - bot: Bot, - channel: discord.TextChannel, - player1: discord.Member, - player2: typing.Optional[discord.Member], - tokens: typing.List[str], - size: int = 7 + self, + bot: Bot, + channel: discord.TextChannel, + player1: discord.Member, + player2: typing.Optional[discord.Member], + tokens: typing.List[str], + size: int = 7 ) -> None: self.bot = bot @@ -286,20 +286,20 @@ class ConnectFour(commands.Cog): return True def get_player( - self, - ctx: commands.Context, - announcement: discord.Message, - reaction: discord.Reaction, - user: discord.Member + self, + ctx: commands.Context, + announcement: discord.Message, + reaction: discord.Reaction, + user: discord.Member ) -> bool: """Predicate checking the criteria for the announcement message.""" if self.already_playing(ctx.author): # If they've joined a game since requesting a player 2 return True # Is dealt with later on if ( - user.id not in (ctx.me.id, ctx.author.id) - and str(reaction.emoji) == Emojis.hand_raised - and reaction.message.id == announcement.id + user.id not in (ctx.me.id, ctx.author.id) + and str(reaction.emoji) == Emojis.hand_raised + and reaction.message.id == announcement.id ): if self.already_playing(user): self.bot.loop.create_task(ctx.send(f"{user.mention} You're already playing a game!")) @@ -316,9 +316,9 @@ class ConnectFour(commands.Cog): return True if ( - user.id == ctx.author.id - and str(reaction.emoji) == CROSS_EMOJI - and reaction.message.id == announcement.id + user.id == ctx.author.id + and str(reaction.emoji) == CROSS_EMOJI + and reaction.message.id == announcement.id ): return True return False @@ -329,7 +329,7 @@ class ConnectFour(commands.Cog): @staticmethod def check_emojis( - e1: EMOJI_CHECK, e2: EMOJI_CHECK + e1: EMOJI_CHECK, e2: EMOJI_CHECK ) -> typing.Tuple[bool, typing.Optional[str]]: """Validate the emojis, the user put.""" if isinstance(e1, str) and emojis.count(e1) != 1: @@ -339,12 +339,12 @@ class ConnectFour(commands.Cog): return True, None async def _play_game( - self, - ctx: commands.Context, - user: typing.Optional[discord.Member], - board_size: int, - emoji1: str, - emoji2: str + self, + ctx: commands.Context, + user: typing.Optional[discord.Member], + board_size: int, + emoji1: str, + emoji2: str ) -> None: """Helper for playing a game of connect four.""" self.tokens = [":white_circle:", str(emoji1), str(emoji2)] @@ -369,11 +369,11 @@ class ConnectFour(commands.Cog): case_insensitive=True ) async def connect_four( - self, - ctx: commands.Context, - board_size: int = 7, - emoji1: EMOJI_CHECK = "\U0001f535", - emoji2: EMOJI_CHECK = "\U0001f534" + self, + ctx: commands.Context, + board_size: int = 7, + emoji1: EMOJI_CHECK = "\U0001f535", + emoji2: EMOJI_CHECK = "\U0001f534" ) -> None: """ Play the classic game of Connect Four with someone! @@ -430,11 +430,11 @@ class ConnectFour(commands.Cog): @guild_only() @connect_four.command(aliases=["bot", "computer", "cpu"]) async def ai( - self, - ctx: commands.Context, - board_size: int = 7, - emoji1: EMOJI_CHECK = "\U0001f535", - emoji2: EMOJI_CHECK = "\U0001f534" + self, + ctx: commands.Context, + board_size: int = 7, + emoji1: EMOJI_CHECK = "\U0001f535", + emoji2: EMOJI_CHECK = "\U0001f534" ) -> None: """Play Connect Four against a computer player.""" check, emoji = self.check_emojis(emoji1, emoji2) diff --git a/bot/exts/evergreen/game.py b/bot/exts/evergreen/game.py index 6f01d81c..43f64be7 100644 --- a/bot/exts/evergreen/game.py +++ b/bot/exts/evergreen/game.py @@ -374,8 +374,10 @@ class Games(Cog): release_date = dt.utcfromtimestamp(data["first_release_date"]).date() if "first_release_date" in data else "?" # Create Age Ratings value - rating = ", ".join(f"{AgeRatingCategories(age['category']).name} {AgeRatings(age['rating']).name}" - for age in data["age_ratings"]) if "age_ratings" in data else "?" + rating = ", ".join( + f"{AgeRatingCategories(age['category']).name} {AgeRatings(age['rating']).name}" + for age in data["age_ratings"] + ) if "age_ratings" in data else "?" companies = [c["company"]["name"] for c in data["involved_companies"]] if "involved_companies" in data else "?" diff --git a/bot/exts/evergreen/issues.py b/bot/exts/evergreen/issues.py index 5bbc57c6..b67aa4a6 100644 --- a/bot/exts/evergreen/issues.py +++ b/bot/exts/evergreen/issues.py @@ -162,9 +162,9 @@ class Issues(commands.Cog): @staticmethod def format_embed( - results: t.List[t.Union[IssueState, FetchError]], - user: str, - repository: t.Optional[str] = None + results: t.List[t.Union[IssueState, FetchError]], + user: str, + repository: t.Optional[str] = None ) -> discord.Embed: """Take a list of IssueState or FetchError and format a Discord embed for them.""" description_list = [] @@ -187,11 +187,11 @@ class Issues(commands.Cog): @whitelist_override(channels=WHITELISTED_CHANNELS, categories=WHITELISTED_CATEGORIES) @commands.command(aliases=("pr",)) async def issue( - self, - ctx: commands.Context, - numbers: commands.Greedy[int], - repository: str = "sir-lancebot", - user: str = "python-discord" + self, + ctx: commands.Context, + numbers: commands.Greedy[int], + repository: str = "sir-lancebot", + user: str = "python-discord" ) -> None: """Command to retrieve issue(s) from a GitHub repository.""" # Remove duplicates diff --git a/bot/exts/evergreen/minesweeper.py b/bot/exts/evergreen/minesweeper.py index 7a31dfde..932358f9 100644 --- a/bot/exts/evergreen/minesweeper.py +++ b/bot/exts/evergreen/minesweeper.py @@ -212,12 +212,12 @@ class Minesweeper(commands.Cog): return True async def reveal_one( - self, - ctx: commands.Context, - revealed: GameBoard, - board: GameBoard, - x: int, - y: int + self, + ctx: commands.Context, + revealed: GameBoard, + board: GameBoard, + x: int, + y: int ) -> bool: """ Reveal one square. diff --git a/bot/exts/evergreen/movie.py b/bot/exts/evergreen/movie.py index fa284417..ff23df4c 100644 --- a/bot/exts/evergreen/movie.py +++ b/bot/exts/evergreen/movie.py @@ -79,8 +79,10 @@ class Movie(Cog): # Check if "results" is in result. If not, throw error. if "results" not in result: - err_msg = f"There is problem while making TMDB API request. Response Code: {result['status_code']}, " \ - f"{result['status_message']}." + err_msg = ( + f"There is problem while making TMDB API request. Response Code: {result['status_code']}, " + f"{result['status_message']}." + ) await ctx.send(err_msg) logger.warning(err_msg) diff --git a/bot/exts/evergreen/snakes/_snakes_cog.py b/bot/exts/evergreen/snakes/_snakes_cog.py index c50b23c5..07d3c363 100644 --- a/bot/exts/evergreen/snakes/_snakes_cog.py +++ b/bot/exts/evergreen/snakes/_snakes_cog.py @@ -579,9 +579,13 @@ class Snakes(Cog): antidote_embed = Embed(color=SNAKE_COLOR, title="Antidote") antidote_embed.set_author(name=ctx.author.name, icon_url=ctx.author.avatar_url) antidote_embed.set_image(url="https://media.giphy.com/media/ceeN6U57leAhi/giphy.gif") - antidote_embed.add_field(name=EMPTY_UNICODE, - value=f"Sorry you didnt make the antidote in time.\n" - f"The formula was {' '.join(antidote_answer)}") + antidote_embed.add_field( + name=EMPTY_UNICODE, + value=( + f"Sorry you didnt make the antidote in time.\n" + f"The formula was {' '.join(antidote_answer)}" + ) + ) await board_id.edit(embed=antidote_embed) log.debug("Ending pagination and removing all reactions...") diff --git a/bot/exts/evergreen/snakes/_utils.py b/bot/exts/evergreen/snakes/_utils.py index 8b39f217..0a5894b7 100644 --- a/bot/exts/evergreen/snakes/_utils.py +++ b/bot/exts/evergreen/snakes/_utils.py @@ -17,38 +17,38 @@ from bot.constants import Roles SNAKE_RESOURCES = Path("bot/resources/snakes").absolute() -h1 = r'''``` +h1 = r"""``` ---- ------ /--------\ |--------| |--------| \------/ - ----```''' -h2 = r'''``` + ----```""" +h2 = r"""``` ---- ------ /---\-/--\ |-----\--| |--------| \------/ - ----```''' -h3 = r'''``` + ----```""" +h3 = r"""``` ---- ------ /---\-/--\ |-----\--| |-----/--| \----\-/ - ----```''' -h4 = r'''``` + ----```""" +h4 = r"""``` ----- ----- \ /--| /---\ |--\ -\---| |--\--/-- / \------- / - ------```''' + ------```""" stages = [h1, h2, h3, h4] snakes = { "Baby Python": "https://i.imgur.com/SYOcmSa.png", diff --git a/bot/exts/evergreen/wolfram.py b/bot/exts/evergreen/wolfram.py index ca7d8454..d23afd6f 100644 --- a/bot/exts/evergreen/wolfram.py +++ b/bot/exts/evergreen/wolfram.py @@ -40,9 +40,11 @@ async def send_embed( """Generate & send a response embed with Wolfram as the author.""" embed = Embed(colour=colour) embed.description = message_txt - embed.set_author(name="Wolfram Alpha", - icon_url=WOLF_IMAGE, - url="https://www.wolframalpha.com/") + embed.set_author( + name="Wolfram Alpha", + icon_url=WOLF_IMAGE, + url="https://www.wolframalpha.com/" + ) if footer: embed.set_footer(text=footer) @@ -222,9 +224,11 @@ class Wolfram(Cog): return embed = Embed() - embed.set_author(name="Wolfram Alpha", - icon_url=WOLF_IMAGE, - url="https://www.wolframalpha.com/") + embed.set_author( + name="Wolfram Alpha", + icon_url=WOLF_IMAGE, + url="https://www.wolframalpha.com/" + ) embed.colour = Colours.soft_orange await ImagePaginator.paginate(pages, ctx, embed) diff --git a/bot/exts/halloween/candy_collection.py b/bot/exts/halloween/candy_collection.py index 14efa1fb..4afd5913 100644 --- a/bot/exts/halloween/candy_collection.py +++ b/bot/exts/halloween/candy_collection.py @@ -155,8 +155,12 @@ class CandyCollection(commands.Cog): ) -> None: """An alternative spooky message sent when user has no candies in the collection.""" embed = discord.Embed(color=author.color) - embed.set_author(name="Ghosts and Ghouls and Jack o' lanterns at night; " - "I tried to take your candies but you had none to begin with!") + embed.set_author( + name=( + "Ghosts and Ghouls and Jack o' lanterns at night; " + "I tried to take your candies but you had none to begin with!" + ) + ) await channel.send(embed=embed) @in_month(Month.OCTOBER) diff --git a/bot/exts/halloween/monstersurvey.py b/bot/exts/halloween/monstersurvey.py index 240a97db..96cda11e 100644 --- a/bot/exts/halloween/monstersurvey.py +++ b/bot/exts/halloween/monstersurvey.py @@ -71,7 +71,8 @@ class MonsterSurvey(Cog): default_embed.add_field( name=".monster show monster_name(optional)", value="Show a specific monster. If none is listed, it will give you an error with valid choices.", - inline=False) + inline=False + ) default_embed.add_field( name=".monster vote monster_name", value="Vote for a specific monster. You get one vote, but can change it at any time.", @@ -182,15 +183,17 @@ class MonsterSurvey(Cog): for rank, m in enumerate(top): votes = len(vr[m]["votes"]) percentage = ((votes / total_votes) * 100) if total_votes > 0 else 0 - embed.add_field(name=f"{rank+1}. {vr[m]['full_name']}", - value=( - f"{votes} votes. {percentage:.1f}% of total votes.\n" - f"Vote for this monster by typing " - f"'.monster vote {m}'\n" - f"Get more information on this monster by typing " - f"'.monster show {m}'" - ), - inline=False) + embed.add_field( + name=f"{rank+1}. {vr[m]['full_name']}", + value=( + f"{votes} votes. {percentage:.1f}% of total votes.\n" + f"Vote for this monster by typing " + f"'.monster vote {m}'\n" + f"Get more information on this monster by typing " + f"'.monster show {m}'" + ), + inline=False + ) embed.set_footer(text="You can also vote by their rank number. '.monster vote {number}' ") diff --git a/bot/exts/valentines/movie_generator.py b/bot/exts/valentines/movie_generator.py index 4508c3b2..0fc5edb4 100644 --- a/bot/exts/valentines/movie_generator.py +++ b/bot/exts/valentines/movie_generator.py @@ -54,8 +54,10 @@ class RomanceMovieFinder(commands.Cog): embed.set_thumbnail(url="https://i.imgur.com/LtFtC8H.png") await ctx.send(embed=embed) except KeyError: - warning_message = "A KeyError was raised while fetching information on the movie. The API service" \ - " could be unavailable or the API key could be set incorrectly." + warning_message = ( + "A KeyError was raised while fetching information on the movie. The API service" + " could be unavailable or the API key could be set incorrectly." + ) embed = discord.Embed(title=warning_message) log.warning(warning_message) await ctx.send(embed=embed) diff --git a/bot/utils/__init__.py b/bot/utils/__init__.py index 09a4dfc3..a1985019 100644 --- a/bot/utils/__init__.py +++ b/bot/utils/__init__.py @@ -3,7 +3,7 @@ import contextlib import re import string from datetime import datetime -from typing import Iterable, List +from typing import Iterable, List, Optional import discord from discord.ext.commands import BadArgument, Context @@ -31,8 +31,13 @@ def resolve_current_month() -> Month: async def disambiguate( - ctx: Context, entries: List[str], *, timeout: float = 30, - entries_per_page: int = 20, empty: bool = False, embed: discord.Embed = None + ctx: Context, + entries: List[str], + *, + timeout: float = 30, + entries_per_page: int = 20, + empty: bool = False, + embed: Optional[discord.Embed] = None ) -> str: """ Has the user choose between multiple entries in case one could not be chosen automatically. diff --git a/bot/utils/checks.py b/bot/utils/checks.py index 3783dd38..c06b6870 100644 --- a/bot/utils/checks.py +++ b/bot/utils/checks.py @@ -92,8 +92,10 @@ def in_whitelist_check( def with_role_check(ctx: Context, *role_ids: int) -> bool: """Returns True if the user has any one of the roles in role_ids.""" if not ctx.guild: # Return False in a DM - log.trace(f"{ctx.author} tried to use the '{ctx.command.name}'command from a DM. " - "This command is restricted by the with_role decorator. Rejecting request.") + log.trace( + f"{ctx.author} tried to use the '{ctx.command.name}'command from a DM. " + "This command is restricted by the with_role decorator. Rejecting request." + ) return False for role in ctx.author.roles: @@ -101,22 +103,28 @@ def with_role_check(ctx: Context, *role_ids: int) -> bool: log.trace(f"{ctx.author} has the '{role.name}' role, and passes the check.") return True - log.trace(f"{ctx.author} does not have the required role to use " - f"the '{ctx.command.name}' command, so the request is rejected.") + log.trace( + f"{ctx.author} does not have the required role to use " + f"the '{ctx.command.name}' command, so the request is rejected." + ) return False def without_role_check(ctx: Context, *role_ids: int) -> bool: """Returns True if the user does not have any of the roles in role_ids.""" if not ctx.guild: # Return False in a DM - log.trace(f"{ctx.author} tried to use the '{ctx.command.name}' command from a DM. " - "This command is restricted by the without_role decorator. Rejecting request.") + log.trace( + f"{ctx.author} tried to use the '{ctx.command.name}' command from a DM. " + "This command is restricted by the without_role decorator. Rejecting request." + ) return False author_roles = [role.id for role in ctx.author.roles] check = all(role not in author_roles for role in role_ids) - log.trace(f"{ctx.author} tried to call the '{ctx.command.name}' command. " - f"The result of the without_role check was {check}.") + log.trace( + f"{ctx.author} tried to call the '{ctx.command.name}' command. " + f"The result of the without_role check was {check}." + ) return check @@ -154,8 +162,10 @@ def cooldown_with_role_bypass(rate: int, per: float, type: BucketType = BucketTy # # If the `before_invoke` detail is ever a problem then I can quickly just swap over. if not isinstance(command, Command): - raise TypeError("Decorator `cooldown_with_role_bypass` must be applied after the command decorator. " - "This means it has to be above the command decorator in the code.") + raise TypeError( + "Decorator `cooldown_with_role_bypass` must be applied after the command decorator. " + "This means it has to be above the command decorator in the code." + ) command._before_invoke = predicate -- cgit v1.2.3