Python discord.ext.commands.NoPrivateMessage() Examples

The following are 30 code examples of discord.ext.commands.NoPrivateMessage(). 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: meta.py    From discordbot.py with MIT License 7 votes vote down vote up
def on_command_error(self, error, ctx):
        ignored = (commands.NoPrivateMessage, commands.DisabledCommand, commands.CheckFailure,
                   commands.CommandNotFound, commands.UserInputError, discord.HTTPException)
        error = getattr(error, 'original', error)

        if isinstance(error, ignored):
            return

        if ctx.message.server:
            fmt = 'Channel: {0} (ID: {0.id})\nGuild: {1} (ID: {1.id})'
        else:
            fmt = 'Channel: {0} (ID: {0.id})'

        exc = traceback.format_exception(type(error), error, error.__traceback__, chain=False)
        description = '```py\n%s\n```' % ''.join(exc)
        time = datetime.datetime.utcnow()

        name = ctx.command.qualified_name
        author = '{0} (ID: {0.id})'.format(ctx.message.author)
        location = fmt.format(ctx.message.channel, ctx.message.server)

        message = '{0} at {1}: Called by: {2} in {3}. More info: {4}'.format(name, time, author, location, description)

        self.bot.logs['discord'].critical(message) 
Example #2
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 #3
Source File: main.py    From discord_bot with MIT License 6 votes vote down vote up
def on_command_error(error, ctx):
    if isinstance(error, commands.NoPrivateMessage):
        await ctx.author.send('This command cannot be used in private messages.')
    elif isinstance(error, commands.DisabledCommand):
        await ctx.channel.send(':x: Dieser Command wurde deaktiviert')
    elif isinstance(error, commands.CommandInvokeError):
        if bot.dev:
            raise error
        else:
            embed = discord.Embed(title=':x: Command Error', colour=0x992d22) #Dark Red
            embed.add_field(name='Error', value=error)
            embed.add_field(name='Guild', value=ctx.guild)
            embed.add_field(name='Channel', value=ctx.channel)
            embed.add_field(name='User', value=ctx.author)
            embed.add_field(name='Message', value=ctx.message.clean_content)
            embed.timestamp = datetime.datetime.utcnow()
            try:
                await bot.AppInfo.owner.send(embed=embed)
            except:
                pass 
Example #4
Source File: checks.py    From NabBot with Apache License 2.0 6 votes vote down vote up
def has_guild_permissions(**perms):
    """Command can only be used if the user has the provided guild permissions."""
    def predicate(ctx):
        if ctx.guild is None:
            raise commands.NoPrivateMessage("This command cannot be used in private messages.")

        permissions = ctx.author.guild_permissions

        missing = [perm for perm, value in perms.items() if getattr(permissions, perm, None) != value]

        if not missing:
            return True

        raise commands.MissingPermissions(missing)

    return commands.check(predicate)
# endregion


# region Auxiliary functions (Not valid decorators) 
Example #5
Source File: checks.py    From NabBot with Apache License 2.0 5 votes vote down vote up
def tracking_world_only():
    """Command can only be used if the current server is tracking a world.

    This check implies that the command can only be used in server channels
    """
    def predicate(ctx):
        if ctx.guild is None:
            raise commands.NoPrivateMessage("This command cannot be used in private messages.")
        if not ctx.bot.tracked_worlds.get(ctx.guild.id):
            raise errors.NotTracking("This server is not tracking any worlds.")
        return True
    return commands.check(predicate) 
Example #6
Source File: security.py    From bot with MIT License 5 votes vote down vote up
def check_on_guild(self, ctx: Context) -> bool:
        """Check if the context is in a guild."""
        if ctx.guild is None:
            raise NoPrivateMessage("This command cannot be used in private messages.")
        return True 
Example #7
Source File: discordbot.py    From discordbot.py with MIT License 5 votes vote down vote up
def on_command_error(self, error, ctx):
        if isinstance(error, commands.NoPrivateMessage):
            await self.send_message(ctx.message.author, 'This command cannot be used in private messages.')
        elif isinstance(error, commands.DisabledCommand):
            await self.send_message(ctx.message.author, 'Sorry. This command is disabled and cannot be used.')
        elif isinstance(error, commands.CommandInvokeError):
            print('In {0.command.qualified_name}:'.format(ctx), file=sys.stderr)
            traceback.print_tb(error.original.__traceback__)
            print('{0.__class__.__name__}: {0}'.format(error.original), file=sys.stderr) 
Example #8
Source File: initTracker.py    From avrae with GNU General Public License v3.0 5 votes vote down vote up
def cog_check(self, ctx):
        if ctx.guild is None:
            raise NoPrivateMessage()
        return True 
Example #9
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 #10
Source File: playlist.py    From Wavelink with MIT License 5 votes vote down vote up
def cog_command_error(self, ctx, error):
        """A local error handler for all errors arising from commands in this cog."""
        if isinstance(error, commands.NoPrivateMessage):
            try:
                return await ctx.send('This command can not be used in Private Messages.')
            except discord.HTTPException:
                pass

        print('Ignoring exception in command {}:'.format(ctx.command), file=sys.stderr)
        traceback.print_exception(type(error), error, error.__traceback__, file=sys.stderr) 
Example #11
Source File: playlist.py    From Wavelink with MIT License 5 votes vote down vote up
def cog_check(self, ctx):
        """A local check which applies to all commands in this cog."""
        if not ctx.guild:
            raise commands.NoPrivateMessage
        return True 
Example #12
Source File: pollmaster.py    From pollmaster with MIT License 5 votes vote down vote up
def on_command_error(ctx, e):

    if hasattr(ctx.cog, 'qualified_name') and ctx.cog.qualified_name == "Admin":
        # Admin cog handles the errors locally
        return

    if SETTINGS.log_errors:
        ignored_exceptions = (
            commands.MissingRequiredArgument,
            commands.CommandNotFound,
            commands.DisabledCommand,
            commands.BadArgument,
            commands.NoPrivateMessage,
            commands.CheckFailure,
            commands.CommandOnCooldown,
            commands.MissingPermissions,
            discord.errors.Forbidden,
        )

        if isinstance(e, ignored_exceptions):
            # log warnings
            # logger.warning(f'{type(e).__name__}: {e}\n{"".join(traceback.format_tb(e.__traceback__))}')
            return

        # log error
        logger.error(f'{type(e).__name__}: {e}\n{"".join(traceback.format_tb(e.__traceback__))}')
        traceback.print_exception(type(e), e, e.__traceback__, file=sys.stderr)

        if SETTINGS.msg_errors:
            # send discord message for unexpected errors
            e = discord.Embed(
                title=f"Error With command: {ctx.command.name}",
                description=f"```py\n{type(e).__name__}: {str(e)}\n```\n\nContent:{ctx.message.content}"
                            f"\n\tServer: {ctx.message.server}\n\tChannel: <#{ctx.message.channel}>"
                            f"\n\tAuthor: <@{ctx.message.author}>",
                timestamp=ctx.message.timestamp
            )
            await ctx.send(bot.owner, embed=e)

        # if SETTINGS.mode == 'development':
        raise e 
Example #13
Source File: music.py    From DJ5n4k3 with MIT License 5 votes vote down vote up
def __error(self, ctx, error):
        """A local error handler for all errors arising from commands in this cog."""
        if isinstance(error, commands.NoPrivateMessage):
            try:
                return await ctx.send(':notes: This command can not be used in Private Messages.')
            except discord.HTTPException:
                pass
        elif isinstance(error, InvalidVoiceChannel):
            await ctx.send(":notes: Please join voice channel or specify one with command!")

        print('Ignoring exception in command {}:'.format(ctx.command), file=sys.stderr)
        traceback.print_exception(type(error), error, error.__traceback__, file=sys.stderr) 
Example #14
Source File: music.py    From DJ5n4k3 with MIT License 5 votes vote down vote up
def __local_check(self, ctx):
        """A local check which applies to all commands in this cog."""
        if not ctx.guild:
            raise commands.NoPrivateMessage
        return True 
Example #15
Source File: admin.py    From NabBot with Apache License 2.0 5 votes vote down vote up
def setting_command():
    """Local check that provides a custom message when used on PMs."""
    async def predicate(ctx):
        if ctx.guild is None:
            raise commands.NoPrivateMessage("Settings can't be modified on private messages.")
        return True
    return commands.check(predicate) 
Example #16
Source File: converter.py    From NabBot with Apache License 2.0 5 votes vote down vote up
def convert(self, ctx, argument) -> discord.Role:
        argument = argument.replace("\"", "")
        guild = ctx.guild
        if not guild:
            raise commands.NoPrivateMessage()

        match = self._get_id_match(argument) or re.match(r'<@&([0-9]+)>$', argument)
        if match:
            result = guild.get_role(int(match.group(1)))
        else:
            result = discord.utils.find(lambda r: r.name.lower() == argument.lower(), guild.roles)
        if result is None:
            raise commands.BadArgument('Role "{}" not found.'.format(argument))
        return result 
Example #17
Source File: checks.py    From NabBot with Apache License 2.0 5 votes vote down vote up
def check_guild_permissions(ctx, perms, *, check=all):
    """Checks if the user has the specified permissions in the current guild."""
    if not ctx.guild:
        raise commands.NoPrivateMessage("This command cannot be used in private messages.")

    if await ctx.bot.is_owner(ctx.author):
        return True

    permissions = ctx.author.guild_permissions
    return check(getattr(permissions, name, None) == value for name, value in perms.items()) 
Example #18
Source File: salary.py    From RPGBot with GNU General Public License v3.0 5 votes vote down vote up
def cog_check(self, ctx):
        def predicate(ctx):
            if ctx.guild is None:
                raise commands.NoPrivateMessage()
            return True

        return commands.check(predicate(ctx)) 
Example #19
Source File: user.py    From RPGBot with GNU General Public License v3.0 5 votes vote down vote up
def cog_check(self, ctx):
        def predicate(ctx):
            if ctx.guild is None:
                raise commands.NoPrivateMessage()
            return True

        return commands.check(predicate(ctx)) 
Example #20
Source File: checks.py    From NabBot with Apache License 2.0 5 votes vote down vote up
def channel_mod_only():
    """Command can only be used by users with manage channel permissions."""
    async def predicate(ctx):
        if ctx.guild is None:
            raise commands.NoPrivateMessage("This command cannot be used in private messages.")
        res = await is_owner(ctx) or (await check_permissions(ctx, {'manage_channels': True}) and
                                      ctx.guild is not None)
        if not res:
            raise errors.UnathorizedUser("You need Manage Channel permissions to use this command.")
        return True
    return commands.check(predicate) 
Example #21
Source File: test_security.py    From bot with MIT License 5 votes vote down vote up
def test_check_on_guild_raises_when_outside_of_guild(self):
        """When invoked outside of a guild, `check_on_guild` should cause an error."""
        self.ctx.guild = None

        with self.assertRaises(NoPrivateMessage, msg="This command cannot be used in private messages."):
            self.cog.check_on_guild(self.ctx) 
Example #22
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 #23
Source File: selfbot.py    From Discord-SelfBot with MIT License 5 votes vote down vote up
def on_command_error(ctx, error):
    if isinstance(error, commands.NoPrivateMessage):
        await edit(ctx, content='\N{HEAVY EXCLAMATION MARK SYMBOL} Only usable on Servers', ttl=5)
    elif isinstance(error, commands.CheckFailure):
        await edit(ctx, content='\N{HEAVY EXCLAMATION MARK SYMBOL} No Permissions to use this command', ttl=5)
    elif isinstance(error, commands.CommandInvokeError):
        log.error('In {0.command.qualified_name}:\n{1}'.format(ctx, ''.join(traceback.format_list(traceback.extract_tb(error.original.__traceback__)))))
        log.error('{0.__class__.__name__}: {0}'.format(error.original))


# Increase use count and log to logger 
Example #24
Source File: bot.py    From RubyRoseBot with Mozilla Public License 2.0 5 votes vote down vote up
def on_command_error(ctx, error):
    if isinstance(error, commands.CommandNotFound):
        return
    if isinstance(error, commands.DisabledCommand):
        await ctx.send(Language.get("bot.errors.disabled_command", ctx))
        return
    if isinstance(error, checks.owner_only):
        await ctx.send(Language.get("bot.errors.owner_only", ctx))
        return
    if isinstance(error, checks.dev_only):
        await ctx.send(Language.get("bot.errors.dev_only", ctx))
        return
    if isinstance(error, checks.support_only):
        await ctx.send(Language.get("bot.errors.support_only", ctx))
        return
    if isinstance(error, checks.not_nsfw_channel):
        await ctx.send(Language.get("bot.errors.not_nsfw_channel", ctx))
        return
    if isinstance(error, checks.not_guild_owner):
        await ctx.send(Language.get("bot.errors.not_guild_owner", ctx))
        return
    if isinstance(error, checks.no_permission):
        await ctx.send(Language.get("bot.errors.no_permission", ctx))
        return
    if isinstance(error, commands.NoPrivateMessage):
        await ctx.send(Language.get("bot.errors.no_private_message", ctx))
        return
    if isinstance(ctx.channel, discord.DMChannel):
        await ctx.send(Language.get("bot.errors.command_error_dm_channel", ctx))
        return

    #In case the bot failed to send a message to the channel, the try except pass statement is to prevent another error
    try:
        await ctx.send(Language.get("bot.errors.command_error", ctx).format(error))
    except:
        pass
    log.error("An error occured while executing the {} command: {}".format(ctx.command.qualified_name, error)) 
Example #25
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 #26
Source File: characters.py    From RPGBot with GNU General Public License v3.0 5 votes vote down vote up
def cog_check(self, ctx):
        def predicate(ctx):
            if ctx.guild is None:
                raise commands.NoPrivateMessage()
            return True

        return commands.check(predicate(ctx)) 
Example #27
Source File: map.py    From RPGBot with GNU General Public License v3.0 5 votes vote down vote up
def cog_check(self, ctx):
        def predicate(ctx):
            if ctx.guild is None:
                raise commands.NoPrivateMessage()
            return True

        return commands.check(predicate(ctx)) 
Example #28
Source File: team.py    From RPGBot with GNU General Public License v3.0 5 votes vote down vote up
def cog_check(self, ctx):
        def predicate(ctx):
            if ctx.guild is None:
                raise commands.NoPrivateMessage()
            return True

        return commands.check(predicate(ctx)) 
Example #29
Source File: settings.py    From RPGBot with GNU General Public License v3.0 5 votes vote down vote up
def cog_check(self, ctx):
        def predicate(ctx):
            if ctx.guild is None:
                raise commands.NoPrivateMessage()
            return True

        return commands.check(predicate(ctx)) 
Example #30
Source File: inventory.py    From RPGBot with GNU General Public License v3.0 5 votes vote down vote up
def cog_check(self, ctx):
        def predicate(ctx):
            if ctx.guild is None:
                raise commands.NoPrivateMessage()
            return True

        return commands.check(predicate(ctx))