當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。