aboutsummaryrefslogtreecommitdiffstats
path: root/arthur/exts/error_handler/error_handler.py
blob: f959c7082d61e22f84ce2195086b8f198af15d74 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
"""This cog provides error handling for King Arthur."""

from discord import Message
from discord.ext import commands
from discord.ext.commands import Cog

from arthur.bot import KingArthur
from arthur.utils import generate_error_message


class ErrorHandler(Cog):
    """Error handling for King Arthur."""

    def __init__(self, bot: KingArthur) -> None:
        self.bot = bot

    async def _add_error_reaction(self, message: Message) -> None:
        await message.add_reaction("\N{CROSS MARK}")

    @Cog.listener()
    async def on_command_error(self, ctx: commands.Context, error: commands.CommandError) -> None:
        """Handle exceptions raised during command processing."""
        if isinstance(error, commands.CommandNotFound):
            return
        if isinstance(error, commands.MissingRequiredArgument | commands.BadArgument):
            await self._add_error_reaction(ctx.message)
            await ctx.send_help(ctx.command)
        elif isinstance(
            error,
            commands.CheckFailure
            | commands.NoPrivateMessage
            | commands.CommandOnCooldown
            | commands.DisabledCommand
            | commands.DisabledCommand,
        ):
            await self._add_error_reaction(ctx.message)
        elif isinstance(error, commands.CommandInvokeError):
            await self._add_error_reaction(ctx.message)
            await ctx.send(
                generate_error_message(
                    description=(
                        f"Command raised an error: `{error.original.__class__.__name__}:"
                        f" {error.original}`"
                    )
                )
            )
        else:
            await ctx.send(
                generate_error_message(
                    description=(
                        f"Unknown exception occurred: `{error.__class__.__name__}: {error}`"
                    )
                )
            )


async def setup(bot: KingArthur) -> None:
    """Add cog to bot."""
    await bot.add_cog(ErrorHandler(bot))