Exemplo n.º 1
0
 async def on_command_completion(self, ctx: commands.Context):
     """Runs when any command is completed succesfully"""
     # prevent double invocation for subcommands
     if ctx.invoked_subcommand is None:
         command_logger.info(log.log_command(ctx))
         if ctx.guild is not None:
             await queries.save_command_usage(ctx)
Exemplo n.º 2
0
    async def bang(self, ctx: commands.Context):
        """
        DuckDuckGo bangs https://duckduckgo.com/bang

        Usage:
            >!<bang> <query...>

        Example:
            >!w horses
        """
        if not hasattr(ctx, "iscallback"):
            return await ctx.send_help(ctx.command)

        try:
            await ctx.trigger_typing()
        except discord.errors.Forbidden:
            pass

        command_logger.info(log.log_command(ctx))
        await queries.save_command_usage(ctx)
        try:
            bang, args = ctx.message.content[len(ctx.prefix) + 1:].split(
                " ", 1)
            if len(bang) != 0:
                await self.resolve_bang(ctx, bang, args)
        except ValueError:
            await ctx.send("Please provide a query to search")
Exemplo n.º 3
0
    async def on_command_error(self, ctx, error):
        """The event triggered when an error is raised while invoking a command."""

        # ignore if command has it's own error handler
        if hasattr(ctx.command, "on_error"):
            return

        # extract the original error from the CommandError wrapper
        error = getattr(error, "original", error)

        # silently ignored expections
        if isinstance(error, (commands.CommandNotFound)):
            return

        if isinstance(error, commands.DisabledCommand):
            command_logger.warning(log.log_command(ctx, extra=error))
            return await self.send(
                ctx,
                "info",
                "This command is temporarily disabled, sorry for the inconvenience!",
            )

        if isinstance(error, commands.MissingRequiredArgument):
            return await util.send_command_help(ctx)

        if isinstance(error, exceptions.Info):
            command_logger.info(log.log_command(ctx, extra=error))
            return await self.send(ctx, "info", str(error), error.kwargs)
        elif isinstance(error, exceptions.Warning):
            command_logger.warning(log.log_command(ctx, extra=error))
            return await self.send(ctx, "warning", str(error), error.kwargs)
        else:
            command_logger.error(
                f'{type(error).__name__:25} > {ctx.guild} : {ctx.author} "{ctx.message.content}" > {error}'
            )

        if isinstance(error, exceptions.Error):
            return await self.send(ctx, "error", str(error), error.kwargs)

        if isinstance(error, commands.NoPrivateMessage):
            try:
                await self.send(
                    ctx.author,
                    "info",
                    "This command cannot be used in DM",
                )
            except (discord.HTTPException, discord.errors.Forbidden):
                pass

        elif isinstance(error, commands.MissingPermissions):
            perms = ", ".join(f"**{x}**" for x in error.missing_perms)
            await self.send(
                ctx, "warning",
                f"You require {perms} permission to use this command!")

        elif isinstance(error, commands.BotMissingPermissions):
            perms = ", ".join(f"**{x}**" for x in error.missing_perms)
            await self.send(
                ctx, "warning",
                f"Cannot execute command! Bot is missing permission {perms}")

        elif isinstance(error, commands.CommandOnCooldown):
            if await queries.is_donator(ctx, ctx.author, 2):
                try:
                    await ctx.reinvoke()
                    return
                except Exception as e:
                    await self.on_command_error(ctx, e)
            else:
                await self.send(
                    ctx,
                    "cooldown",
                    f"You are on cooldown. Please wait `{error.retry_after:.0f} seconds`",
                )

        elif isinstance(error, commands.errors.MaxConcurrencyReached):
            await ctx.send("Stop spamming! >:(")

        elif isinstance(error, commands.NoPrivateMessage):
            await self.send(
                ctx, "info",
                "You cannot use this command in private messages!")

        elif isinstance(error, util.PatronCheckFailure):
            await self.send(
                ctx,
                "error",
                "Support me on patreon to use this command! <https://patreon.com/joinemm>",
            )

        elif isinstance(error, (commands.NotOwner, commands.CheckFailure)):
            await self.send(
                ctx, "error",
                "Sorry, you are not authorized to use this command!")

        elif isinstance(error, exceptions.Blacklist):
            delete = await self.bot.db.execute(
                "SELECT delete_blacklisted_usage FROM guild_settings WHERE guild_id = %s",
                ctx.guild.id,
                one_value=True,
            )
            await self.send(ctx,
                            "error",
                            error.message,
                            delete_after=(5 if delete else None))
            if delete:
                await asyncio.sleep(5)
                await ctx.message.delete()

        elif isinstance(
                error,
            (commands.BadArgument, flags._parser.ArgumentParsingError)):
            await self.send(ctx, "warning", str(error), help_footer=True)

        elif isinstance(error, discord.errors.Forbidden):
            try:
                await self.send(ctx, "error", str(error), codeblock=True)
            except discord.errors.Forbidden:
                try:
                    await ctx.message.add_reaction("🙊")
                except discord.errors.Forbidden:
                    await self.log_and_traceback(ctx, error)

        elif isinstance(error, exceptions.LastFMError):
            if error.error_code == 8:
                message = "There was a problem connecting to LastFM servers. LastFM might be down. Try again later."
            elif error.error_code == 17:
                message = "Unable to get listening information. Please check you LastFM privacy settings."
            elif error.error_code == 29:
                message = "LastFM rate limit exceeded. Please try again in 60 seconds."
            else:
                message = error.display()

            await self.send(ctx, "lastfm", message)

        else:
            await self.log_and_traceback(ctx, error)