コード例 #1
0
ファイル: errors.py プロジェクト: cyrus01337/penguin-bot
    async def on_command_error(self, ctx, error):
        ignored_errors = (commands.CommandNotFound)
        stringed_errors = (commands.MissingPermissions,
                           commands.MissingRequiredArgument,
                           commands.BadArgument,
                           commands.BotMissingPermissions, discord.NotFound,
                           commands.CommandOnCooldown,
                           commands.BadUnionArgument)

        error = getattr(error, "original", error)

        if isinstance(error, ignored_errors):
            return

        setattr(ctx, "original_author_id",
                getattr(ctx, "original_author_id", ctx.author.id))
        owner_reinvoke_errors = (commands.CommandOnCooldown,
                                 commands.DisabledCommand)

        if ctx.original_author_id in self.bot.owner_ids and isinstance(
                error, owner_reinvoke_errors):
            return await ctx.reinvoke()
        if isinstance(error, stringed_errors):
            await ctx.reply(embed=ErrorEmbed(description=str(error)))
        elif isinstance(error, commands.NotOwner):
            await ctx.reply(embed=ErrorEmbed(
                description="You do not own this bot."))
        elif isinstance(error, commands.CheckFailure):
            await ctx.reply(embed=ErrorEmbed(
                description=
                "You are blacklisted, join the support server to find out more https://penguin.vaskel.xyz/support"
            ))

        else:
            c = self.bot.get_channel(770685546724982845)
            prettify_exceptions.DefaultFormatter(
            ).theme['_ansi_enabled'] = False
            traceback = ''.join(
                prettify_exceptions.DefaultFormatter().format_exception(
                    type(error), error, error.__traceback__))
            embed = ErrorEmbed(
                description=
                f"Reported to the support server. Need more help? [Join the support server](https://penguin.vaskel.xyz/support)\n```Error: \n{traceback}```",
            )
            embed.set_footer(text=f"Caused by: {ctx.command}")
            await ctx.reply(embed=embed)

            #Support server embed
            embed = ErrorEmbed(description=f"```{traceback}```", )
            embed.add_field(name="Details:",
                            value=f"""
                Caused by: `{str(ctx.author)} [{ctx.author}.id]`
                In guild: `{str(ctx.guild)} [{ctx.guild.id}]`
                Command: `{ctx.command}`
                """)
            await c.send(embed=embed)
コード例 #2
0
    async def on_command_error(self, ctx, error):
        if isinstance(error, commands.CommandNotFound):
            await ctx.reply("Command not Found")
            return

        if isinstance(error, commands.MissingRequiredArgument):
            return await ctx.reply(
                f"Usage: `{ctx.prefix}{ctx.command.qualified_name} {ctx.command.signature}`"
            )

        if isinstance(error, commands.CommandOnCooldown):
            bot_msg = await ctx.reply(
                f"{ctx.author.mention}, you have to wait {round(error.retry_after, 2)} seconds before using this again"
            )
            await asyncio.sleep(round(error.retry_after))
            await bot_msg.delete()
            return

        if isinstance(error, commands.CommandInvokeError):
            _traceback = ''.join(prettify_exceptions.DefaultFormatter().format_exception(type(error), error, error.__traceback__))
            self.bot.logger.error(f"Something went wrong! error: {error}\n{_traceback}")

            error = discord.Embed(
                title="Something went wrong!",
                description=f"Here is the error\n```{error}```",
                color=0x2E3137
            )
            await ctx.reply(embed=error)
コード例 #3
0
    async def on_command_error(self, ctx, error):
        ignored_errors = (commands.CommandNotFound)
        stringed_errors = (commands.MissingPermissions,
                           commands.MissingRequiredArgument,
                           commands.BadArgument,
                           commands.BotMissingPermissions, discord.NotFound,
                           commands.CommandOnCooldown,
                           commands.BadUnionArgument,
                           flags.ArgumentParsingError)

        if isinstance(error, ignored_errors):
            return

        if isinstance(error, stringed_errors):
            await ctx.reply(embed=discord.Embed(title=str(error),
                                                color=discord.Color.red()))
        elif isinstance(error, commands.NotOwner):
            await ctx.reply(embed=discord.Embed(
                title="You do not own this bot.", color=discord.Color.red()))
        else:
            prettify_exceptions.DefaultFormatter(
            ).theme['_ansi_enabled'] = False
            traceback = ''.join(
                prettify_exceptions.DefaultFormatter().format_exception(
                    type(error), error, error.__traceback__))
            url = await self.mystbin.post(traceback, syntax="py")
            embed = discord.Embed(
                title="An error occurred!",
                description=
                f"[Please report this to the bots GitHub with the mystbin link.](https://github.com/ImVaskel/diabetes-discord-rank-bot) \n {url}",
                color=discord.Color.red(),
                timestamp=ctx.message.created_at)
            embed.set_footer(
                text="That above is a hyperlink to the github, click it!")

            await ctx.send(embed=embed)
コード例 #4
0
    async def handle_error(self, ctx, error):
        self.errors_handled += 1
        if isinstance(error, (ItemNotFound, NetNotFound)):
            return await ctx.send(error)
        if isinstance(error, commands.CommandNotFound):
            return  # await ctx.send("stuff")
        if isinstance(error, commands.MissingRequiredArgument):
            return await ctx.send(
                f"Missing required argument \"{error.param.name}\"")
        if isinstance(error,
                      (commands.ConversionError, commands.NotOwner,
                       commands.CheckAnyFailure, commands.CheckFailure)):
            return
        if isinstance(error, commands.UserInputError):
            return await ctx.send(error)
        if isinstance(error, flags.ArgumentParsingError):
            return await ctx.send("Invalid flag signature.")
        if isinstance(error, commands.MaxConcurrencyReached):
            return await ctx.send(
                "Another instance of this command is running.")

        _base = (type(error), error, error.__traceback__)

        _complete_traceback = "".join(
            prettify_exceptions.DefaultFormatter().format_exception(*_base))
        try:
            _myst = await ctx.bot.mystbin.post(_complete_traceback,
                                               syntax="python")
        except APIError:
            _myst = ""

        _error = '{0.__class__.__name__}: {0}'.format(
            error.original) if isinstance(
                error, commands.CommandInvokeError) else error
        _broad_traceback = escape_markdown(str(_error)[:1800])

        await ctx.send(
            f"Something has gone wrong while executing your command.\n{_broad_traceback}\n\n**<{_myst}>**"
        )
        raise error
コード例 #5
0
ファイル: events.py プロジェクト: HimawanRenn/Life
    async def on_command_error(self, ctx: context.Context, error) -> None:

        error = getattr(error, 'original', error)

        if isinstance(error, commands.CommandNotFound):
            return

        elif isinstance(error, commands.CommandOnCooldown):

            cooldowns = {
                commands.BucketType.default: f'for the whole bot.',
                commands.BucketType.user: f'for you.',
                commands.BucketType.guild: f'for this server.',
                commands.BucketType.channel: f'for this channel.',
                commands.BucketType.member: f'cooldown for you.',
                commands.BucketType.category: f'for this channel category.',
                commands.BucketType.role: f'for your role.'
            }
            await ctx.send(
                f'The command `{ctx.command}` is on cooldown {cooldowns[error.cooldown.type]} You can retry in '
                f'`{self.bot.utils.format_seconds(seconds=error.retry_after, friendly=True)}`'
            )
            return

        elif isinstance(error, commands.MaxConcurrencyReached):
            cooldowns = {
                commands.BucketType.default: f'.',
                commands.BucketType.user: f' per user.',
                commands.BucketType.guild: f' per server.',
                commands.BucketType.channel: f' per channel.',
                commands.BucketType.member: f' per member.',
                commands.BucketType.category: f' per channel category.',
                commands.BucketType.role: f' per role.'
            }
            await ctx.send(
                f'The command `{ctx.command}` is already being ran at its maximum of {error.number} time(s){cooldowns[error.per]} Retry a bit later.'
            )
            return

        elif isinstance(error, commands.BotMissingPermissions):
            permissions = '\n'.join(
                [f'> {permission}' for permission in error.missing_perms])
            message = f'I am missing the following permissions required to run the command `{ctx.command}`.\n{permissions}'
            try:
                await ctx.send(message)
            except discord.Forbidden:
                try:
                    await ctx.author.send(message)
                except discord.Forbidden:
                    pass
            return

        elif isinstance(error, commands.MissingPermissions):
            permissions = '\n'.join(
                [f'> {permission}' for permission in error.missing_perms])
            await ctx.send(
                f'You are missing the following permissions required to run the command `{ctx.command}`.\n{permissions}'
            )
            return

        elif isinstance(error, commands.MissingRequiredArgument):
            await ctx.send(
                f'You missed the `{error.param.name}` parameter for the command `{ctx.command}`. '
                f'Use `{self.bot.config.prefix}help {ctx.command}` for more information on what parameters to use.'
            )
            return

        error_messages = {
            exceptions.ArgumentError:
            f'{error}',
            exceptions.ImageError:
            f'{error}',
            exceptions.VoiceError:
            f'{error}',
            commands.CheckFailure:
            f'{error}',
            NodeNotFound:
            f'There are no lavalink nodes available right now.',
            commands.TooManyArguments:
            f'You used too many parameters for the command `{ctx.command}`. Use `{self.bot.config.prefix}help {ctx.command}` for '
            f'more information on what parameters to use.',
            commands.BadArgument:
            f'I was unable to understand a parameter that you used for the command `{ctx.command}`. '
            f'Use `{self.bot.config.prefix}help {ctx.command}` for more information on what parameters to use.',
            commands.BadUnionArgument:
            f'I was unable to understand a parameter that you used for the command `{ctx.command}`. '
            f'Use `{self.bot.config.prefix}help {ctx.command}` for more information on what parameters to use.',
            commands.NoPrivateMessage:
            f'The command `{ctx.command}` can not be used in private messages.',
            commands.NotOwner:
            f'The command `{ctx.command}` is owner only.',
            commands.NSFWChannelRequired:
            f'The command `{ctx.command}` can only be ran in a NSFW channel.',
            commands.DisabledCommand:
            f'The command `{ctx.command}` has been disabled.',
            commands.ExpectedClosingQuoteError:
            f'You missed a closing quote in the parameters passed to the `{ctx.command}` command.',
            commands.UnexpectedQuoteError:
            f'There was an unexpected quote in the parameters passed to the `{ctx.command}` command.'
        }

        error_message = error_messages.get(type(error), None)
        if error_message is not None:
            await ctx.send(error_message)
            return

        await ctx.send(
            f'Something went wrong while executing that command. Please use `{self.bot.config.prefix}support` for more help or information.'
        )

        formatter = prettify_exceptions.DefaultFormatter()

        formatter.theme['_ansi_enabled'] = True
        print(
            f'\n{"".join(formatter.format_exception(type(error), error, error.__traceback__)).strip()}\n'
        )

        time = self.bot.utils.format_datetime(datetime=datetime.now(pytz.UTC))
        guild = f'`Guild:` {ctx.guild} `{ctx.guild.id}`\n' if ctx.guild else ''
        info = f'Error in command `{ctx.command}`\n\n{guild}`Channel:` {ctx.channel} `{ctx.channel.id}`\n`Author:` {ctx.author} `{ctx.author.id}`\n`Time:` {time}'

        embed = discord.Embed(colour=ctx.colour,
                              description=f'{ctx.message.content}')
        embed.add_field(name='Info:', value=info)

        await self.bot.errors_webhook.send(
            embed=embed,
            username=f'{ctx.author}',
            avatar_url=str(
                ctx.author.avatar_url_as(format='gif' if ctx.author.
                                         is_avatar_animated() else 'png')))

        formatter.theme['_ansi_enabled'] = False
        traceback = "".join(
            formatter.format_exception(type(error), error,
                                       error.__traceback__)).strip()

        if len(traceback) > 2000:
            async with self.bot.session.post('https://mystb.in/documents',
                                             data=traceback) as response:
                response = await response.json()
            traceback = f'https://mystb.in/{response["key"]}.python'
        else:
            traceback = f'```\n{traceback}\n```'

        await self.bot.errors_webhook.send(
            content=f'{traceback}',
            username=f'{ctx.author}',
            avatar_url=str(
                ctx.author.avatar_url_as(format='gif' if ctx.author.
                                         is_avatar_animated() else 'png')))
コード例 #6
0
ファイル: error_handler.py プロジェクト: ZiRO-Bot/ziBot
    async def on_command_error(self, ctx, error):
        if isinstance(error, commands.CommandNotFound):
            return

        if isinstance(error, commands.BotMissingPermissions):
            return await ctx.send(
                f"The bot doesn't have `{missing_perms}` permission to do this command!"
            )

        if isinstance(error, commands.MissingRequiredArgument):
            return await ctx.send(
                f"Usage: `{ctx.prefix}{ctx.command.qualified_name} {ctx.command.signature}`"
            )

        if isinstance(error, commands.CommandOnCooldown):
            bot_msg = await ctx.send(
                f"{ctx.message.author.mention}," + f" slowdown bud!"
            )
            await asyncio.sleep(round(error.retry_after))
            await bot_msg.delete()
            return

        if isinstance(error, commands.CommandInvokeError):
            _traceback = ''.join(prettify_exceptions.DefaultFormatter().format_exception(type(error), error, error.__traceback__))
            self.bot.logger.error(f"Something went wrong! error: {error}\n{_traceback}")

            # Give details about the error
            # print(
            #     "Ignoring exception in command {}:".format(ctx.command), file=sys.stderr
            # )
            # print(_traceback, file=sys.stderr)

            # Send embed that when user react withh greenTick bot will send it to bot owner
            desc = (
                f"The command was unsuccessful because of this reason:\n```{error}```\n"
                + "React with <:greenTick:767209095090274325> to report the error to ZiRO2264#4572"
            )
            e = discord.Embed(
                title="Something went wrong!",
                description=desc,
                colour=discord.Colour(0x2F3136),
            )
            e.set_footer(text="Waiting for answer...", icon_url=ctx.author.avatar_url)
            msg = await ctx.send(embed=e)
            await msg.add_reaction("<:greenTick:767209095090274325>")

            def check(reaction, user):
                return (
                    user == ctx.author
                    and str(reaction.emoji) == "<:greenTick:767209095090274325>"
                )

            try:
                reaction, user = await self.bot.wait_for(
                    "reaction_add", timeout=60.0, check=check
                )
            except asyncio.TimeoutError:
                e.set_footer(
                    text="You were too late to answer.", icon_url=ctx.author.avatar_url
                )
                await msg.edit(embed=e)
                await msg.clear_reactions()
            else:
                e_owner = discord.Embed(
                    title="Something went wrong!",
                    description=f"An error occured:\n```{error}```",
                    colour=discord.Colour(0x2F3136),
                )
                e_owner.add_field(name="Executor", value=ctx.author)
                e_owner.add_field(name="Message", value=ctx.message.content)
                e_owner.add_field(name="Guild", value=ctx.guild)
                bot_owner = self.bot.get_user(self.bot.master[0])
                await bot_owner.send(embed=e_owner)
                e.set_footer(
                    text=f"Error has been reported to {bot_owner}",
                    icon_url=ctx.author.avatar_url,
                )
                await msg.edit(embed=e)
                await msg.clear_reactions()

            return
コード例 #7
0
    async def on_command_error(self, ctx, error):
        owner_errors = (
            commands.MissingAnyRole,
            commands.MissingPermissions,
            commands.MissingRole,
            commands.CommandOnCooldown,
            commands.DisabledCommand,
        )
        if await self.bot.is_owner(ctx.author) and isinstance(
                error, owner_errors):
            return await ctx.reinvoke()

        if not isinstance(
                error, (commands.CommandNotFound, commands.CommandOnCooldown)):
            ctx.command.reset_cooldown(ctx)

        if isinstance(error, NotRegistered):
            return await ctx.send(str(error))

        if hasattr(ctx.command, "on_error"):
            return

        cog = ctx.cog
        if cog and cog._get_overridden_method(cog.cog_command_error):
            return

        ignored = (commands.CommandNotFound, )

        error = getattr(error, "original", error)

        if isinstance(error, ignored):
            return

        command = ctx.command.qualified_name

        if isinstance(error, commands.CheckFailure):
            if self.bot.maintenance:
                return await ctx.send(embed=ctx.embed(
                    title="⚠️ Maintenence mode is active."))
            if ctx.author.id in self.bot.blacklist:
                reason = self.bot.blacklist.get(
                    ctx.author.id,
                    "No reason, you probably did something dumb.")
                embed = ctx.embed(
                    title=
                    "⚠️ You are blacklisted from using this bot globally.",
                    description=
                    (f"**Blacklisted For:** {reason}"
                     f"\n\nYou can join the support server [here]({self.bot.support_invite}) "
                     f"if you feel this is a mistake."),
                )
                try:
                    await ctx.author.send(embed=embed)
                except discord.Forbidden:
                    await ctx.send(embed=embed)
                finally:
                    return

            return await ctx.send(embed=ctx.embed(description=str(error)))

        if isinstance(error, discord.Forbidden):
            return await ctx.send(embed=ctx.embed(
                description=
                f"I do not have the correct permissions for `{command}`"))

        if isinstance(error, commands.CommandOnCooldown):
            retry = humanize.precisedelta(error.retry_after,
                                          minimum_unit="seconds")
            cd = error.cooldown
            embed = ctx.embed(description=(
                f"<a:countdown:827916388659363870> **{command}** is on cooldown. Try again in {retry}.\n"
                f"You can use this command **{cd.rate} {ctx.plural('time(s)', cd.rate)} every {humanize.precisedelta(cd.per, minimum_unit='seconds')}.\n"
                f"Type: {cd.type.name}"))

            return await ctx.send(embed=embed)

        if isinstance(error, commands.NoPrivateMessage):
            try:
                return await ctx.author.send(embed=ctx.embed(
                    description=f"{ctx.invoked_with} cannot be used in DM's"))
            except discord.HTTPException:
                pass

        if isinstance(error, commands.MissingRequiredArgument):
            errors = str(error).split(" ", maxsplit=1)
            return await ctx.send(embed=ctx.embed(description=(
                f"`{errors[0]}` {errors[1]}\n"
                f"You can view the help for this command with `{ctx.clean_prefix}help` `{command}`"
            )))

        if isinstance(error, commands.DisabledCommand):
            return await ctx.send(embed=ctx.embed(
                description=f"`{command}` has been disabled."))

        if isinstance(error, commands.BadArgument):
            return await ctx.send(embed=ctx.embed(title=str(error)))

        if isinstance(error, asyncio.TimeoutError):
            return await ctx.send(embed=ctx.embed(
                description=f"{command} timed out."))

        formatted = traceback.format_exception(type(error), error,
                                               error.__traceback__)
        pretty_traceback = "".join(
            prettify_exceptions.DefaultFormatter().format_exception(
                type(error), error, error.__traceback__))

        desc = (f"Command: {ctx.invoked_with}\n"
                f"Full content: {ctx.escape(ctx.message.content)}\n"
                f"Guild: {ctx.guild.name} ({ctx.guild.id})\n"
                f"Channel: {ctx.channel.name} ({ctx.channel.id})\n"
                f"User: {ctx.author.name} ({ctx.author.id})\n"
                f"Jump URL: {ctx.message.jump_url}")
        embed = ctx.embed(
            title="AN ERROR OCCURED",
            url=await ctx.mystbin(pretty_traceback) + ".py",
            description=desc,
        )
        await self.bot.error_webhook.send(f"```py\n{''.join(formatted)}```",
                                          embed=embed)

        await ctx.send(f"Oops, an error occured. Here's some info on it:"
                       f"```py\n{error}\n```")
コード例 #8
0
    async def on_command_error(self, ctx, error):
        def setup_embed(**kwargs):
            kwargs["colour"] = 0xf5291b
            return self.bot.embed(ctx, **kwargs)

        async def send_error(ctx, error):
            embed = setup_embed(
                title="Something went wrong...",
                description=f"```py\nAn Error Occurred:\n{error}\n```",
            )
            embed.set_author(
                name=f"{ctx.author} | {ctx.author.id}", icon_url=ctx.author.avatar_url
            )
            if ctx.guild:
                cmd = (
                    "None"
                    if isinstance(ctx.command, type(None))
                    else ctx.command.qualified_name
                )
                embed.set_thumbnail(url=ctx.guild.icon_url_as(size=512))
                embed.add_field(
                    name="Key Information:",
                    value=f"Channel: {ctx.channel} {ctx.channel.id}\n"
                    f"Guild: {ctx.guild} {ctx.guild.id}\n"
                    f"Command: {cmd}\n"
                    f"Message Content: {ctx.message.content}",
                )

            await self.bot.error_webhook.send(embed=embed)

        ignored_errors = (
            commands.CommandNotFound,
        )

        error = getattr(error, "original", error)

        if isinstance(error, ignored_errors):
            return

        setattr(
            ctx, "original_author_id", getattr(
                ctx, "original_author_id", ctx.author.id)
        )
        owner_reinvoke_errors = (
            commands.MissingAnyRole,
            commands.MissingPermissions,
            commands.MissingRole,
            commands.CommandOnCooldown,
            commands.DisabledCommand,
        )

        if ctx.original_author_id in self.bot.owner_ids and isinstance(
            error, owner_reinvoke_errors
        ):
            return await ctx.reinvoke()

        elif isinstance(error, commands.MaxConcurrencyReached):
            return await self.send_to_ctx_or_author(
                ctx,
                embed=setup_embed(
                    description=f"{error}"
                ),
                delete_after=5.0,
            )

        # Command failed global check
        elif isinstance(error, commands.CheckFailure):
            if self.bot.maintenance_mode:
                fmt = ("The developer has currently put the bot into maintenance mode, this could be due to a severe "
                       "bug or something that requires the bot to be contained. The bots functionality "
                       "outside of commands will still work though, sorry for the inconvenience.\n"
                       f"For more updates you may join the support server: {self.bot.support_url}")
                embed = self.bot.embed(title="\N{WARNING SIGN} | Maintenance Mode",
                                       description=fmt)
                return await ctx.send(embed=embed)

            try:
                reason = self.bot.blacklist[ctx.author.id]
            except KeyError:
                return await self.send_to_ctx_or_author(
                    ctx,
                    embed=setup_embed(
                        description=f"{error}"
                    )
                )

            return await ctx.send(f"You are blacklisted from using this bot globally for *{reason}*")

        # If the emoji couldn't be converted
        elif isinstance(error, commands.PartialEmojiConversionFailure):
            if ctx.command.name == "emoji":
                return

            return await self.send_to_ctx_or_author(
                ctx,
                embed=setup_embed(
                    description=f"{error}"
                ),
                delete_after=5.0,
            )

        # Command is on Cooldown
        elif isinstance(error, commands.CommandOnCooldown):
            return await self.send_to_ctx_or_author(
                ctx,
                embed=setup_embed(
                    description=f"This command is on cooldown. **`{int(error.retry_after)}` seconds**"
                ),
                delete_after=5.0,
            )

        # Missing argument
        elif isinstance(error, commands.MissingRequiredArgument):
            return await ctx.send_help(ctx.command)

        # Missing Permissions
        elif isinstance(error, commands.MissingPermissions):
            return await self.send_to_ctx_or_author(
                ctx,
                embed=setup_embed(
                    description=f"You're missing the required permission: `{error.missing_perms[0]}`"
                ),
            )

        # Bad Argument passed
        elif isinstance(error, commands.BadArgument):
            return await self.send_to_ctx_or_author(
                ctx,
                embed=setup_embed(
                    description=f"{error}"
                ),
            )

        # Missing Permissions
        elif isinstance(error, commands.BotMissingPermissions):
            return await self.send_to_ctx_or_author(
                ctx,
                embed=setup_embed(
                    description=f"I'm missing the required permission: `{error.missing_perms[0]}`"
                ),
            )

        # User who invoked command is not owner
        elif isinstance(error, commands.NotOwner):
            return await self.send_to_ctx_or_author(
                ctx,
                embed=setup_embed(
                    description="You must be the owner of the bot to run this."
                ),
            )

        # Role was not found
        elif isinstance(error, commands.RoleNotFound):
            return await self.send_to_ctx_or_author(
                ctx,
                embed=setup_embed(
                    description=f"{error}"
                ),
            )

        # Custom exception
        elif isinstance(error, utils.MemberIsStaff):
            return await self.send_to_ctx_or_author(
                ctx,
                embed=setup_embed(
                    description=f"{error}"
                ),
            )

        # Custom exception
        elif isinstance(error, utils.UserNotVoted):
            return await self.send_to_ctx_or_author(
                ctx,
                embed=setup_embed(
                    description=f"{error}"
                ),
            )

        # Custom exception
        elif isinstance(error, utils.NoTodoItems):
            return await self.send_to_ctx_or_author(
                ctx,
                embed=setup_embed(
                    description=f"{error}"
                ),
            )

        prettify_exceptions.DefaultFormatter().theme['_ansi_enabled'] = False
        tb = (
            ''.join(prettify_exceptions.DefaultFormatter().format_exception(
                type(error), error, error.__traceback__))
        )

        if len(tb) > 1000:
            tb = await utils.mystbin(self.bot.session, tb)

        await self.send_to_ctx_or_author(ctx, embed=setup_embed(
            title="Uhoh an error has occurred...",
            description=(
                "Here's some details on it: ```py\n"
                f"{error}```"
            )
        ))
        await send_error(ctx, tb)

        raise error
コード例 #9
0
    async def on_command_error(self, ctx, error):
        if isinstance(error, Maintenance):
            return await ctx.send(embed=ctx.embed(title='⚠️ Maintenence mode is active.'))

        if isinstance(error, Blacklisted):
            reason = self.bot.blacklist.get(ctx.author.id, "No reason, you probably did something dumb.")
            return await ctx.author.send(embed=ctx.embed(title='⚠️ You are blacklisted.',
                                                  description=f'**Blacklisted For:** {reason}'
                                                              f'\n\nYou can join the support server [here]({self.bot.support_invite}) if you feel this is a mistake.'))

        command = ctx.invoked_with

        # This prevents any commands with local handlers being handled here in on_command_error.
        global match
        if hasattr(ctx.command, 'on_error'):
            return

        # This prevents any cogs with an overwritten cog_command_error being handled here.
        cog = ctx.cog
        if cog and cog._get_overridden_method(cog.cog_command_error) is not None:
            return

        # ignored = (commands.CommandNotFound,)  # if you want to not send error messages
        ignored = ()

        # Allows us to check for original exceptions raised and sent to CommandInvokeError.
        # If nothing is found. We keep the exception passed to on_command_error.
        error = getattr(error, 'original', error)

        # Anything in ignored will return and prevent anything happening.
        if isinstance(error, ignored):
            return

        if isinstance(error, commands.CommandNotFound):
            failed_command = re.match(rf"^({ctx.prefix})\s*(.*)", ctx.message.content, flags=re.IGNORECASE).group(2)
            matches = finder(failed_command, self.bot.command_list, lazy=False)
            if not matches:
                return
            match = None
            for command in matches:
                cmd = self.bot.get_command(command)
                if not await cmd.can_run(ctx):
                    return
                match = command
                break
            return await ctx.send(embed=ctx.embed(
                description=f"No command called `{failed_command}` found. Did you mean `{match}`?"
            ))

        if isinstance(error, commands.CheckFailure):
            return await ctx.send(embed=ctx.embed(
                description=f'You do not have the correct permissions for `{command}`'
            ))

        if isinstance(error, discord.Forbidden):
            return await ctx.send(embed=ctx.embed(
                description=f'I do not have the correct permissions for `{command}`'
            ))

        if isinstance(error, commands.CommandOnCooldown):
            retry = humanize.precisedelta(error.retry_after, minimum_unit='seconds')
            return await ctx.send(embed=ctx.embed(
                description=f"{command} is on cooldown.\nTry again in {retry}"
            ))

        if isinstance(error, commands.NoPrivateMessage):
            try:
                return await ctx.author.send(embed=ctx.embed(description=f"{ctx.invoked_with} cannot be used in DM's"))
            except discord.HTTPException:
                pass

        if isinstance(error, commands.MissingRequiredArgument):
            errors = str(error).split(" ", maxsplit=1)
            return await ctx.send(embed=ctx.embed(
                description=f'`{errors[0]}` {errors[1]}\n'
                            f'You can view the help for this command with `{ctx.clean_prefix}help` `{command}`'
            ))

        if isinstance(error, commands.DisabledCommand):
            return await ctx.send(embed=ctx.embed(description=f'`{command}` has been disabled.'))

        if isinstance(error, commands.BadArgument):
            return await ctx.send(embed=ctx.embed(title=str(error),
                                                  description=f'You provided a bad argument to `{command}`! View `{ctx.clean_prefix}help {command}` for more info on how to use this command.'))

        print('Ignoring exception in command {}:'.format(ctx.command), file=sys.stderr)
        traceback.print_exception(type(error),
                                  error,
                                  error.__traceback__,
                                  file=sys.stderr)

        formatted = traceback.format_exception(type(error), error, error.__traceback__)
        pretty_traceback = "".join(
            prettify_exceptions.DefaultFormatter().format_exception(type(error), error, error.__traceback__)
        )
        log_channel = await self.bot.fetch_channel(817433615473311744)
        webhook = await log_channel.webhooks()
        msg = (
            f"Command: {ctx.invoked_with}\n"
            f"Full content: {ctx.escape(ctx.message.content)}\n"
            f"Guild: {ctx.guild.name} ({ctx.guild.id})\n"
            f"Channel: {ctx.channel.name} ({ctx.channel.id})\n"
            f"User: {ctx.author.name} ({ctx.author.id})\n"
            f"Jump URL: {ctx.message.jump_url}"
        )
        embed = ctx.embed(title='AN ERROR OCCURED', url=await ctx.mystbin(pretty_traceback) + '.py',
                          description=f"```yaml\n{msg}```")
        await webhook[0].send(f"```py\n{''.join(formatted)}```", embed=embed)

        error = "".join(formatted)
        if len(error) > 1700:
            error = await ctx.mystbin(str(error)) + ".py"

        await ctx.send(
            f"Something has gone wrong while executing `{command}`. You should not be seeing this, I have contacted my developer with information about this error.\n"
            f"```py\n{error}\n```")
コード例 #10
0
ファイル: errors.py プロジェクト: FrostiiWeeb/penguin-bot
    async def on_command_error(self, ctx: commands.Context, error):
        ignored_errors = (commands.CommandNotFound, )
        stringed_errors = (commands.MissingPermissions,
                           commands.MissingRequiredArgument,
                           commands.BadArgument,
                           commands.BotMissingPermissions, discord.NotFound,
                           commands.CommandOnCooldown,
                           commands.BadUnionArgument, Blacklisted,
                           commands.TooManyArguments)

        cog = ctx.cog
        if cog:
            if cog._get_overridden_method(cog.cog_command_error) is not None:
                return

        error = getattr(error, "original", error)

        if isinstance(error, ignored_errors):
            return

        setattr(ctx, "original_author_id",
                getattr(ctx, "original_author_id", ctx.author.id))
        owner_reinvoke_errors = (commands.CommandOnCooldown,
                                 commands.DisabledCommand)

        if ctx.original_author_id in self.bot.owner_ids and isinstance(
                error, owner_reinvoke_errors):
            return await ctx.reinvoke()
        if isinstance(error, stringed_errors):
            await ctx.reply(embed=ErrorEmbed(description=str(error)))
        elif isinstance(error, commands.NotOwner):
            await ctx.reply(embed=ErrorEmbed(
                description="You do not own this bot."))
        elif isinstance(error, commands.CheckFailure):
            await ctx.reply(embed=ErrorEmbed(
                description=
                "You are blacklisted, join the support server to find out more https://penguin.vaskel.xyz/support"
            ))

        else:
            c = self.bot.get_channel(self.bot.config['log-channel'])
            prettify_exceptions.DefaultFormatter(
            ).theme['_ansi_enabled'] = False
            traceback = ''.join(
                prettify_exceptions.DefaultFormatter().format_exception(
                    type(error), error, error.__traceback__))

            url = str(await self.bot.mystbin.post(
                traceback)) if len(traceback) > 512 else None

            embed = ErrorEmbed(description=url or f"```{traceback}```", )
            embed.set_footer(
                text=
                f"Caused by: {ctx.command} • Click the title of the embed to join the support server!"
            )
            await ctx.reply(embed=embed)

            # Support server embed
            embed = ErrorEmbed(description=url or f"```{traceback}```", )
            embed.add_field(
                name="Details:",
                value=(f"Caused by: `{str(ctx.author)} [{ctx.author.id}]`\n"
                       f"In guild: `{str(ctx.guild)} [{ctx.guild.id}]`\n"
                       f"Command: `{ctx.command}`"))
            await c.send(embed=embed)
コード例 #11
0
ファイル: cog.py プロジェクト: IAmTomahawkx/taptrack
import os
import pprint
from typing import Tuple, Optional

import aiohttp
import prettify_exceptions
import yarl
from discord.ext import commands, menus

from . import state, paginators

formatter = prettify_exceptions.DefaultFormatter()

def _frame(t):
    header = f"File \"{t['filename']}\", line {t['lineno']}, in {t['function']}\n"
    return header + pprint.pformat(t['scope'])

class TapTrack(commands.Cog):
    """
    TapTrack error tracking
    """
    def __init__(self, bot: commands.Bot):
        self.bot = bot
        self._haste_cache = {}
        self._haste_target = yarl.URL(os.getenv("TAPTRACK_PASTE_SITE", "https://mystb.in/")).with_path("documents")

        self._session = None
        if state.TAPTRACK_STORAGE in ("postgres", "postgresql"):
            self.state = state.PostgresState(self)

        elif state.TAPTRACK_STORAGE == "redis":
コード例 #12
0
    def __init__(self, bot: Life) -> None:
        self.bot = bot

        self.bot.error_formatter = prettify_exceptions.DefaultFormatter()
        self.bot.mystbin = mystbin.Client()
コード例 #13
0
    async def on_command_error(self, ctx: context.Context, error) -> None:

        error = getattr(error, 'original', error)

        if isinstance(error, commands.CommandNotFound):
            return

        elif isinstance(error, commands.CommandOnCooldown):
            cooldown_types = {
                commands.BucketType.default: f'for the whole bot.',
                commands.BucketType.user: f'for you.',
                commands.BucketType.member: f'for you.',
                commands.BucketType.role: f'for your role.',
                commands.BucketType.guild: f'for this server.',
                commands.BucketType.channel: f'for this channel.',
                commands.BucketType.category: f'for this channel category.'
            }
            await ctx.send(
                f'The command `{ctx.command}` is on cooldown {cooldown_types.get(error.cooldown.type, "for you.")} You can retry in '
                f'`{self.bot.utils.format_seconds(seconds=error.retry_after, friendly=True)}`'
            )
            return

        elif isinstance(error, commands.MaxConcurrencyReached):
            cooldowns = {
                commands.BucketType.default: f'.',
                commands.BucketType.user: f' per user.',
                commands.BucketType.member: f' per member.',
                commands.BucketType.role: f' per role.',
                commands.BucketType.guild: f' per server.',
                commands.BucketType.channel: f' per channel.',
                commands.BucketType.category: f' per channel category.',
            }
            await ctx.send(
                f'The command `{ctx.command}` is being ran at its maximum of {error.number} time(s){cooldowns.get(error.per, ".")} Retry a bit later.'
            )
            return

        elif isinstance(error, commands.BotMissingPermissions):
            permissions = '\n'.join(
                [f'> {permission}' for permission in error.missing_perms])
            message = f'I am missing the following permissions required to run the command `{ctx.command}`.\n{permissions}'
            try:
                await ctx.send(message)
            except discord.Forbidden:
                try:
                    await ctx.author.send(message)
                except discord.Forbidden:
                    return
            return

        elif isinstance(error, commands.MissingPermissions):
            permissions = '\n'.join(
                [f'> {permission}' for permission in error.missing_perms])
            await ctx.send(
                f'You are missing the following permissions required to run the command `{ctx.command}`.\n{permissions}'
            )
            return

        elif isinstance(error, commands.MissingRequiredArgument):
            await ctx.send(
                f'You missed the `{error.param.name}` argument. Use `{self.bot.config.prefix}help {ctx.command}` for more information on what arguments to use.'
            )
            return

        elif isinstance(error, commands.BadUnionArgument):
            await ctx.send(
                f'I was unable to convert the `{error.param}` argument. Use `{self.bot.config.prefix}help {ctx.command}` for more information on what arguments '
                f'to use.')
            return

        elif isinstance(error, commands.MissingRole):
            await ctx.send(
                f'The role `{error.missing_role}` is required to run this command.'
            )
            return

        elif isinstance(error, commands.BotMissingRole):
            await ctx.send(
                f'The bot requires the role `{error.missing_role}` to run this command.'
            )
            return

        elif isinstance(error, commands.MissingAnyRole):
            await ctx.send(
                f'The roles {", ".join([f"`{role}`" for role in error.missing_roles])} are required to run this command.'
            )
            return

        elif isinstance(error, commands.BotMissingAnyRole):
            await ctx.send(
                f'The bot requires the roles {", ".join([f"`{role}`" for role in error.missing_roles])} to run this command.'
            )
            return

        elif isinstance(error, commands.BadArgument):

            if isinstance(error, commands.MessageNotFound):
                await ctx.send(
                    f'A message for the argument `{error.argument}` was not found.'
                )
            elif isinstance(error, commands.MemberNotFound):
                await ctx.send(
                    f'A member for the argument `{error.argument}` was not found.'
                )
            elif isinstance(error, commands.UserNotFound):
                await ctx.send(
                    f'A user for the argument `{error.argument}` was not found.'
                )
            elif isinstance(error, commands.ChannelNotFound):
                await ctx.send(
                    f'A channel for the argument `{error.argument}` was not found.'
                )
            elif isinstance(error, commands.RoleNotFound):
                await ctx.send(
                    f'A role for the argument `{error.argument}` was not found.'
                )
            elif isinstance(error, commands.EmojiNotFound):
                await ctx.send(
                    f'An emoji for the argument `{error.argument}` was not found.'
                )
            elif isinstance(error, commands.ChannelNotReadable):
                await ctx.send(
                    f'I do not have permission to read the channel `{error.argument}`'
                )
            elif isinstance(error, commands.PartialEmojiConversionFailure):
                await ctx.send(
                    f'The argument `{error.argument}` did not match the partial emoji format.'
                )
            elif isinstance(error, commands.BadInviteArgument):
                await ctx.send(
                    f'The invite that matched that argument was not valid or is expired.'
                )
            elif isinstance(error, commands.BadBoolArgument):
                await ctx.send(
                    f'The argument `{error.argument}` was not a valid True/False value.'
                )
            elif isinstance(error, commands.BadColourArgument):
                await ctx.send(
                    f'The argument `{error.argument}` was not a valid colour.')
            elif isinstance(error, BadLiteralArgument):
                await ctx.send(
                    f'The argument `{error.param.name}` must be one of {", ".join([f"`{arg}`" for arg in error.valid_arguments])}.'
                )
            return

        else:

            error_messages = {
                exceptions.ArgumentError:
                f'{error}',
                exceptions.ImageError:
                f'{error}',
                exceptions.VoiceError:
                f'{error}',
                NodeNotFound:
                f'There are no lavalink nodes available right now.',
                commands.TooManyArguments:
                f'You used too many arguments. Use `{self.bot.config.prefix}help {ctx.command}` for more information on what argument to use.',
                commands.UnexpectedQuoteError:
                f'There was an unexpected quote character in the arguments you passed.',
                commands.InvalidEndOfQuotedStringError:
                f'There was an unexpected space after a quote character in the arguments you passed.',
                commands.ExpectedClosingQuoteError:
                f'There is a missing quote character in the argument you passed.',
                commands.BadArgument:
                f'I was unable to convert an argument that you used. Use `{self.bot.config.prefix}help {ctx.command}` for more information on what '
                f'arguments to use.',
                commands.CheckFailure:
                f'{error}',
                commands.PrivateMessageOnly:
                f'The command `{ctx.command}` can only be used in private messages',
                commands.NoPrivateMessage:
                f'The command `{ctx.command}` can not be used in private messages.',
                commands.NotOwner:
                f'The command `{ctx.command}` is owner only.',
                commands.NSFWChannelRequired:
                f'The command `{ctx.command}` can only be run in a NSFW channel.',
                commands.DisabledCommand:
                f'The command `{ctx.command}` has been disabled.',
            }

            error_message = error_messages.get(type(error), None)
            if error_message is not None:
                await ctx.send(error_message)

            return

        await ctx.send(
            f'Something went wrong while executing that command. Please use `{self.bot.config.prefix}support` for more help or information.'
        )

        formatter = prettify_exceptions.DefaultFormatter()

        formatter.theme['_ansi_enabled'] = True
        print(
            f'\n{"".join(formatter.format_exception(type(error), error, error.__traceback__)).strip()}\n'
        )

        time = self.bot.utils.format_datetime(datetime=pendulum.now(tz='UTC'))
        guild = f'`Guild:` {ctx.guild} `{ctx.guild.id}`\n' if ctx.guild else ''
        info = f'Error in command `{ctx.command}`\n\n{guild}`Channel:` {ctx.channel} `{ctx.channel.id}`\n`Author:` {ctx.author} `{ctx.author.id}`\n`Time:` {time}'

        embed = discord.Embed(colour=ctx.colour,
                              description=f'{ctx.message.content}')
        embed.add_field(name='Info:', value=info)

        await self.bot.errors_webhook.send(
            embed=embed,
            username=f'{ctx.author}',
            avatar_url=str(
                ctx.author.avatar_url_as(format='gif' if ctx.author.
                                         is_avatar_animated() else 'png')))

        formatter.theme['_ansi_enabled'] = False
        traceback = "".join(
            formatter.format_exception(type(error), error,
                                       error.__traceback__)).strip()

        if len(traceback) > 2000:
            async with self.bot.session.post('https://mystb.in/documents',
                                             data=traceback) as response:
                response = await response.json()
            traceback = f'https://mystb.in/{response["key"]}.python'
        else:
            traceback = f'```\n{traceback}\n```'

        await self.bot.errors_webhook.send(
            content=f'{traceback}',
            username=f'{ctx.author}',
            avatar_url=str(
                ctx.author.avatar_url_as(format='gif' if ctx.author.
                                         is_avatar_animated() else 'png')))
コード例 #14
0
    async def on_command_error(self, ctx: context.Context, error):

        error = getattr(error, 'original', error)

        if isinstance(error, commands.CommandNotFound):
            return  # Ignore this exception

        elif isinstance(error, commands.CommandOnCooldown):

            if ctx.author.id in self.bot.owner_ids:
                ctx.command.reset_cooldown(ctx)
                return await ctx.command.reinvoke(ctx)

            cooldowns = {
                commands.BucketType.default: f'for the whole bot.',
                commands.BucketType.user: f'for you.',
                commands.BucketType.guild: f'for this server.',
                commands.BucketType.channel: f'for this channel.',
                commands.BucketType.member: f'cooldown for you.',
                commands.BucketType.category: f'for this channel category.',
                commands.BucketType.role: f'for your role.'
            }
            return await ctx.send(
                f'The command `{ctx.command}` is on cooldown {cooldowns[error.cooldown.type]} '
                f'You can retry in `{self.bot.utils.format_time(error.retry_after, friendly=True)}`'
            )

        elif isinstance(error, commands.MaxConcurrencyReached):
            cooldowns = {
                commands.BucketType.default: f'.',
                commands.BucketType.user: f' per user.',
                commands.BucketType.guild: f' per server.',
                commands.BucketType.channel: f' per channel.',
                commands.BucketType.member: f' per member.',
                commands.BucketType.category: f' per channel category.',
                commands.BucketType.role: f' per role.'
            }
            return await ctx.send(
                f'The command `{ctx.command}` is already being ran at its maximum of '
                f'{error.number} time(s){cooldowns[error.per]} Retry a bit later.'
            )

        ctx.command.reset_cooldown(ctx)

        if isinstance(error, commands.BotMissingPermissions):
            permissions = '\n'.join(
                [f'> {permission}' for permission in error.missing_perms])
            message = f'I am missing the following permissions required to run the command `{ctx.command}`.\n{permissions}'
            try:
                return await ctx.send(message)
            except discord.Forbidden:
                try:
                    return await ctx.author.send(message)
                except discord.Forbidden:
                    return

        elif isinstance(error, commands.MissingPermissions):
            permissions = '\n'.join(
                [f'> {permission}' for permission in error.missing_perms])
            return await ctx.send(
                f'You are missing the following permissions required to run the command `{ctx.command}`.\n{permissions}'
            )

        elif isinstance(error, commands.MissingRequiredArgument):
            return await ctx.send(
                f'You missed the `{error.param.name}` parameter for the command `{ctx.command}`. '
                f'Use `{self.bot.config.prefix}help {ctx.command}` for more information on what parameters to use.'
            )

        error_messages = {
            exceptions.ArgumentError:
            f'{error}',
            exceptions.ImageError:
            f'{error}',
            exceptions.VoiceError:
            f'{error}',
            commands.CheckFailure:
            f'{error}',
            NodeNotFound:
            f'There are no lavalink nodes available right now.',
            commands.TooManyArguments:
            f'You used too many parameters for the command `{ctx.command}`. Use `{self.bot.config.prefix}help {ctx.command}` for '
            f'more information on what parameters to use.',
            commands.BadArgument:
            f'I was unable to understand a parameter that you used for the command `{ctx.command}`. '
            f'Use `{self.bot.config.prefix}help {ctx.command}` for more information on what parameters to use.',
            commands.BadUnionArgument:
            f'I was unable to understand a parameter that you used for the command `{ctx.command}`. '
            f'Use `{self.bot.config.prefix}help {ctx.command}` for more information on what parameters to use.',
            commands.NoPrivateMessage:
            f'The command `{ctx.command}` can not be used in private messages.',
            commands.NotOwner:
            f'The command `{ctx.command}` is owner only.',
            commands.NSFWChannelRequired:
            f'The command `{ctx.command}` can only be ran in a NSFW channel.',
            commands.DisabledCommand:
            f'The command `{ctx.command}` has been disabled.',
            commands.ExpectedClosingQuoteError:
            f'You missed a closing quote in the parameters passed to the `{ctx.command}` command.',
            commands.UnexpectedQuoteError:
            f'There was an unexpected quote in the parameters passed to the `{ctx.command}` command.'
        }

        error_message = error_messages.get(type(error), None)
        if error_message is not None:
            return await ctx.send(error_message)

        await ctx.send(
            f'Something went wrong while executing that command. Please use `{self.bot.config.prefix}support` for more help or information.'
        )

        formatter = prettify_exceptions.DefaultFormatter()

        formatter.theme['_ansi_enabled'] = True
        print(
            f'\n{"".join(formatter.format_exception(type(error), error, error.__traceback__)).strip()}'
        )

        if not self.bot.error_channel:
            return

        guild = f'`Guild:` {ctx.guild} ({ctx.guild.id})' if ctx.guild else ''
        channel = f'`Channel:` {ctx.channel} ({ctx.channel.id})'
        author = f'`Author:` {ctx.author} ({ctx.author.id})'
        time = f'`Time:` {datetime.strftime(ctx.message.created_at, "%A %d %B %Y at %H:%M:%S")}'
        info = f'`Message content:` {ctx.message.content}\n{guild}\n{channel}\n{author}\n{time}'

        embed = discord.Embed(colour=ctx.colour,
                              description=f'Error in command `{ctx.command}`')
        embed.set_author(
            name=ctx.author,
            icon_url=str(
                ctx.author.avatar_url_as(
                    format='gif'
                    if ctx.author.is_avatar_animated() is True else 'png')))
        embed.add_field(name='Info:', value=info)
        await self.bot.error_channel.send(embed=embed)

        formatter.theme['_ansi_enabled'] = False
        traceback = "".join(
            formatter.format_exception(type(error), error,
                                       error.__traceback__)).strip()

        if len(traceback) < 2000:
            return await self.bot.error_channel.send(f'```{traceback}```')

        [
            await self.bot.error_channel.send(f'```{msg}```') for msg in
            [traceback[i:i + 1900] for i in range(0, len(traceback), 1900)]
        ]