本文整理汇总了Python中discord.ext.commands.MissingPermissions方法的典型用法代码示例。如果您正苦于以下问题:Python commands.MissingPermissions方法的具体用法?Python commands.MissingPermissions怎么用?Python commands.MissingPermissions使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类discord.ext.commands
的用法示例。
在下文中一共展示了commands.MissingPermissions方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: assertHasPermissionsCheck
# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import MissingPermissions [as 别名]
def assertHasPermissionsCheck( # noqa: N802
self,
cmd: commands.Command,
permissions: Dict[str, bool],
) -> None:
"""
Test that `cmd` raises a `MissingPermissions` exception if author lacks `permissions`.
Every permission in `permissions` is expected to be reported as missing. In other words, do
not include permissions which should not raise an exception along with those which should.
"""
# Invert permission values because it's more intuitive to pass to this assertion the same
# permissions as those given to the check decorator.
permissions = {k: not v for k, v in permissions.items()}
ctx = helpers.MockContext()
ctx.channel.permissions_for.return_value = discord.Permissions(**permissions)
with self.assertRaises(commands.MissingPermissions) as cm:
await cmd.can_run(ctx)
self.assertCountEqual(permissions.keys(), cm.exception.missing_perms)
示例2: on_command_error
# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import MissingPermissions [as 别名]
def on_command_error(ctx, error):
send_help = (commands.MissingRequiredArgument, commands.BadArgument, commands.TooManyArguments, commands.UserInputError)
if isinstance(error, commands.CommandNotFound): # fails silently
pass
elif isinstance(error, send_help):
_help = await send_cmd_help(ctx)
await ctx.send(embed=_help)
elif isinstance(error, commands.CommandOnCooldown):
await ctx.send(f'This command is on cooldown. Please wait {error.retry_after:.2f}s')
elif isinstance(error, commands.MissingPermissions):
await ctx.send('You do not have the permissions to use this command.')
# If any other error occurs, prints to console.
else:
print(''.join(traceback.format_exception(type(error), error, error.__traceback__)))
示例3: set_locale_command
# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import MissingPermissions [as 别名]
def set_locale_command(self, context, channel: typing.Optional[discord.TextChannel], locale: Locale):
"""Set the locale for a channel or yourself.
Manage Messages is required to change the locale of a whole channel.
If the channel is left blank, this command sets your user locale.
"""
if channel is None:
await self.set_user_locale(context.author.id, locale)
elif (
not context.author.guild_permissions.manage_messages
or not await self.bot.is_owner(context.author)
):
raise commands.MissingPermissions(('manage_messages',))
else:
await self.set_channel_locale(context.guild.id, channel.id, locale)
await context.try_add_reaction(utils.SUCCESS_EMOJIS[True])
示例4: has_guild_permissions
# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import MissingPermissions [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)
示例5: prefix
# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import MissingPermissions [as 别名]
def prefix(self, ctx, *, prefix: str = None):
if prefix is None:
await ctx.send(
embed=discord.Embed(
description=f"The prefix for this server is `{ctx.prefix}`.", colour=self.bot.primary_colour,
)
)
return
if ctx.author.guild_permissions.administrator is False:
raise commands.MissingPermissions(["administrator"])
else:
if len(prefix) > 10:
await ctx.send(
embed=discord.Embed(description="The chosen prefix is too long.", colour=self.bot.error_colour,)
)
return
if prefix == self.bot.config.default_prefix:
prefix = None
await self.bot.get_data(ctx.guild.id)
async with self.bot.pool.acquire() as conn:
await conn.execute("UPDATE data SET prefix=$1 WHERE guild=$2", prefix, ctx.guild.id)
self.bot.all_prefix[ctx.guild.id] = prefix
await ctx.send(
embed=discord.Embed(
description="Successfully changed the prefix to "
f"`{self.bot.config.default_prefix if prefix is None else prefix}`.",
colour=self.bot.primary_colour,
)
)
示例6: on_command_error
# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import MissingPermissions [as 别名]
def on_command_error(ctx, error):
if isinstance(error, commands.CommandNotFound):
return
if isinstance(error, commands.MissingRequiredArgument):
await ctx.send("Missing a required argument. Do >help")
if isinstance(error, commands.MissingPermissions):
await ctx.send("You do not have the appropriate permissions to run this command.")
if isinstance(error, commands.BotMissingPermissions):
await ctx.send("I don't have sufficient permissions!")
else:
print("error not caught")
print(error)
示例7: developer
# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import MissingPermissions [as 别名]
def developer():
def wrapper(ctx):
with open('data/devs.json') as f:
devs = json.load(f)
if ctx.author.id in devs:
return True
raise commands.MissingPermissions('You cannot use this command because you are not a developer.')
return commands.check(wrapper)
示例8: has_permissions
# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import MissingPermissions [as 别名]
def has_permissions(**perms):
"""Command can only be used if the user has the provided permissions."""
async def pred(ctx):
ret = await check_permissions(ctx, perms)
if not ret:
raise commands.MissingPermissions(perms)
return True
return commands.check(pred)
示例9: process_check_failure
# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import MissingPermissions [as 别名]
def process_check_failure(cls, ctx: context.NabCtx, error: commands.CheckFailure):
"""Handles CheckFailure errors.
These are exceptions that may be raised when executing command checks."""
if isinstance(error, (commands.NoPrivateMessage, errors.NotTracking, errors.UnathorizedUser,
commands.MissingPermissions)):
await ctx.error(error)
elif isinstance(error, errors.CannotEmbed):
await ctx.error(f"Sorry, `Embed Links` permission is required for this command.")
示例10: on_command_error
# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import MissingPermissions [as 别名]
def on_command_error(ctx: commands.Context, exc: BaseException):
if isinstance(exc, ignore_errors):
pass
elif isinstance(exc, MissingPermissions):
await ctx.send(
embed=Embed(
description='YAdmin command executed',
color=Color.red()))
elif isinstance(exc, NotADeveloper):
await ctx.send(
embed=Embed(
description='Oh nice you found an dev only command, but sorry only for devs!',
color=Color.red()))
else:
raise exc
示例11: admin_permissions
# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import MissingPermissions [as 别名]
def admin_permissions():
def predicate(ctx: CommandContext):
author: Member = ctx.message.author
if author.id in ADMINS:
return True
elif not author.guild_permissions.administrator:
raise MissingPermissions("You are missing administrator permissions")
else:
return True
return commands.check(predicate)
示例12: on_command_error
# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import MissingPermissions [as 别名]
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
示例13: setmp_error
# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import MissingPermissions [as 别名]
def setmp_error(self, ctx, error):
""" Respond to a permissions error with an explanation message. """
if isinstance(error, commands.MissingPermissions):
await ctx.trigger_typing()
missing_perm = error.missing_perms[0].replace('_', ' ')
title = f'Cannot set the map pool without {missing_perm} permission!'
embed = discord.Embed(title=title, color=self.color)
await ctx.send(embed=embed)
示例14: remove_error
# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import MissingPermissions [as 别名]
def remove_error(self, ctx, error):
""" Respond to a permissions error with an explanation message. """
if isinstance(error, commands.MissingPermissions):
await ctx.trigger_typing()
missing_perm = error.missing_perms[0].replace('_', ' ')
title = f'Cannot remove players without {missing_perm} permission!'
embed = discord.Embed(title=title, color=self.color)
await ctx.send(embed=embed)
示例15: cap_error
# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import MissingPermissions [as 别名]
def cap_error(self, ctx, error):
""" Respond to a permissions error with an explanation message. """
if isinstance(error, commands.MissingPermissions):
await ctx.trigger_typing()
missing_perm = error.missing_perms[0].replace('_', ' ')
title = f'Cannot change queue capacity without {missing_perm} permission!'
embed = discord.Embed(title=title, color=self.color)
await ctx.send(embed=embed)