当前位置: 首页>>代码示例>>Python>>正文


Python commands.NoPrivateMessage方法代码示例

本文整理汇总了Python中discord.ext.commands.NoPrivateMessage方法的典型用法代码示例。如果您正苦于以下问题:Python commands.NoPrivateMessage方法的具体用法?Python commands.NoPrivateMessage怎么用?Python commands.NoPrivateMessage使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在discord.ext.commands的用法示例。


在下文中一共展示了commands.NoPrivateMessage方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: on_command_error

# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import NoPrivateMessage [as 别名]
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) 
开发者ID:initzx,项目名称:rewrite,代码行数:19,代码来源:bot.py

示例2: has_guild_permissions

# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import NoPrivateMessage [as 别名]
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) 
开发者ID:NabDev,项目名称:NabBot,代码行数:22,代码来源:checks.py

示例3: on_command_error

# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import NoPrivateMessage [as 别名]
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) 
开发者ID:rauenzi,项目名称:discordbot.py,代码行数:26,代码来源:meta.py

示例4: on_command_error

# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import NoPrivateMessage [as 别名]
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 
开发者ID:Der-Eddy,项目名称:discord_bot,代码行数:22,代码来源:main.py

示例5: test_check_on_guild_raises_when_outside_of_guild

# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import NoPrivateMessage [as 别名]
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) 
开发者ID:python-discord,项目名称:bot,代码行数:8,代码来源:test_security.py

示例6: check_on_guild

# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import NoPrivateMessage [as 别名]
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 
开发者ID:python-discord,项目名称:bot,代码行数:7,代码来源:security.py

示例7: cog_check

# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import NoPrivateMessage [as 别名]
def cog_check(self, ctx):
        if ctx.guild is None:
            raise NoPrivateMessage()
        return True 
开发者ID:avrae,项目名称:avrae,代码行数:6,代码来源:initTracker.py

示例8: cog_check

# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import NoPrivateMessage [as 别名]
def cog_check(self, ctx):
        def predicate(ctx):
            if ctx.guild is None:
                raise commands.NoPrivateMessage()
            return True

        return commands.check(predicate(ctx)) 
开发者ID:henry232323,项目名称:RPGBot,代码行数:9,代码来源:salary.py

示例9: no_pm

# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import NoPrivateMessage [as 别名]
def no_pm():
    def predicate(ctx):
        if ctx.command.name == "help":
            return True
        if ctx.guild is None:
            raise commands.NoPrivateMessage('This command cannot be used in private messages.')
        return True

    return commands.check(predicate) 
开发者ID:henry232323,项目名称:RPGBot,代码行数:11,代码来源:checks.py

示例10: on_command_error

# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import NoPrivateMessage [as 别名]
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() 
开发者ID:jgayfer,项目名称:spirit,代码行数:37,代码来源:core.py

示例11: on_command_error

# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import NoPrivateMessage [as 别名]
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)) 
开发者ID:ZeroEpoch1969,项目名称:RubyRoseBot,代码行数:39,代码来源:bot.py

示例12: on_command_error

# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import NoPrivateMessage [as 别名]
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 
开发者ID:lehnification,项目名称:Discord-SelfBot,代码行数:13,代码来源:selfbot.py

示例13: on_command_error

# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import NoPrivateMessage [as 别名]
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 
开发者ID:EmoteBot,项目名称:EmoteCollector,代码行数:39,代码来源:__init__.py

示例14: channel_mod_only

# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import NoPrivateMessage [as 别名]
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) 
开发者ID:NabDev,项目名称:NabBot,代码行数:13,代码来源:checks.py

示例15: tracking_world_only

# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import NoPrivateMessage [as 别名]
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) 
开发者ID:NabDev,项目名称:NabBot,代码行数:14,代码来源:checks.py


注:本文中的discord.ext.commands.NoPrivateMessage方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。