diff options
Diffstat (limited to 'bot/exts/evergreen')
25 files changed, 230 insertions, 230 deletions
| diff --git a/bot/exts/evergreen/cheatsheet.py b/bot/exts/evergreen/cheatsheet.py index 57c6d0b0..86fae167 100644 --- a/bot/exts/evergreen/cheatsheet.py +++ b/bot/exts/evergreen/cheatsheet.py @@ -24,11 +24,11 @@ Unknown cheat sheet. Please try to reformulate your query.  If the problem persists send a message in <#{Channels.dev_contrib}>  """ -URL = 'https://cheat.sh/python/{search}' +URL = "https://cheat.sh/python/{search}"  ESCAPE_TT = str.maketrans({"`": "\\`"})  ANSI_RE = re.compile(r"\x1b\[.*?m")  # We need to pass headers as curl otherwise it would default to aiohttp which would return raw html. -HEADERS = {'User-Agent': 'curl/7.68.0'} +HEADERS = {"User-Agent": "curl/7.68.0"}  class CheatSheet(commands.Cog): diff --git a/bot/exts/evergreen/connect_four.py b/bot/exts/evergreen/connect_four.py index df2a913a..929a15d8 100644 --- a/bot/exts/evergreen/connect_four.py +++ b/bot/exts/evergreen/connect_four.py @@ -55,8 +55,8 @@ class Game:      async def print_grid(self) -> None:          """Formats and outputs the Connect Four grid to the channel."""          title = ( -            f'Connect 4: {self.player1.display_name}' -            f' VS {self.bot.user.display_name if isinstance(self.player2, AI) else self.player2.display_name}' +            f"Connect 4: {self.player1.display_name}" +            f" VS {self.bot.user.display_name if isinstance(self.player2, AI) else self.player2.display_name}"          )          rows = [" ".join(self.tokens[s] for s in row) for row in self.grid] @@ -67,7 +67,7 @@ class Game:          if self.message:              await self.message.edit(embed=embed)          else: -            self.message = await self.channel.send(content='Loading...') +            self.message = await self.channel.send(content="Loading...")              for emoji in self.unicode_numbers:                  await self.message.add_reaction(emoji)              await self.message.add_reaction(CROSS_EMOJI) diff --git a/bot/exts/evergreen/conversationstarters.py b/bot/exts/evergreen/conversationstarters.py index 54fea0b3..4fe8c47c 100644 --- a/bot/exts/evergreen/conversationstarters.py +++ b/bot/exts/evergreen/conversationstarters.py @@ -9,7 +9,7 @@ from bot.constants import WHITELISTED_CHANNELS  from bot.utils.decorators import whitelist_override  from bot.utils.randomization import RandomCycle -SUGGESTION_FORM = 'https://forms.gle/zw6kkJqv8U43Nfjg9' +SUGGESTION_FORM = "https://forms.gle/zw6kkJqv8U43Nfjg9"  with Path("bot/resources/evergreen/starter.yaml").open("r", encoding="utf8") as f:      STARTERS = yaml.load(f, Loader=yaml.FullLoader) @@ -25,9 +25,9 @@ with Path("bot/resources/evergreen/py_topics.yaml").open("r", encoding="utf8") a      ALL_ALLOWED_CHANNELS = list(PY_TOPICS.keys()) + list(WHITELISTED_CHANNELS)  # Putting all topics into one dictionary and shuffling lists to reduce same-topic repetitions. -ALL_TOPICS = {'default': STARTERS, **PY_TOPICS} +ALL_TOPICS = {"default": STARTERS, **PY_TOPICS}  TOPICS = { -    channel: RandomCycle(topics or ['No topics found for this channel.']) +    channel: RandomCycle(topics or ["No topics found for this channel."])      for channel, topics in ALL_TOPICS.items()  } @@ -46,7 +46,7 @@ class ConvoStarters(commands.Cog):          Otherwise, a random conversation topic will be received by the user.          """          # No matter what, the form will be shown. -        embed = Embed(description=f'Suggest more topics [here]({SUGGESTION_FORM})!', color=Color.blurple()) +        embed = Embed(description=f"Suggest more topics [here]({SUGGESTION_FORM})!", color=Color.blurple())          try:              # Fetching topics. @@ -54,11 +54,11 @@ class ConvoStarters(commands.Cog):          # If the channel isn't Python-related.          except KeyError: -            embed.title = f'**{next(TOPICS["default"])}**' +            embed.title = f"**{next(TOPICS['default'])}**"          # If the channel ID doesn't have any topics.          else: -            embed.title = f'**{next(channel_topics)}**' +            embed.title = f"**{next(channel_topics)}**"          finally:              await ctx.send(embed=embed) diff --git a/bot/exts/evergreen/emoji.py b/bot/exts/evergreen/emoji.py index 8e540712..e7452a15 100644 --- a/bot/exts/evergreen/emoji.py +++ b/bot/exts/evergreen/emoji.py @@ -46,9 +46,9 @@ class Emojis(commands.Cog):                  else:                      emoji_info = f"There is **{len(category_emojis)}** emoji in the **{category_name}** category."                  if emoji_choice.animated: -                    msg.append(f'<a:{emoji_choice.name}:{emoji_choice.id}> {emoji_info}') +                    msg.append(f"<a:{emoji_choice.name}:{emoji_choice.id}> {emoji_info}")                  else: -                    msg.append(f'<:{emoji_choice.name}:{emoji_choice.id}> {emoji_info}') +                    msg.append(f"<:{emoji_choice.name}:{emoji_choice.id}> {emoji_info}")          return embed, msg      @staticmethod @@ -64,7 +64,7 @@ class Emojis(commands.Cog):          for emoji in emojis:              emoji_dict[emoji.name.split("_")[0]].append(emoji) -        error_comp = ', '.join(emoji_dict) +        error_comp = ", ".join(emoji_dict)          msg.append(f"These are the valid emoji categories:\n```{error_comp}```")          return embed, msg diff --git a/bot/exts/evergreen/error_handler.py b/bot/exts/evergreen/error_handler.py index dabd0ab5..5cd8d28d 100644 --- a/bot/exts/evergreen/error_handler.py +++ b/bot/exts/evergreen/error_handler.py @@ -40,7 +40,7 @@ class CommandErrorHandler(commands.Cog):      @commands.Cog.listener()      async def on_command_error(self, ctx: commands.Context, error: commands.CommandError) -> None:          """Activates when a command opens an error.""" -        if getattr(error, 'handled', False): +        if getattr(error, "handled", False):              logging.debug(f"Command {ctx.command} had its error already handled locally; ignoring.")              return @@ -49,7 +49,7 @@ class CommandErrorHandler(commands.Cog):              parent_command = f"{ctx.command} "              ctx = subctx -        error = getattr(error, 'original', error) +        error = getattr(error, "original", error)          logging.debug(              f"Error Encountered: {type(error).__name__} - {str(error)}, "              f"Command: {ctx.command}, " diff --git a/bot/exts/evergreen/game.py b/bot/exts/evergreen/game.py index 24872e76..7abbadcd 100644 --- a/bot/exts/evergreen/game.py +++ b/bot/exts/evergreen/game.py @@ -176,7 +176,7 @@ class Games(Cog):                              "Invalid OAuth credentials. Unloading Games cog. "                              f"OAuth response message: {result['message']}"                          ) -                        self.bot.remove_cog('Games') +                        self.bot.remove_cog("Games")                      return @@ -260,7 +260,7 @@ class Games(Cog):                  display_possibilities = "`, `".join(p[1] for p in possibilities)                  await ctx.send(                      f"Invalid genre `{genre}`. " -                    f"{f'Maybe you meant `{display_possibilities}`?' if display_possibilities else ''}" +                    f"Maybe you meant `{display_possibilities}`?" if display_possibilities else ''                  )                  return              elif len(possibilities) == 1: diff --git a/bot/exts/evergreen/githubinfo.py b/bot/exts/evergreen/githubinfo.py index fd100a7c..24479c79 100644 --- a/bot/exts/evergreen/githubinfo.py +++ b/bot/exts/evergreen/githubinfo.py @@ -27,14 +27,14 @@ class GithubInfo(commands.Cog):          async with self.bot.http_session.get(url) as r:              return await r.json() -    @commands.group(name='github', aliases=('gh', 'git')) +    @commands.group(name="github", aliases=("gh", "git"))      @commands.cooldown(1, 10, BucketType.user)      async def github_group(self, ctx: commands.Context) -> None:          """Commands for finding information related to GitHub."""          if ctx.invoked_subcommand is None:              await invoke_help_command(ctx) -    @github_group.command(name='user', aliases=('userinfo',)) +    @github_group.command(name="user", aliases=("userinfo",))      async def github_user_info(self, ctx: commands.Context, username: str) -> None:          """Fetches a user's GitHub information."""          async with ctx.typing(): @@ -51,31 +51,31 @@ class GithubInfo(commands.Cog):                  await ctx.send(embed=embed)                  return -            org_data = await self.fetch_data(user_data['organizations_url']) +            org_data = await self.fetch_data(user_data["organizations_url"])              orgs = [f"[{org['login']}](https://github.com/{org['login']})" for org in org_data] -            orgs_to_add = ' | '.join(orgs) +            orgs_to_add = " | ".join(orgs) -            gists = user_data['public_gists'] +            gists = user_data["public_gists"]              # Forming blog link -            if user_data['blog'].startswith("http"):  # Blog link is complete -                blog = user_data['blog'] -            elif user_data['blog']:  # Blog exists but the link is not complete +            if user_data["blog"].startswith("http"):  # Blog link is complete +                blog = user_data["blog"] +            elif user_data["blog"]:  # Blog exists but the link is not complete                  blog = f"https://{user_data['blog']}"              else:                  blog = "No website link available"              embed = discord.Embed(                  title=f"`{user_data['login']}`'s GitHub profile info", -                description=f"```{user_data['bio']}```\n" if user_data['bio'] is not None else "", +                description=f"```{user_data['bio']}```\n" if user_data["bio"] is not None else "",                  colour=discord.Colour.blurple(), -                url=user_data['html_url'], -                timestamp=datetime.strptime(user_data['created_at'], "%Y-%m-%dT%H:%M:%SZ") +                url=user_data["html_url"], +                timestamp=datetime.strptime(user_data["created_at"], "%Y-%m-%dT%H:%M:%SZ")              ) -            embed.set_thumbnail(url=user_data['avatar_url']) +            embed.set_thumbnail(url=user_data["avatar_url"])              embed.set_footer(text="Account created at") -            if user_data['type'] == "User": +            if user_data["type"] == "User":                  embed.add_field(                      name="Followers", @@ -91,7 +91,7 @@ class GithubInfo(commands.Cog):                  value=f"[{user_data['public_repos']}]({user_data['html_url']}?tab=repositories)"              ) -            if user_data['type'] == "User": +            if user_data["type"] == "User":                  embed.add_field(name="Gists", value=f"[{gists}](https://gist.github.com/{quote(username, safe='')})")                  embed.add_field( @@ -109,8 +109,8 @@ class GithubInfo(commands.Cog):          The repository should look like `user/reponame` or `user reponame`.          """ -        repo = '/'.join(repo) -        if repo.count('/') != 1: +        repo = "/".join(repo) +        if repo.count("/") != 1:              embed = discord.Embed(                  title=random.choice(NEGATIVE_REPLIES),                  description="The repository should look like `user/reponame` or `user reponame`.", @@ -135,10 +135,10 @@ class GithubInfo(commands.Cog):                  return          embed = discord.Embed( -            title=repo_data['name'], +            title=repo_data["name"],              description=repo_data["description"],              colour=discord.Colour.blurple(), -            url=repo_data['html_url'] +            url=repo_data["html_url"]          )          # If it's a fork, then it will have a parent key @@ -148,7 +148,7 @@ class GithubInfo(commands.Cog):          except KeyError:              log.debug("Repository is not a fork.") -        repo_owner = repo_data['owner'] +        repo_owner = repo_data["owner"]          embed.set_author(              name=repo_owner["login"], @@ -156,8 +156,8 @@ class GithubInfo(commands.Cog):              icon_url=repo_owner["avatar_url"]          ) -        repo_created_at = datetime.strptime(repo_data['created_at'], "%Y-%m-%dT%H:%M:%SZ").strftime("%d/%m/%Y") -        last_pushed = datetime.strptime(repo_data['pushed_at'], "%Y-%m-%dT%H:%M:%SZ").strftime("%d/%m/%Y at %H:%M") +        repo_created_at = datetime.strptime(repo_data["created_at"], "%Y-%m-%dT%H:%M:%SZ").strftime("%d/%m/%Y") +        last_pushed = datetime.strptime(repo_data["pushed_at"], "%Y-%m-%dT%H:%M:%SZ").strftime("%d/%m/%Y at %H:%M")          embed.set_footer(              text=( diff --git a/bot/exts/evergreen/help.py b/bot/exts/evergreen/help.py index f557e42e..bfaf25f1 100644 --- a/bot/exts/evergreen/help.py +++ b/bot/exts/evergreen/help.py @@ -22,14 +22,14 @@ from bot.utils.pagination import (  DELETE_EMOJI = Emojis.trashcan  REACTIONS = { -    FIRST_EMOJI: 'first', -    LEFT_EMOJI: 'back', -    RIGHT_EMOJI: 'next', -    LAST_EMOJI: 'end', -    DELETE_EMOJI: 'stop', +    FIRST_EMOJI: "first", +    LEFT_EMOJI: "back", +    RIGHT_EMOJI: "next", +    LAST_EMOJI: "end", +    DELETE_EMOJI: "stop",  } -Cog = namedtuple('Cog', ['name', 'description', 'commands']) +Cog = namedtuple("Cog", ["name", "description", "commands"])  log = logging.getLogger(__name__) @@ -87,7 +87,7 @@ class HelpSession:          # set the query details for the session          if command: -            query_str = ' '.join(command) +            query_str = " ".join(command)              self.query = self._get_query(query_str)              self.description = self.query.description or self.query.help          else: @@ -191,7 +191,7 @@ class HelpSession:          self.reset_timeout()          # Run relevant action method -        action = getattr(self, f'do_{REACTIONS[emoji]}', None) +        action = getattr(self, f"do_{REACTIONS[emoji]}", None)          if action:              await action() @@ -234,11 +234,11 @@ class HelpSession:          if cmd.cog:              try:                  if cmd.cog.category: -                    return f'**{cmd.cog.category}**' +                    return f"**{cmd.cog.category}**"              except AttributeError:                  pass -            return f'**{cmd.cog_name}**' +            return f"**{cmd.cog_name}**"          else:              return "**\u200bNo Category:**" @@ -262,47 +262,47 @@ class HelpSession:                  # if default is not an empty string or None                  if show_default: -                    results.append(f'[{name}={param.default}]') +                    results.append(f"[{name}={param.default}]")                  else: -                    results.append(f'[{name}]') +                    results.append(f"[{name}]")              # if variable length argument              elif param.kind == param.VAR_POSITIONAL: -                results.append(f'[{name}...]') +                results.append(f"[{name}...]")              # if required              else: -                results.append(f'<{name}>') +                results.append(f"<{name}>")          return f"{cmd.name} {' '.join(results)}"      async def build_pages(self) -> None:          """Builds the list of content pages to be paginated through in the help message, as a list of str."""          # Use LinePaginator to restrict embed line height -        paginator = LinePaginator(prefix='', suffix='', max_lines=self._max_lines) +        paginator = LinePaginator(prefix="", suffix="", max_lines=self._max_lines)          prefix = constants.Client.prefix          # show signature if query is a command          if isinstance(self.query, commands.Command):              signature = self._get_command_params(self.query) -            parent = self.query.full_parent_name + ' ' if self.query.parent else '' -            paginator.add_line(f'**```{prefix}{parent}{signature}```**') +            parent = self.query.full_parent_name + " " if self.query.parent else "" +            paginator.add_line(f"**```{prefix}{parent}{signature}```**")              aliases = [f"`{alias}`" if not parent else f"`{parent} {alias}`" for alias in self.query.aliases]              aliases += [f"`{alias}`" for alias in getattr(self.query, "root_aliases", ())]              aliases = ", ".join(sorted(aliases))              if aliases: -                paginator.add_line(f'**Can also use:** {aliases}\n') +                paginator.add_line(f"**Can also use:** {aliases}\n")              if not await self.query.can_run(self._ctx): -                paginator.add_line('***You cannot run this command.***\n') +                paginator.add_line("***You cannot run this command.***\n")          if isinstance(self.query, Cog): -            paginator.add_line(f'**{self.query.name}**') +            paginator.add_line(f"**{self.query.name}**")          if self.description: -            paginator.add_line(f'*{self.description}*') +            paginator.add_line(f"*{self.description}*")          # list all children commands of the queried object          if isinstance(self.query, (commands.GroupMixin, Cog)): @@ -319,13 +319,13 @@ class HelpSession:                  return              if isinstance(self.query, Cog): -                grouped = (('**Commands:**', self.query.commands),) +                grouped = (("**Commands:**", self.query.commands),)              elif isinstance(self.query, commands.Command): -                grouped = (('**Subcommands:**', self.query.commands),) +                grouped = (("**Subcommands:**", self.query.commands),)                  # don't show prefix for subcommands -                prefix = '' +                prefix = ""              # otherwise sort and organise all commands into categories              else: @@ -347,7 +347,7 @@ class HelpSession:                          continue                      # see if the user can run the command -                    strikeout = '' +                    strikeout = ""                      # Patch to make the !help command work outside of #bot-commands again                      # This probably needs a proper rewrite, but this will make it work in @@ -361,16 +361,16 @@ class HelpSession:                          # skip if we don't show commands they can't run                          if self._only_can_run:                              continue -                        strikeout = '~~' +                        strikeout = "~~"                      signature = self._get_command_params(command)                      info = f"{strikeout}**`{prefix}{signature}`**{strikeout}"                      # handle if the command has no docstring                      if command.short_doc: -                        cat_cmds.append(f'{info}\n*{command.short_doc}*') +                        cat_cmds.append(f"{info}\n*{command.short_doc}*")                      else: -                        cat_cmds.append(f'{info}\n*No details provided.*') +                        cat_cmds.append(f"{info}\n*No details provided.*")                  # state var for if the category should be added next                  print_cat = 1 @@ -379,7 +379,7 @@ class HelpSession:                  for details in cat_cmds:                      # keep details together, paginating early if it won't fit -                    lines_adding = len(details.split('\n')) + print_cat +                    lines_adding = len(details.split("\n")) + print_cat                      if paginator._linecount + lines_adding > self._max_lines:                          paginator._linecount = 0                          new_page = True @@ -390,7 +390,7 @@ class HelpSession:                      if print_cat:                          if new_page: -                            paginator.add_line('') +                            paginator.add_line("")                          paginator.add_line(category)                          print_cat = 0 @@ -412,7 +412,7 @@ class HelpSession:          page_count = len(self._pages)          if page_count > 1: -            embed.set_footer(text=f'Page {self._current_page+1} / {page_count}') +            embed.set_footer(text=f"Page {self._current_page+1} / {page_count}")          return embed @@ -496,7 +496,7 @@ class HelpSession:  class Help(DiscordCog):      """Custom Embed Pagination Help feature.""" -    @commands.command('help') +    @commands.command("help")      async def new_help(self, ctx: Context, *commands) -> None:          """Shows Command Help."""          try: @@ -507,8 +507,8 @@ class Help(DiscordCog):              embed.title = str(error)              if error.possible_matches: -                matches = '\n'.join(error.possible_matches.keys()) -                embed.description = f'**Did you mean:**\n`{matches}`' +                matches = "\n".join(error.possible_matches.keys()) +                embed.description = f"**Did you mean:**\n`{matches}`"              await ctx.send(embed=embed) @@ -519,7 +519,7 @@ def unload(bot: Bot) -> None:      This is run if the cog raises an exception on load, or if the extension is unloaded.      """ -    bot.remove_command('help') +    bot.remove_command("help")      bot.add_command(bot._old_help) @@ -534,8 +534,8 @@ def setup(bot: Bot) -> None:      If an exception is raised during the loading of the cog, `unload` will be called in order to      reinstate the original help command.      """ -    bot._old_help = bot.get_command('help') -    bot.remove_command('help') +    bot._old_help = bot.get_command("help") +    bot.remove_command("help")      try:          bot.add_cog(Help()) diff --git a/bot/exts/evergreen/issues.py b/bot/exts/evergreen/issues.py index d7ee99c0..5bbc57c6 100644 --- a/bot/exts/evergreen/issues.py +++ b/bot/exts/evergreen/issues.py @@ -158,7 +158,7 @@ class Issues(commands.Cog):          issue_url = json_data.get("html_url") -        return IssueState(repository, number, issue_url, json_data.get('title', ''), emoji) +        return IssueState(repository, number, issue_url, json_data.get("title", ""), emoji)      @staticmethod      def format_embed( @@ -177,7 +177,7 @@ class Issues(commands.Cog):          resp = discord.Embed(              colour=Colours.bright_green, -            description='\n'.join(description_list) +            description="\n".join(description_list)          )          embed_url = f"https://github.com/{user}/{repository}" if repository else f"https://github.com/{user}" diff --git a/bot/exts/evergreen/minesweeper.py b/bot/exts/evergreen/minesweeper.py index d0cc28c5..f2c5e656 100644 --- a/bot/exts/evergreen/minesweeper.py +++ b/bot/exts/evergreen/minesweeper.py @@ -38,7 +38,7 @@ class CoordinateConverter(commands.Converter):      async def convert(self, ctx: commands.Context, coordinate: str) -> typing.Tuple[int, int]:          """Take in a coordinate string and turn it into an (x, y) tuple."""          if not 2 <= len(coordinate) <= 3: -            raise commands.BadArgument('Invalid co-ordinate provided.') +            raise commands.BadArgument("Invalid co-ordinate provided.")          coordinate = coordinate.lower()          if coordinate[0].isalpha(): @@ -51,7 +51,7 @@ class CoordinateConverter(commands.Converter):          if not digit.isdigit():              raise commands.BadArgument -        x = ord(letter) - ord('a') +        x = ord(letter) - ord("a")          y = int(digit) - 1          if (not 0 <= x <= 9) or (not 0 <= y <= 9): @@ -82,7 +82,7 @@ class Minesweeper(commands.Cog):      def __init__(self, _bot: Bot) -> None:          self.games: GamesDict = {}  # Store the currently running games -    @commands.group(name='minesweeper', aliases=('ms',), invoke_without_command=True) +    @commands.group(name="minesweeper", aliases=("ms",), invoke_without_command=True)      async def minesweeper_group(self, ctx: commands.Context) -> None:          """Commands for Playing Minesweeper."""          await invoke_help_command(ctx) diff --git a/bot/exts/evergreen/movie.py b/bot/exts/evergreen/movie.py index 488e5142..e67f8d04 100644 --- a/bot/exts/evergreen/movie.py +++ b/bot/exts/evergreen/movie.py @@ -53,7 +53,7 @@ class Movie(Cog):      def __init__(self, bot: Bot):          self.http_session: ClientSession = bot.http_session -    @group(name='movies', aliases=['movie'], invoke_without_command=True) +    @group(name="movies", aliases=["movie"], invoke_without_command=True)      async def movies(self, ctx: Context, genre: str = "", amount: int = 5) -> None:          """          Get random movies by specifying genre. Also support amount parameter, that define how much movies will be shown. @@ -89,7 +89,7 @@ class Movie(Cog):          # Get movies list from TMDB, check if results key in result. When not, raise error.          movies = await self.get_movies_list(self.http_session, MovieGenres[genre].value, page) -        if 'results' not in movies.keys(): +        if "results" not in movies.keys():              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) @@ -101,7 +101,7 @@ class Movie(Cog):          await ImagePaginator.paginate(pages, ctx, embed) -    @movies.command(name='genres', aliases=['genre', 'g']) +    @movies.command(name="genres", aliases=["genre", "g"])      async def genres(self, ctx: Context) -> None:          """Show all currently available genres for .movies command."""          await ctx.send(f"Current available genres: {', '.join('`' + genre.name + '`' for genre in MovieGenres)}") @@ -130,7 +130,7 @@ class Movie(Cog):          pages = []          for i in range(amount): -            movie_id = movies['results'][i]['id'] +            movie_id = movies["results"][i]["id"]              movie = await self.get_movie(client, movie_id)              page, img = await self.create_page(movie) @@ -151,7 +151,7 @@ class Movie(Cog):          # Add title + tagline (if not empty)          text += f"**{movie['title']}**\n" -        if movie['tagline']: +        if movie["tagline"]:              text += f"{movie['tagline']}\n\n"          else:              text += "\n" @@ -162,8 +162,8 @@ class Movie(Cog):          text += "__**Production Information**__\n" -        companies = movie['production_companies'] -        countries = movie['production_countries'] +        companies = movie["production_companies"] +        countries = movie["production_countries"]          text += f"**Made by:** {', '.join(company['name'] for company in companies)}\n"          text += f"**Made in:** {', '.join(country['name'] for country in countries)}\n\n" @@ -173,8 +173,8 @@ class Movie(Cog):          budget = f"{movie['budget']:,d}" if movie['budget'] else "?"          revenue = f"{movie['revenue']:,d}" if movie['revenue'] else "?" -        if movie['runtime'] is not None: -            duration = divmod(movie['runtime'], 60) +        if movie["runtime"] is not None: +            duration = divmod(movie["runtime"], 60)          else:              duration = ("?", "?") @@ -182,7 +182,7 @@ class Movie(Cog):          text += f"**Revenue:** ${revenue}\n"          text += f"**Duration:** {f'{duration[0]} hour(s) {duration[1]} minute(s)'}\n\n" -        text += movie['overview'] +        text += movie["overview"]          img = f"http://image.tmdb.org/t/p/w200{movie['poster_path']}" diff --git a/bot/exts/evergreen/pythonfacts.py b/bot/exts/evergreen/pythonfacts.py index 73234d55..2dc4996f 100644 --- a/bot/exts/evergreen/pythonfacts.py +++ b/bot/exts/evergreen/pythonfacts.py @@ -6,7 +6,7 @@ from discord.ext import commands  from bot.bot import Bot  from bot.constants import Colours -with open('bot/resources/evergreen/python_facts.txt') as file: +with open("bot/resources/evergreen/python_facts.txt") as file:      FACTS = itertools.cycle(list(file))  COLORS = itertools.cycle([Colours.python_blue, Colours.python_yellow]) @@ -15,13 +15,13 @@ COLORS = itertools.cycle([Colours.python_blue, Colours.python_yellow])  class PythonFacts(commands.Cog):      """Sends a random fun fact about Python.""" -    @commands.command(name='pythonfact', aliases=['pyfact']) +    @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', +        embed = discord.Embed(title="Python Facts",                                      description=next(FACTS),                                      colour=next(COLORS)) -        embed.add_field(name='Suggestions', +        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/recommend_game.py b/bot/exts/evergreen/recommend_game.py index be329f44..340a42d3 100644 --- a/bot/exts/evergreen/recommend_game.py +++ b/bot/exts/evergreen/recommend_game.py @@ -13,7 +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: +    with rec_path.open(encoding="utf8") as file:          data = json.load(file)      game_recs.append(data)  shuffle(game_recs) @@ -26,7 +26,7 @@ class RecommendGame(commands.Cog):          self.bot = bot          self.index = 0 -    @commands.command(name="recommendgame", aliases=['gamerec']) +    @commands.command(name="recommendgame", aliases=["gamerec"])      async def recommend_game(self, ctx: commands.Context) -> None:          """Sends an Embed of a random game recommendation."""          if self.index >= len(game_recs): @@ -35,14 +35,14 @@ class RecommendGame(commands.Cog):          game = game_recs[self.index]          self.index += 1 -        author = self.bot.get_user(int(game['author'])) +        author = self.bot.get_user(int(game["author"]))          # Creating and formatting Embed          embed = discord.Embed(color=discord.Colour.blue())          if author is not None:              embed.set_author(name=author.name, icon_url=author.avatar_url) -        embed.set_image(url=game['image']) -        embed.add_field(name='Recommendation: ' + game['title'] + '\n' + game['link'], value=game['description']) +        embed.set_image(url=game["image"]) +        embed.add_field(name="Recommendation: " + game["title"] + "\n" + game["link"], value=game["description"])          await ctx.send(embed=embed) diff --git a/bot/exts/evergreen/reddit.py b/bot/exts/evergreen/reddit.py index 51a360b3..82af6ce9 100644 --- a/bot/exts/evergreen/reddit.py +++ b/bot/exts/evergreen/reddit.py @@ -21,18 +21,18 @@ class Reddit(commands.Cog):          """Send a get request to the reddit API and get json response."""          session = self.bot.http_session          params = { -            'limit': 50 +            "limit": 50          }          headers = { -            'User-Agent': 'Iceman' +            "User-Agent": "Iceman"          }          async with session.get(url=url, params=params, headers=headers) as response:              return await response.json() -    @commands.command(name='reddit') +    @commands.command(name="reddit")      @commands.cooldown(1, 10, BucketType.user) -    async def get_reddit(self, ctx: commands.Context, subreddit: str = 'python', sort: str = "hot") -> None: +    async def get_reddit(self, ctx: commands.Context, subreddit: str = "python", sort: str = "hot") -> None:          """          Fetch reddit posts by using this command. @@ -46,15 +46,15 @@ class Reddit(commands.Cog):              await ctx.send(f"Invalid sorting: {sort}\nUsing default sorting: `Hot`")              sort = "hot" -        data = await self.fetch(f'https://www.reddit.com/r/{subreddit}/{sort}/.json') +        data = await self.fetch(f"https://www.reddit.com/r/{subreddit}/{sort}/.json")          try:              posts = data["data"]["children"]          except KeyError: -            await ctx.send('Subreddit not found!') +            await ctx.send("Subreddit not found!")              return          if not posts: -            await ctx.send('No posts available!') +            await ctx.send("No posts available!")              return          if posts[0]["data"]["over_18"] is True: @@ -106,12 +106,12 @@ class Reddit(commands.Cog):                  post_stats = f"{image_emoji} "                  image_url = post_url -            votes = f'{upvote_emoji}{post["data"]["ups"]}' -            comments = f'{comment_emoji}\u2002{ post["data"]["num_comments"]}' +            votes = f"{upvote_emoji}{post['data']['ups']}" +            comments = f"{comment_emoji}\u2002{ post['data']['num_comments']}"              post_stats += (                  f"\u2002{votes}\u2003"                  f"{comments}" -                f'\u2003{user_emoji}\u2002{post["data"]["author"]}\n' +                f"\u2003{user_emoji}\u2002{post['data']['author']}\n"              )              embed_titles += f"{post_stats}\n"              page_text = f"**[{post_title}]({post_url})**\n{post_stats}\n{post['data']['selftext'][0:200]}" diff --git a/bot/exts/evergreen/snakes/_converter.py b/bot/exts/evergreen/snakes/_converter.py index eee248cf..0ca10d6c 100644 --- a/bot/exts/evergreen/snakes/_converter.py +++ b/bot/exts/evergreen/snakes/_converter.py @@ -24,8 +24,8 @@ class Snake(Converter):          await self.build_list()          name = name.lower() -        if name == 'python': -            return 'Python (programming language)' +        if name == "python": +            return "Python (programming language)"          def get_potential(iterable: Iterable, *, threshold: int = 80) -> List[str]:              nonlocal name @@ -47,12 +47,12 @@ class Snake(Converter):          if name.lower() in self.special_cases:              return self.special_cases.get(name.lower(), name.lower()) -        names = {snake['name']: snake['scientific'] for snake in self.snakes} +        names = {snake["name"]: snake["scientific"] for snake in self.snakes}          all_names = names.keys() | names.values()          timeout = len(all_names) * (3 / 4)          embed = discord.Embed( -            title='Found multiple choices. Please choose the correct one.', colour=0x59982F) +            title="Found multiple choices. Please choose the correct one.", colour=0x59982F)          embed.set_author(name=ctx.author.display_name, icon_url=ctx.author.avatar_url)          name = await disambiguate(ctx, get_potential(all_names), timeout=timeout, embed=embed) @@ -70,7 +70,7 @@ class Snake(Converter):          if cls.special_cases is None:              with (SNAKE_RESOURCES / "special_snakes.json").open(encoding="utf8") as snakefile:                  special_cases = json.load(snakefile) -            cls.special_cases = {snake['name'].lower(): snake for snake in special_cases} +            cls.special_cases = {snake["name"].lower(): snake for snake in special_cases}      @classmethod      async def random(cls) -> str: @@ -81,5 +81,5 @@ class Snake(Converter):          so I can get it from here.          """          await cls.build_list() -        names = [snake['scientific'] for snake in cls.snakes] +        names = [snake["scientific"] for snake in cls.snakes]          return random.choice(names) diff --git a/bot/exts/evergreen/snakes/_snakes_cog.py b/bot/exts/evergreen/snakes/_snakes_cog.py index c8633ce7..d95970da 100644 --- a/bot/exts/evergreen/snakes/_snakes_cog.py +++ b/bot/exts/evergreen/snakes/_snakes_cog.py @@ -143,8 +143,8 @@ class Snakes(Cog):      https://github.com/python-discord/code-jam-1      """ -    wiki_brief = re.compile(r'(.*?)(=+ (.*?) =+)', flags=re.DOTALL) -    valid_image_extensions = ('gif', 'png', 'jpeg', 'jpg', 'webp') +    wiki_brief = re.compile(r"(.*?)(=+ (.*?) =+)", flags=re.DOTALL) +    valid_image_extensions = ("gif", "png", "jpeg", "jpg", "webp")      def __init__(self, bot: Bot):          self.active_sal = {} @@ -183,28 +183,28 @@ class Snakes(Cog):          # Get the size of the snake icon, configure the height of the image box (yes, it changes)          icon_width = 347  # Hardcoded, not much i can do about that          icon_height = int((icon_width / snake.width) * snake.height) -        frame_copies = icon_height // CARD['frame'].height + 1 +        frame_copies = icon_height // CARD["frame"].height + 1          snake.thumbnail((icon_width, icon_height))          # Get the dimensions of the final image -        main_height = icon_height + CARD['top'].height + CARD['bottom'].height -        main_width = CARD['frame'].width +        main_height = icon_height + CARD["top"].height + CARD["bottom"].height +        main_width = CARD["frame"].width          # Start creating the foreground          foreground = Image.new("RGBA", (main_width, main_height), (0, 0, 0, 0)) -        foreground.paste(CARD['top'], (0, 0)) +        foreground.paste(CARD["top"], (0, 0))          # Generate the frame borders to the correct height          for offset in range(frame_copies): -            position = (0, CARD['top'].height + offset * CARD['frame'].height) -            foreground.paste(CARD['frame'], position) +            position = (0, CARD["top"].height + offset * CARD["frame"].height) +            foreground.paste(CARD["frame"], position)          # Add the image and bottom part of the image -        foreground.paste(snake, (36, CARD['top'].height))  # Also hardcoded :( -        foreground.paste(CARD['bottom'], (0, CARD['top'].height + icon_height)) +        foreground.paste(snake, (36, CARD["top"].height))  # Also hardcoded :( +        foreground.paste(CARD["bottom"], (0, CARD["top"].height + icon_height))          # Setup the background -        back = random.choice(CARD['backs']) +        back = random.choice(CARD["backs"])          back_copies = main_height // back.height + 1          full_image = Image.new("RGBA", (main_width, main_height), (0, 0, 0, 0)) @@ -216,11 +216,11 @@ class Snakes(Cog):          full_image.paste(foreground, (0, 0), foreground)          # Get the first two sentences of the info -        description = '.'.join(content['info'].split(".")[:2]) + '.' +        description = ".".join(content["info"].split(".")[:2]) + "."          # Setup positioning variables          margin = 36 -        offset = CARD['top'].height + icon_height + margin +        offset = CARD["top"].height + icon_height + margin          # Create blank rectangle image which will be behind the text          rectangle = Image.new( @@ -242,12 +242,12 @@ class Snakes(Cog):          # Draw the text onto the final image          draw = ImageDraw.Draw(full_image)          for line in textwrap.wrap(description, 36): -            draw.text([margin + 4, offset], line, font=CARD['font']) -            offset += CARD['font'].getsize(line)[1] +            draw.text([margin + 4, offset], line, font=CARD["font"]) +            offset += CARD["font"].getsize(line)[1]          # Get the image contents as a BufferIO object          buffer = BytesIO() -        full_image.save(buffer, 'PNG') +        full_image.save(buffer, "PNG")          buffer.seek(0)          return buffer @@ -311,12 +311,12 @@ class Snakes(Cog):          async with aiohttp.ClientSession() as session:              params = { -                'format': 'json', -                'action': 'query', -                'list': 'search', -                'srsearch': name, -                'utf8': '', -                'srlimit': '1', +                "format": "json", +                "action": "query", +                "list": "search", +                "srsearch": name, +                "utf8": "", +                "srlimit": "1",              }              json = await self._fetch(session, URL, params=params) @@ -331,13 +331,13 @@ class Snakes(Cog):                  return None              params = { -                'format': 'json', -                'action': 'query', -                'prop': 'extracts|images|info', -                'exlimit': 'max', -                'explaintext': '', -                'inprop': 'url', -                'pageids': pageid +                "format": "json", +                "action": "query", +                "prop": "extracts|images|info", +                "exlimit": "max", +                "explaintext": "", +                "inprop": "url", +                "pageids": pageid              }              json = await self._fetch(session, URL, params=params) @@ -353,32 +353,32 @@ class Snakes(Cog):                  snake_info["error"] = True              if snake_info["images"]: -                i_url = 'https://commons.wikimedia.org/wiki/Special:FilePath/' +                i_url = "https://commons.wikimedia.org/wiki/Special:FilePath/"                  image_list = []                  map_list = []                  thumb_list = []                  # Wikipedia has arbitrary images that are not snakes                  banned = [ -                    'Commons-logo.svg', -                    'Red%20Pencil%20Icon.png', -                    'distribution', -                    'The%20Death%20of%20Cleopatra%20arthur.jpg', -                    'Head%20of%20holotype', -                    'locator', -                    'Woma.png', -                    '-map.', -                    '.svg', -                    'ange.', -                    'Adder%20(PSF).png' +                    "Commons-logo.svg", +                    "Red%20Pencil%20Icon.png", +                    "distribution", +                    "The%20Death%20of%20Cleopatra%20arthur.jpg", +                    "Head%20of%20holotype", +                    "locator", +                    "Woma.png", +                    "-map.", +                    ".svg", +                    "ange.", +                    "Adder%20(PSF).png"                  ]                  for image in snake_info["images"]:                      # Images come in the format of `File:filename.extension` -                    file, sep, filename = image["title"].partition(':') +                    file, sep, filename = image["title"].partition(":")                      filename = filename.replace(" ", "%20")  # Wikipedia returns good data! -                    if not filename.startswith('Map'): +                    if not filename.startswith("Map"):                          if any(ban in filename for ban in banned):                              pass                          else: @@ -392,7 +392,7 @@ class Snakes(Cog):              snake_info["thumb_list"] = thumb_list              snake_info["name"] = name -            match = self.wiki_brief.match(snake_info['extract']) +            match = self.wiki_brief.match(snake_info["extract"])              info = match.group(1) if match else None              if info: @@ -438,13 +438,13 @@ class Snakes(Cog):      # endregion      # region: Commands -    @group(name='snakes', aliases=('snake',), invoke_without_command=True) +    @group(name="snakes", aliases=("snake",), invoke_without_command=True)      async def snakes_group(self, ctx: Context) -> None:          """Commands from our first code jam."""          await invoke_help_command(ctx)      @bot_has_permissions(manage_messages=True) -    @snakes_group.command(name='antidote') +    @snakes_group.command(name="antidote")      @locked()      async def antidote_command(self, ctx: Context) -> None:          """ @@ -586,7 +586,7 @@ class Snakes(Cog):          log.debug("Ending pagination and removing all reactions...")          await board_id.clear_reactions() -    @snakes_group.command(name='draw') +    @snakes_group.command(name="draw")      async def draw_command(self, ctx: Context) -> None:          """          Draws a random snek using Perlin noise. @@ -621,10 +621,10 @@ class Snakes(Cog):                  bg_color=bg_color              )              png_bytes = utils.frame_to_png_bytes(image_frame) -            file = File(png_bytes, filename='snek.png') +            file = File(png_bytes, filename="snek.png")              await ctx.send(file=file) -    @snakes_group.command(name='get') +    @snakes_group.command(name="get")      @bot_has_permissions(manage_messages=True)      @locked()      async def get_command(self, ctx: Context, *, name: Snake = None) -> None: @@ -642,8 +642,8 @@ class Snakes(Cog):              else:                  data = await self._get_snek(name) -            if data.get('error'): -                await ctx.send('Could not fetch data from Wikipedia.') +            if data.get("error"): +                await ctx.send("Could not fetch data from Wikipedia.")                  return              description = data["info"] @@ -662,19 +662,19 @@ class Snakes(Cog):              # Build and send the embed.              embed = Embed( -                title=data.get("title", data.get('name')), +                title=data.get("title", data.get("name")),                  description=description,                  colour=0x59982F,              ) -            emoji = 'https://emojipedia-us.s3.amazonaws.com/thumbs/60/google/3/snake_1f40d.png' -            image = next((url for url in data['image_list'] +            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)              embed.set_image(url=image)              await ctx.send(embed=embed) -    @snakes_group.command(name='guess', aliases=('identify',)) +    @snakes_group.command(name="guess", aliases=("identify",))      @locked()      async def guess_command(self, ctx: Context) -> None:          """ @@ -694,11 +694,11 @@ class Snakes(Cog):                  data = await self._get_snek(snake) -                image = next((url for url in data['image_list'] +                image = next((url for url in data["image_list"]                                if url.endswith(self.valid_image_extensions)), None)              embed = Embed( -                title='Which of the following is the snake in the image?', +                title="Which of the following is the snake in the image?",                  description="\n".join(                      f"{'ABCD'[snakes.index(snake)]}: {snake}" for snake in snakes),                  colour=SNAKE_COLOR @@ -709,7 +709,7 @@ class Snakes(Cog):          options = {f"{'abcd'[snakes.index(snake)]}": snake for snake in snakes}          await self._validate_answer(ctx, guess, answer, options) -    @snakes_group.command(name='hatch') +    @snakes_group.command(name="hatch")      async def hatch_command(self, ctx: Context) -> None:          """          Hatches your personal snake. @@ -740,7 +740,7 @@ class Snakes(Cog):          await ctx.send(embed=my_snake_embed) -    @snakes_group.command(name='movie') +    @snakes_group.command(name="movie")      async def movie_command(self, ctx: Context) -> None:          """          Gets a random snake-related movie from TMDB. @@ -806,7 +806,7 @@ class Snakes(Cog):              await ctx.send("An error occurred while fetching a snake-related movie!")              raise err from None -    @snakes_group.command(name='quiz') +    @snakes_group.command(name="quiz")      @locked()      async def quiz_command(self, ctx: Context) -> None:          """ @@ -832,7 +832,7 @@ class Snakes(Cog):          quiz = await ctx.send("", embed=embed)          await self._validate_answer(ctx, quiz, answer, options) -    @snakes_group.command(name='name', aliases=('name_gen',)) +    @snakes_group.command(name="name", aliases=("name_gen",))      async def name_command(self, ctx: Context, *, name: str = None) -> None:          """          Snakifies a username. @@ -856,7 +856,7 @@ class Snakes(Cog):          This was written by Iceman, and modified for inclusion into the bot by lemon.          """          snake_name = await self._get_snake_name() -        snake_name = snake_name['name'] +        snake_name = snake_name["name"]          snake_prefix = ""          # Set aside every word in the snake name except the last. @@ -904,7 +904,7 @@ class Snakes(Cog):          await ctx.send(embed=embed)          return -    @snakes_group.command(name='sal') +    @snakes_group.command(name="sal")      @locked()      async def sal_command(self, ctx: Context) -> None:          """ @@ -923,7 +923,7 @@ class Snakes(Cog):          await game.open_game() -    @snakes_group.command(name='about') +    @snakes_group.command(name="about")      async def about_command(self, ctx: Context) -> None:          """Show an embed with information about the event, its participants, and its winners."""          contributors = [ @@ -968,7 +968,7 @@ class Snakes(Cog):          await ctx.send(embed=embed) -    @snakes_group.command(name='card') +    @snakes_group.command(name="card")      async def card_command(self, ctx: Context, *, name: Snake = None) -> None:          """          Create an interesting little card from a snake. @@ -978,7 +978,7 @@ class Snakes(Cog):          # Get the snake data we need          if not name:              name_obj = await self._get_snake_name() -            name = name_obj['scientific'] +            name = name_obj["scientific"]              content = await self._get_snek(name)          elif isinstance(name, dict): @@ -992,7 +992,7 @@ class Snakes(Cog):              stream = BytesIO()              async with async_timeout.timeout(10): -                async with self.bot.http_session.get(content['image_list'][0]) as response: +                async with self.bot.http_session.get(content["image_list"][0]) as response:                      stream.write(await response.read())              stream.seek(0) @@ -1003,10 +1003,10 @@ class Snakes(Cog):          # Send it!          await ctx.send(              f"A wild {content['name'].title()} appears!", -            file=File(final_buffer, filename=content['name'].replace(" ", "") + ".png") +            file=File(final_buffer, filename=content["name"].replace(" ", "") + ".png")          ) -    @snakes_group.command(name='fact') +    @snakes_group.command(name="fact")      async def fact_command(self, ctx: Context) -> None:          """          Gets a snake-related fact. @@ -1022,7 +1022,7 @@ class Snakes(Cog):          )          await ctx.send(embed=embed) -    @snakes_group.command(name='snakify') +    @snakes_group.command(name="snakify")      async def snakify_command(self, ctx: Context, *, message: str = None) -> None:          """          How would I talk if I were a snake? @@ -1063,7 +1063,7 @@ class Snakes(Cog):              await ctx.send(embed=embed) -    @snakes_group.command(name='video', aliases=('get_video',)) +    @snakes_group.command(name="video", aliases=("get_video",))      async def video_command(self, ctx: Context, *, search: str = None) -> None:          """          Gets a YouTube video about snakes. @@ -1074,13 +1074,13 @@ class Snakes(Cog):          """          # Are we searching for anything specific?          if search: -            query = search + ' snake' +            query = search + " snake"          else:              snake = await self._get_snake_name() -            query = snake['name'] +            query = snake["name"]          # Build the URL and make the request -        url = 'https://www.googleapis.com/youtube/v3/search' +        url = "https://www.googleapis.com/youtube/v3/search"          response = await self.bot.http_session.get(              url,              params={ @@ -1096,14 +1096,14 @@ class Snakes(Cog):          # Send the user a video          if len(data) > 0:              num = random.randint(0, len(data) - 1) -            youtube_base_url = 'https://www.youtube.com/watch?v=' +            youtube_base_url = "https://www.youtube.com/watch?v="              await ctx.send(                  content=f"{youtube_base_url}{data[num]['id']['videoId']}"              )          else:              log.warning(f"YouTube API error. Full response looks like {response}") -    @snakes_group.command(name='zen') +    @snakes_group.command(name="zen")      async def zen_command(self, ctx: Context) -> None:          """          Gets a random quote from the Zen of Python, except as if spoken by a snake. 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) diff --git a/bot/exts/evergreen/source.py b/bot/exts/evergreen/source.py index 14fd02f3..2f25e4cb 100644 --- a/bot/exts/evergreen/source.py +++ b/bot/exts/evergreen/source.py @@ -83,7 +83,7 @@ class BotSource(commands.Cog):          url, location, first_line = self.get_source_link(source_object)          if isinstance(source_object, commands.Command): -            if source_object.cog_name == 'Help': +            if source_object.cog_name == "Help":                  title = "Help Command"                  description = source_object.__doc__.splitlines()[1]              else: diff --git a/bot/exts/evergreen/speedrun.py b/bot/exts/evergreen/speedrun.py index bf6f2117..110d5c13 100644 --- a/bot/exts/evergreen/speedrun.py +++ b/bot/exts/evergreen/speedrun.py @@ -8,7 +8,7 @@ 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: +with Path("bot/resources/evergreen/speedrun_links.json").open(encoding="utf8") as file:      LINKS = json.load(file) diff --git a/bot/exts/evergreen/status_codes.py b/bot/exts/evergreen/status_codes.py index 635eef3d..a866692e 100644 --- a/bot/exts/evergreen/status_codes.py +++ b/bot/exts/evergreen/status_codes.py @@ -22,10 +22,10 @@ class HTTPStatusCodes(commands.Cog):          if not ctx.invoked_subcommand:              await invoke_help_command(ctx) -    @http_status_group.command(name='cat') +    @http_status_group.command(name="cat")      async def http_cat(self, ctx: commands.Context, code: int) -> None:          """Sends an embed with an image of a cat, portraying the status code.""" -        embed = discord.Embed(title=f'**Status: {code}**') +        embed = discord.Embed(title=f"**Status: {code}**")          url = HTTP_CAT_URL.format(code=code)          try: @@ -37,18 +37,18 @@ class HTTPStatusCodes(commands.Cog):                      raise NotImplementedError          except ValueError: -            embed.set_footer(text='Inputted status code does not exist.') +            embed.set_footer(text="Inputted status code does not exist.")          except NotImplementedError: -            embed.set_footer(text='Inputted status code is not implemented by http.cat yet.') +            embed.set_footer(text="Inputted status code is not implemented by http.cat yet.")          finally:              await ctx.send(embed=embed) -    @http_status_group.command(name='dog') +    @http_status_group.command(name="dog")      async def http_dog(self, ctx: commands.Context, code: int) -> None:          """Sends an embed with an image of a dog, portraying the status code.""" -        embed = discord.Embed(title=f'**Status: {code}**') +        embed = discord.Embed(title=f"**Status: {code}**")          url = HTTP_DOG_URL.format(code=code)          try: @@ -60,10 +60,10 @@ class HTTPStatusCodes(commands.Cog):                      raise NotImplementedError          except ValueError: -            embed.set_footer(text='Inputted status code does not exist.') +            embed.set_footer(text="Inputted status code does not exist.")          except NotImplementedError: -            embed.set_footer(text='Inputted status code is not implemented by httpstatusdogs.com yet.') +            embed.set_footer(text="Inputted status code is not implemented by httpstatusdogs.com yet.")          finally:              await ctx.send(embed=embed) diff --git a/bot/exts/evergreen/tic_tac_toe.py b/bot/exts/evergreen/tic_tac_toe.py index 1fef427a..7b387c0a 100644 --- a/bot/exts/evergreen/tic_tac_toe.py +++ b/bot/exts/evergreen/tic_tac_toe.py @@ -58,7 +58,7 @@ class Player:              )          try: -            react, _ = await self.ctx.bot.wait_for('reaction_add', timeout=30.0, check=check_for_move) +            react, _ = await self.ctx.bot.wait_for("reaction_add", timeout=30.0, check=check_for_move)          except asyncio.TimeoutError:              return True, None          else: diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index bfd7d357..1953253b 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -129,7 +129,7 @@ class TriviaQuiz(commands.Cog):                  )              try: -                msg = await self.bot.wait_for('message', check=check, timeout=10) +                msg = await self.bot.wait_for("message", check=check, timeout=10)              except asyncio.TimeoutError:                  # In case of TimeoutError and the game has been stopped, then do nothing.                  if self.game_status[ctx.channel.id] is False: diff --git a/bot/exts/evergreen/wikipedia.py b/bot/exts/evergreen/wikipedia.py index e2172fc3..fa21b916 100644 --- a/bot/exts/evergreen/wikipedia.py +++ b/bot/exts/evergreen/wikipedia.py @@ -20,7 +20,7 @@ WIKI_THUMBNAIL = (      "https://upload.wikimedia.org/wikipedia/en/thumb/8/80/Wikipedia-logo-v2.svg"      "/330px-Wikipedia-logo-v2.svg.png"  ) -WIKI_SNIPPET_REGEX = r'(<!--.*?-->|<[^>]*>)' +WIKI_SNIPPET_REGEX = r"(<!--.*?-->|<[^>]*>)"  WIKI_SEARCH_RESULT = (      "**[{name}]({url})**\n"      "{description}\n" @@ -39,18 +39,18 @@ class WikipediaSearch(commands.Cog):          async with self.bot.http_session.get(url=url) as resp:              if resp.status == 200:                  raw_data = await resp.json() -                number_of_results = raw_data['query']['searchinfo']['totalhits'] +                number_of_results = raw_data["query"]["searchinfo"]["totalhits"]                  if number_of_results: -                    results = raw_data['query']['search'] +                    results = raw_data["query"]["search"]                      lines = []                      for article in results:                          line = WIKI_SEARCH_RESULT.format( -                            name=article['title'], +                            name=article["title"],                              description=unescape(                                  re.sub( -                                    WIKI_SNIPPET_REGEX, '', article['snippet'] +                                    WIKI_SNIPPET_REGEX, "", article["snippet"]                                  )                              ),                              url=f"https://en.wikipedia.org/?curid={article['pageid']}" diff --git a/bot/exts/evergreen/wolfram.py b/bot/exts/evergreen/wolfram.py index c57a8d7a..3cc12c03 100644 --- a/bot/exts/evergreen/wolfram.py +++ b/bot/exts/evergreen/wolfram.py @@ -59,7 +59,7 @@ def custom_cooldown(*ignore: List[int]) -> Callable:      A list of roles may be provided to ignore the per-user cooldown.      """      async def predicate(ctx: Context) -> bool: -        if ctx.invoked_with == 'help': +        if ctx.invoked_with == "help":              # if the invoked command is help we don't want to increase the ratelimits since it's not actually              # invoking the command/making a request, so instead just check if the user/guild are on cooldown.              guild_cooldown = not guildcd.get_bucket(ctx.message).get_tokens() == 0  # if guild is on cooldown @@ -118,7 +118,7 @@ async def get_pod_pages(ctx: Context, bot: Bot, query: str) -> Optional[List[Tup          request_url = QUERY.format(request="query", data=url_str)          async with bot.http_session.get(request_url) as response: -            json = await response.json(content_type='text/plain') +            json = await response.json(content_type="text/plain")          result = json["queryresult"] diff --git a/bot/exts/evergreen/xkcd.py b/bot/exts/evergreen/xkcd.py index ba9e46e0..c98830bc 100644 --- a/bot/exts/evergreen/xkcd.py +++ b/bot/exts/evergreen/xkcd.py @@ -53,7 +53,7 @@ class XKCD(Cog):              await ctx.send(embed=embed)              return -        comic = randint(1, self.latest_comic_info['num']) if comic is None else comic.group(0) +        comic = randint(1, self.latest_comic_info["num"]) if comic is None else comic.group(0)          if comic == "latest":              info = self.latest_comic_info @@ -69,7 +69,7 @@ class XKCD(Cog):                      return          embed.title = f"XKCD comic #{info['num']}" -        embed.description = info['alt'] +        embed.description = info["alt"]          embed.url = f"{BASE_URL}/{info['num']}"          if info["img"][-3:] in ("jpg", "png", "gif"): | 
