Python discord.ext.commands.NotOwner() Examples

The following are 14 code examples of discord.ext.commands.NotOwner(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module discord.ext.commands , or try the search function .
Example #1
Source File: bot.py    From rewrite with GNU General Public License v3.0 6 votes vote down vote up
def on_command_error(self, ctx, exception):
        exc_class = exception.__class__
        if exc_class in (commands.CommandNotFound, commands.NotOwner):
            return

        exc_table = {
            commands.MissingRequiredArgument: f"{WARNING} The required arguments are missing for this command!",
            commands.NoPrivateMessage: f"{WARNING} This command cannot be used in PM's!",
            commands.BadArgument: f"{WARNING} A bad argument was passed, please check if your arguments are correct!",
            IllegalAction: f"{WARNING} A node error has occurred: `{getattr(exception, 'msg', None)}`",
            CustomCheckFailure: getattr(exception, "msg", None) or "None"
        }

        if exc_class in exc_table.keys():
            await ctx.send(exc_table[exc_class])
        else:
            await super().on_command_error(ctx, exception) 
Example #2
Source File: core.py    From spirit with MIT License 5 votes vote down vote up
def on_command_error(self, ctx, error):
        """Command error handler"""
        manager = MessageManager(ctx)

        if isinstance(error, commands.CommandNotFound):
            pass

        elif isinstance(error, commands.MissingRequiredArgument):
            pass

        elif isinstance(error, commands.NotOwner):
            pass

        elif isinstance(error, commands.NoPrivateMessage):
            await manager.send_message("You can't use that command in a private message")

        elif isinstance(error, commands.CheckFailure):
            await manager.send_message("You don't have the required permissions to do that")

        elif isinstance(error, commands.CommandOnCooldown):
            await manager.send_message(error)

        # Non Discord.py errors
        elif isinstance(error, commands.CommandInvokeError):
            if isinstance(error.original, discord.errors.Forbidden):
                pass
            elif isinstance(error.original, asyncio.TimeoutError):
                await manager.send_private_message("I'm not sure where you went. We can try this again later.")
            else:
                raise error

        else:
            raise error

        await manager.clean_messages() 
Example #3
Source File: checks.py    From modmail with GNU Affero General Public License v3.0 5 votes vote down vote up
def is_owner():
    def predicate(ctx):
        if ctx.author.id not in ctx.bot.config.owners:
            raise commands.NotOwner()
        else:
            return True

    return commands.check(predicate) 
Example #4
Source File: checks.py    From modmail with GNU Affero General Public License v3.0 5 votes vote down vote up
def is_admin():
    def predicate(ctx):
        if ctx.author.id not in ctx.bot.config.admins and ctx.author.id not in ctx.bot.config.owners:
            raise commands.NotOwner()
        else:
            return True

    return commands.check(predicate) 
Example #5
Source File: __init__.py    From EmoteCollector with GNU Affero General Public License v3.0 5 votes vote down vote up
def on_command_error(self, context, error):
		if isinstance(error, commands.NoPrivateMessage):
			await context.author.send(_('This command cannot be used in private messages.'))
		elif isinstance(error, commands.DisabledCommand):
			message = _('Sorry. This command is disabled and cannot be used.')
			try:
				await context.author.send(message)
			except discord.Forbidden:
				await context.send(message)
		elif isinstance(error, commands.NotOwner):
			logger.error('%s tried to run %s but is not the owner', context.author, context.command.name)
			with contextlib.suppress(discord.HTTPException):
				await context.try_add_reaction(utils.SUCCESS_EMOJIS[False])
		elif isinstance(error, (commands.UserInputError, commands.CheckFailure)):
			await context.send(error)
		elif (
			isinstance(error, commands.CommandInvokeError)
			# abort if it's overridden
			and
				getattr(
					type(context.cog),
					'cog_command_error',
					# treat ones with no cog (e.g. eval'd ones) as being in a cog that did not override
					commands.Cog.cog_command_error)
				is commands.Cog.cog_command_error
		):
			if not isinstance(error.original, discord.HTTPException):
				logger.error('"%s" caused an exception', context.message.content)
				logger.error(''.join(traceback.format_tb(error.original.__traceback__)))
				# pylint: disable=logging-format-interpolation
				logger.error('{0.__class__.__name__}: {0}'.format(error.original))

				await context.send(_('An internal error occurred while trying to run that command.'))
			elif isinstance(error.original, discord.Forbidden):
				await context.send(_("I'm missing permissions to perform that action."))

	### Utility functions 
Example #6
Source File: cog_base.py    From jishaku with MIT License 5 votes vote down vote up
def cog_check(self, ctx: commands.Context):  # pylint: disable=invalid-overridden-method
        """
        Local check, makes all commands in this cog owner-only
        """

        if not await ctx.bot.is_owner(ctx.author):
            raise commands.NotOwner("You must own this bot to use Jishaku.")
        return True

    # pylint: disable=no-member
    # Meta commands 
Example #7
Source File: test_cog.py    From jishaku with MIT License 5 votes vote down vote up
def test_cog_check(bot):
    cog = bot.get_cog("Jishaku")

    with utils.mock_ctx() as ctx:
        with utils.mock_coro(ctx.bot, 'is_owner'):
            ctx.bot.is_owner.coro.return_value = True

            assert await cog.cog_check(ctx)

            ctx.bot.is_owner.coro.return_value = False

            with pytest.raises(commands.NotOwner):
                await cog.cog_check(ctx) 
Example #8
Source File: bot.py    From pollmaster with MIT License 5 votes vote down vote up
def on_command_error(self, ctx, exc):
        if not isinstance(exc, (commands.CommandNotFound, commands.NotOwner)):
            self.log.critical(''.join(traceback.format_exception(type(exc), exc, exc.__traceback__)))
            # await ctx.send("check logs") 
Example #9
Source File: development.py    From Dozer with GNU General Public License v3.0 5 votes vote down vote up
def cog_check(self, ctx):  # All of this cog is only available to devs
        if ctx.author.id not in ctx.bot.config['developers']:
            raise NotOwner('you are not a developer!')
        return True 
Example #10
Source File: maintenance.py    From Dozer with GNU General Public License v3.0 5 votes vote down vote up
def cog_check(self, ctx):  # All of this cog is only available to devs
        if ctx.author.id not in ctx.bot.config['developers']:
            raise NotOwner('you are not a developer!')
        return True 
Example #11
Source File: _utils.py    From Dozer with GNU General Public License v3.0 5 votes vote down vote up
def dev_check():
    """Function decorator to check that the calling user is a developer"""
    async def predicate(ctx):
        if ctx.author.id not in ctx.bot.config['developers']:
            raise commands.NotOwner('you are not a developer!')
        return True
    return commands.check(predicate) 
Example #12
Source File: bot.py    From Dozer with GNU General Public License v3.0 5 votes vote down vote up
def on_command_error(self, context, exception):
        if isinstance(exception, commands.NoPrivateMessage):
            await context.send('{}, This command cannot be used in DMs.'.format(context.author.mention))
        elif isinstance(exception, commands.UserInputError):
            await context.send('{}, {}'.format(context.author.mention, self.format_error(context, exception)))
        elif isinstance(exception, commands.NotOwner):
            await context.send('{}, {}'.format(context.author.mention, exception.args[0]))
        elif isinstance(exception, commands.MissingPermissions):
            permission_names = [name.replace('guild', 'server').replace('_', ' ').title() for name in exception.missing_perms]
            await context.send('{}, you need {} permissions to run this command!'.format(
                context.author.mention, utils.pretty_concat(permission_names)))
        elif isinstance(exception, commands.BotMissingPermissions):
            permission_names = [name.replace('guild', 'server').replace('_', ' ').title() for name in exception.missing_perms]
            await context.send('{}, I need {} permissions to run this command!'.format(
                context.author.mention, utils.pretty_concat(permission_names)))
        elif isinstance(exception, commands.CommandOnCooldown):
            await context.send(
                '{}, That command is on cooldown! Try again in {:.2f}s!'.format(context.author.mention, exception.retry_after))
        elif isinstance(exception, (commands.CommandNotFound, InvalidContext)):
            pass  # Silent ignore
        else:
            await context.send('```\n%s\n```' % ''.join(traceback.format_exception_only(type(exception), exception)).strip())
            if isinstance(context.channel, discord.TextChannel):
                DOZER_LOGGER.error('Error in command <%d> (%d.name!r(%d.id) %d(%d.id) %d(%d.id) %d)',
                                   context.command, context.guild, context.guild, context.channel, context.channel,
                                   context.author, context.author, context.message.content)
            else:
                DOZER_LOGGER.error('Error in command <%d> (DM %d(%d.id) %d)', context.command, context.channel.recipient,
                                   context.channel.recipient, context.message.content)
            DOZER_LOGGER.error(''.join(traceback.format_exception(type(exception), exception, exception.__traceback__))) 
Example #13
Source File: error_handler.py    From RTFMbot with Mozilla Public License 2.0 4 votes vote down vote up
def _on_command_error(self, ctx, error, bypass = False):
        name, content = None, None
        raised = False

        if hasattr(ctx.command, 'on_error') or (ctx.command and hasattr(ctx.cog, f'_{ctx.command.cog_name}__error')) and not bypass:
            # Do nothing if the command/cog has its own error handler and the bypass is False
            return
        if isinstance(error, commands.CommandInvokeError) and hasattr(error, 'original'):
            error = error.original
            raised = True
        if isinstance(error, commands.CommandNotFound) or isinstance(error, commands.NotOwner):
            return
        elif isinstance(error, commands.MissingRequiredArgument):
            name = "SyntaxError"
            content = f"Command `{ctx.command.name}` missing 1 required argument: `{error.param.name}`"
        elif isinstance(error, commands.BadArgument):
            name = "TypeError"
            content = str(error.args[0])
        elif isinstance(error, commands.CommandOnCooldown):
            name = "TimeoutError"
            content = f"Command on cooldown. Retry in `{format(error.retry_after, '.2f')}s`."
        elif isinstance(error, commands.CheckFailure):
            name = "PermissionError"
            content = "Escalation failed: you are not in the sudoers file.\nThis incident will be reported"
        elif isinstance(error, discord.Forbidden) or isinstance(error, discord.HTTPException):
            # We may not be able to send an embed or even send a message at this point
            bot_member = ctx.guild.get_member(self.bot.user.id)
            can_talk = ctx.channel.permissions_for(bot_member).send_messages
            if can_talk:
                return await ctx.send(f"```An error occurred while responding:\n{error.code} - {error.text}\n\nI need following permissions:\n\nEmbed links\nAttach files\nAdd reactions```")
        elif isinstance(error, UnicodeError):
            name = "UnicodeError"
            content = "The bot failed to decode your input or a command output. Make sure you only use UTF-8"

        if name is not None:
            emb = discord.Embed(title=name, description=content, colour=self.bot.config['RED'])
            await ctx.send(embed=emb)
        elif raised:
            print(f'{time.strftime("%d/%m/%y %H:%M:%S")} | {ctx.command.qualified_name}', file=sys.stderr)
            traceback.print_tb(error.__traceback__)
            print(f'{error.__class__.__name__}: {error}', file=sys.stderr, end='\n\n')
        else:
            print(traceback.format_exc()) 
Example #14
Source File: handler.py    From DJ5n4k3 with MIT License 4 votes vote down vote up
def on_command_error(self, ctx, error):
        if hasattr(ctx.command, 'on_error'):
            return
        
        ignored = (commands.MissingRequiredArgument, commands.BadArgument, commands.NoPrivateMessage, commands.CheckFailure, commands.CommandNotFound, commands.DisabledCommand, commands.CommandInvokeError, commands.TooManyArguments, commands.UserInputError, commands.CommandOnCooldown, commands.NotOwner, commands.MissingPermissions, commands.BotMissingPermissions)   
        error = getattr(error, 'original', error)
        

        if isinstance(error, commands.CommandNotFound):
            return

        elif isinstance(error, commands.BadArgument):
            await ctx.send(embed=discord.Embed(color=self.bot.color).set_footer(text=f"Seems like {error}.", icon_url=ctx.author.avatar_url))

        elif isinstance(error, commands.MissingRequiredArgument):
            await ctx.send(embed=discord.Embed(color=self.bot.color).set_footer(text=f"Seems like {error}.", icon_url=ctx.author.avatar_url))

        elif isinstance(error, commands.NoPrivateMessage):
            return

        elif isinstance(error, commands.CheckFailure):
            await ctx.send(embed=discord.Embed(color=self.bot.color).set_footer(text=f"Seems like this command is thought for other users. You can't use it.", icon_url=ctx.author.avatar_url))

        elif isinstance(error, commands.DisabledCommand):
            await ctx.send(embed=discord.Embed(color=self.bot.color).set_footer(text=f"Seems like this command in disabled.", icon_url=ctx.author.avatar_url))

        elif isinstance(error, commands.CommandInvokeError):
            await ctx.send(embed=discord.Embed(color=self.bot.color).set_footer(text=f"Seems like something went wrong. Report this issue to the developer.", icon_url=ctx.author.avatar_url))

        elif isinstance(error, commands.TooManyArguments):
            await ctx.send(embed=discord.Embed(color=self.bot.color).set_footer(text=f"Seems like you gave too many arguments.", icon_url=ctx.author.avatar_url))

        elif isinstance(error, commands.UserInputError):
            await ctx.send(embed=discord.Embed(color=self.bot.color).set_footer(text=f"Seems like you did something wrong.", icon_url=ctx.author.avatar_url))

        elif isinstance(error, commands.CommandOnCooldown):
            await ctx.send(embed=discord.Embed(color=self.bot.color).set_footer(text=f"Seems like {error}.", icon_url=ctx.author.avatar_url))

        elif isinstance(error, commands.NotOwner):
            await ctx.send(embed=discord.Embed(color=self.bot.color).set_footer(text=f"Seems like you do not own this bot.", icon_url=ctx.author.avatar_url))

        elif isinstance(error, commands.MissingPermissions):
            await ctx.send(embed=discord.Embed(color=self.bot.color).set_footer(text=f"Seems like {error}.", icon_url=ctx.author.avatar_url))

        elif isinstance(error, commands.BotMissingPermissions):
            await ctx.send(embed=discord.Embed(color=self.bot.color).set_footer(text=f"Seems like {error}.", icon_url=ctx.author.avatar_url))