diff options
| author | 2024-02-18 20:39:16 +0100 | |
|---|---|---|
| committer | 2024-03-21 14:29:02 +0100 | |
| commit | ee3d68cc9543b79fa35de3e1db3acef24b0dca85 (patch) | |
| tree | 02617d30ba7c0a8d8398dd9b4303e2e0899f5f6e /bot | |
| parent | implement DefaultCommandErrorHandler (diff) | |
register default and command not found error handlers
Diffstat (limited to '')
| -rw-r--r-- | bot/__main__.py | 4 | ||||
| -rw-r--r-- | bot/command_error_handlers/__init__.py | 14 | ||||
| -rw-r--r-- | bot/exts/core/error_handler.py | 54 | 
3 files changed, 19 insertions, 53 deletions
| diff --git a/bot/__main__.py b/bot/__main__.py index bacb2fdd..a6eb6d88 100644 --- a/bot/__main__.py +++ b/bot/__main__.py @@ -11,12 +11,14 @@ from redis import RedisError  import bot  from bot import constants  from bot.bot import Bot +from bot.command_error_handlers import bootstrap_command_error_manager  from bot.log import setup_sentry  from bot.utils.decorators import whitelist_check  log = get_logger(__name__)  setup_sentry() +  async def _create_redis_session() -> RedisSession:      """Create and connect to a redis session."""      redis_session = RedisSession( @@ -74,6 +76,8 @@ async def main() -> None:              allowed_roles=allowed_roles,          ) +        bot.instance.register_command_error_manager(bootstrap_command_error_manager(bot.instance)) +          async with bot.instance as _bot:              _bot.add_check(whitelist_check(                  channels=constants.WHITELISTED_CHANNELS, diff --git a/bot/command_error_handlers/__init__.py b/bot/command_error_handlers/__init__.py index e69de29b..a5181636 100644 --- a/bot/command_error_handlers/__init__.py +++ b/bot/command_error_handlers/__init__.py @@ -0,0 +1,14 @@ +from pydis_core.utils.error_handling.commands import CommandErrorManager + +from bot.bot import Bot + +from .command_not_found import CommandNotFoundErrorHandler +from .default import DefaultCommandErrorHandler + + +def bootstrap_command_error_manager(bot: Bot) -> CommandErrorManager: +    """Bootstraps the command error manager with all the needed error handlers.""" +    default_handler = DefaultCommandErrorHandler() +    manager = CommandErrorManager(default=default_handler) +    manager.register_handler(CommandNotFoundErrorHandler(bot)) +    return manager diff --git a/bot/exts/core/error_handler.py b/bot/exts/core/error_handler.py index cf116ba0..ce62070b 100644 --- a/bot/exts/core/error_handler.py +++ b/bot/exts/core/error_handler.py @@ -5,11 +5,9 @@ from collections.abc import Iterable  from discord import Embed, Message  from discord.ext import commands  from pydis_core.utils.logging import get_logger -from sentry_sdk import push_scope  from bot.bot import Bot  from bot.constants import Channels, Colours, ERROR_REPLIES, NEGATIVE_REPLIES -from bot.utils.commands import get_command_suggestions  from bot.utils.decorators import InChannelCheckFailure, InMonthCheckFailure  from bot.utils.exceptions import APIError, MovedCommandError, UserNotPlayingError @@ -65,12 +63,6 @@ class CommandErrorHandler(commands.Cog):              f"Channel: {ctx.channel}"          ) -        if isinstance(error, commands.CommandNotFound): -            # Ignore messages that start with "..", as they were likely not meant to be commands -            if not ctx.invoked_with.startswith("."): -                await self.send_command_suggestion(ctx, ctx.invoked_with) -            return -          if isinstance(error, InChannelCheckFailure | InMonthCheckFailure):              await ctx.send(embed=self.error_embed(str(error), NEGATIVE_REPLIES), delete_after=7.5)              return @@ -141,51 +133,7 @@ class CommandErrorHandler(commands.Cog):              await ctx.send(embed=self.error_embed(description, NEGATIVE_REPLIES))              return -        with push_scope() as scope: -            scope.user = { -                "id": ctx.author.id, -                "username": str(ctx.author) -            } - -            scope.set_tag("command", ctx.command.qualified_name) -            scope.set_tag("message_id", ctx.message.id) -            scope.set_tag("channel_id", ctx.channel.id) - -            scope.set_extra("full_message", ctx.message.content) - -            if ctx.guild is not None: -                scope.set_extra("jump_to", ctx.message.jump_url) - -            log.exception(f"Unhandled command error: {error!s}", exc_info=error) - -    async def send_command_suggestion(self, ctx: commands.Context, command_name: str) -> None: -        """Sends user similar commands if any can be found.""" -        command_suggestions = [] -        if similar_command_names := get_command_suggestions(list(self.bot.all_commands.keys()), command_name): -            for similar_command_name in similar_command_names: -                similar_command = self.bot.get_command(similar_command_name) - -                if not similar_command: -                    continue - -                log_msg = "Cancelling attempt to suggest a command due to failed checks." -                try: -                    if not await similar_command.can_run(ctx): -                        log.debug(log_msg) -                        continue -                except commands.errors.CommandError: -                    log.debug(log_msg) -                    continue - -                command_suggestions.append(similar_command_name) - -            misspelled_content = ctx.message.content -            e = Embed() -            e.set_author(name="Did you mean:", icon_url=QUESTION_MARK_ICON) -            e.description = "\n".join( -                misspelled_content.replace(command_name, cmd, 1) for cmd in command_suggestions -            ) -            await ctx.send(embed=e, delete_after=DELETE_DELAY) +        await self.bot.command_error_manager.handle_error(error, ctx)  async def setup(bot: Bot) -> None: | 
