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/help.py | 74 +++++++++++++++++++++++----------------------- 1 file changed, 37 insertions(+), 37 deletions(-) (limited to 'bot/exts/evergreen/help.py') 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()) -- 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/help.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 42002ea00706732f5a67c9bbad194c104b046f25 Mon Sep 17 00:00:00 2001 From: ToxicKidz Date: Thu, 13 May 2021 17:54:49 -0400 Subject: chore: Break up the HelpSession.build_pages method --- bot/exts/evergreen/help.py | 172 +++++++++++++++++++++++---------------------- 1 file changed, 87 insertions(+), 85 deletions(-) (limited to 'bot/exts/evergreen/help.py') diff --git a/bot/exts/evergreen/help.py b/bot/exts/evergreen/help.py index 7e3fdad4..3c9ba4d2 100644 --- a/bot/exts/evergreen/help.py +++ b/bot/exts/evergreen/help.py @@ -287,22 +287,9 @@ class HelpSession: # Use LinePaginator to restrict embed line height 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}```**") - - 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") - - if not await self.query.can_run(self._ctx): - paginator.add_line("***You cannot run this command.***\n") + await self._add_command_signature(paginator) if isinstance(self.query, Cog): paginator.add_line(f"**{self.query.name}**") @@ -312,97 +299,112 @@ class HelpSession: # list all children commands of the queried object if isinstance(self.query, (commands.GroupMixin, Cog)): + await self._list_child_commands(paginator) - # remove hidden commands if session is not wanting hiddens - if not self._show_hidden: - filtered = [c for c in self.query.commands if not c.hidden] - else: - filtered = self.query.commands - - # if after filter there are no commands, finish up - if not filtered: - self._pages = paginator.pages - return - - if isinstance(self.query, Cog): - grouped = (("**Commands:**", self.query.commands),) - - elif isinstance(self.query, commands.Command): - grouped = (("**Subcommands:**", self.query.commands),) - - # don't show prefix for subcommands - prefix = "" + self._pages = paginator.pages - # otherwise sort and organise all commands into categories - else: - cat_sort = sorted(filtered, key=self._category_key) - grouped = itertools.groupby(cat_sort, key=self._category_key) + async def _add_command_signature(self, paginator: LinePaginator) -> None: + prefix = constants.Client.prefix - for category, cmds in grouped: - cmds = sorted(cmds, key=lambda c: c.name) + 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}```**") + 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") + if not await self.query.can_run(self._ctx): + paginator.add_line("***You cannot run this command.***\n") + + async def _list_child_commands(self, paginator: LinePaginator) -> None: + # remove hidden commands if session is not wanting hiddens + if not self._show_hidden: + filtered = [c for c in self.query.commands if not c.hidden] + else: + filtered = self.query.commands - if len(cmds) == 0: - continue + # if after filter there are no commands, finish up + if not filtered: + self._pages = paginator.pages + return - cat_cmds = [] + if isinstance(self.query, Cog): + grouped = (("**Commands:**", self.query.commands),) - for command in cmds: + elif isinstance(self.query, commands.Command): + grouped = (("**Subcommands:**", self.query.commands),) - # skip if hidden and hide if session is set to - if command.hidden and not self._show_hidden: - continue + # otherwise sort and organise all commands into categories + else: + cat_sort = sorted(filtered, key=self._category_key) + grouped = itertools.groupby(cat_sort, key=self._category_key) - # see if the user can run the command - strikeout = "" + for category, cmds in grouped: + await self._format_command_category(paginator, category, list(cmds)) - # 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 - # the mean time. - try: - can_run = await command.can_run(self._ctx) - except CheckFailure: - can_run = False + async def _format_command_category(self, paginator: LinePaginator, category: str, cmds: List[Command]) -> None: + cmds = sorted(cmds, key=lambda c: c.name) + cat_cmds = [] + for command in cmds: + cat_cmds += await self._format_command(command) - if not can_run: - # skip if we don't show commands they can't run - if self._only_can_run: - continue - strikeout = "~~" + # state var for if the category should be added next + print_cat = 1 + new_page = True - signature = self._get_command_params(command) - info = f"{strikeout}**`{prefix}{signature}`**{strikeout}" + for details in cat_cmds: - # handle if the command has no docstring - if command.short_doc: - cat_cmds.append(f"{info}\n*{command.short_doc}*") - else: - cat_cmds.append(f"{info}\n*No details provided.*") + # keep details together, paginating early if it won"t fit + lines_adding = len(details.split("\n")) + print_cat + if paginator._linecount + lines_adding > self._max_lines: + paginator._linecount = 0 + new_page = True + paginator.close_page() - # state var for if the category should be added next + # new page so print category title again print_cat = 1 - new_page = True - for details in cat_cmds: + if print_cat: + if new_page: + paginator.add_line("") + paginator.add_line(category) + print_cat = 0 - # keep details together, paginating early if it won't fit - lines_adding = len(details.split("\n")) + print_cat - if paginator._linecount + lines_adding > self._max_lines: - paginator._linecount = 0 - new_page = True - paginator.close_page() + paginator.add_line(details) - # new page so print category title again - print_cat = 1 + async def _format_command(self, command: Command) -> List[str]: + # skip if hidden and hide if session is set to + if command.hidden and not self._show_hidden: + return [] - if print_cat: - if new_page: - paginator.add_line("") - paginator.add_line(category) - print_cat = 0 + # 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 + # the mean time. + try: + can_run = await command.can_run(self._ctx) + except CheckFailure: + can_run = False + + # see if the user can run the command + strikeout = "" + if not can_run: + # skip if we don't show commands they can't run + if self._only_can_run: + return [] + strikeout = "~~" - paginator.add_line(details) + if isinstance(self.query, commands.Command): + prefix = "" + else: + prefix = constants.Client.prefix - self._pages = paginator.pages + signature = self._get_command_params(command) + info = f"{strikeout}**`{prefix}{signature}`**{strikeout}" + + # handle if the command has no docstring + short_doc = command.short_doc or "No details provided" + return [f"{info}\n*{short_doc}*"] def embed_page(self, page_number: int = 0) -> Embed: """Returns an Embed with the requested page formatted within.""" -- cgit v1.2.3