def requiredEnabled(**kwargs):
'''Checks to see if a certain token type's secret exists
Parameters ::
token : str
The type of token whose secret needs to exist
'''
def predicate(ctx):
token = kwargs.get('enable')
serverSettings = getServerJson(ctx.message.server.id)
enabled = serverSettings['Toggles'][token]
if enabled:
return True
else:
raise CommandDisabled
return False
return commands.check(predicate)
python类check()的实例源码
def needsToken(**kwargs):
'''Checks to see if a certain token type's secret exists
Parameters ::
token : str
The type of token whose secret needs to exist
'''
def predicate(ctx):
token = kwargs.get('token')
v = getTokens()[token]
for i, o in v.items():
if not o:
raise ThisNeedsAToken
return True
return commands.check(predicate)
def check_last(self, ctx: commands.Context, name):
""" Shows you how long other users' last session lasted.
:param name: The name (not the nick) of the person to check.
Must use the name#discriminator format.
"""
time_str = printable_time(db_manager.get_user_last_session(name))
if time_str is None:
time_str = "None found."
lib.log("{} queried for {}'s last session time. Result: {}"
.format(lib.get_author_name(ctx, True),
"their" if name == str(ctx.message.author)
else (name + "'s"), time_str))
await self.bot.say("```{}```".format(time_str),
delete_after=self.bot.ans_lifespan * 3)
def total(self, ctx: commands.Context, name=None):
""" Shows you the total time a user has used the timer for.
:param name: The name (not the nick) of the person to check.
Must use the name#discriminator format. If none is provided, it will
check your own record.
"""
if name is None:
name = ctx.message.author
time_str = printable_time(db_manager.get_user_total(name))
if time_str is None:
time_str = "None found."
name = str(name)
lib.log("{} queried for {}'s last session time. Result: {}"
.format(lib.get_author_name(ctx, True),
"their" if name == str(ctx.message.author)
else (name + "'s"), time_str))
await self.bot.say("```{}```".format(time_str),
delete_after=self.bot.ans_lifespan * 3)
def in_channel(name):
"""
Checks if command is sent in a given channel ignores high roles.
To be used as a decorator
:param name: name of the channel
"""
def predicate(ctx):
if ctx.message.channel.is_private:
return False
# Adapted from discord.ext.core.has_any_role
user_roles = functools.partial(discordutils.get, ctx.message.author.roles)
if any(user_roles(name=role) is not None for role in ['Admin', 'Moderator', 'Support']):
return True
return ctx.message.channel.name == name
return commands.check(predicate)
def permcheck(**kwargs):
def predicate(ctx):
owners_ = kwargs.get('owners', [])
check = kwargs.get('check', '')
if type(owners_) is not list:
owners_ = [owners_]
if ctx.message.author.id in [owners[x] for x in owners_]:
return True
if check == 'dm_only' and ctx.message.server is None:
return True
return False
return commands.check(predicate)
def progress(self, ctx):
"""Provides the progress of the current song"""
# Make sure we're playing first
state = self.get_voice_state(ctx.message.server)
if not state.is_playing():
await self.bot.say('Not playing anything.')
else:
progress = state.current.progress
length = state.current.length
# Another check, just to make sure; this may happen for a very brief amount of time
# Between when the song was requested, and still downloading to play
if not progress or not length:
await self.bot.say('Not playing anything.')
return
# Otherwise just format this nicely
progress = divmod(round(progress, 0), 60)
length = divmod(round(length, 0), 60)
fmt = "Current song progress: {0[0]}m {0[1]}s/{1[0]}m {1[1]}s".format(progress, length)
await self.bot.say(fmt)
def summon(self, ctx):
"""Summons the bot to join your voice channel."""
# This method will be invoked by other commands, so we should return True or False instead of just returning
# First check if the author is even in a voice_channel
summoned_channel = ctx.message.author.voice_channel
if summoned_channel is None:
await self.bot.say('You are not in a voice channel.')
return False
# Then simply create a voice client
try:
success = await self.create_voice_client(summoned_channel)
except (asyncio.TimeoutError, discord.ConnectionClosed):
await self.bot.say("I failed to connect! This usually happens if I don't have permission to join the"
" channel, but can sometimes be caused by your server region being far away."
" Otherwise this is an issue on Discord's end, causing the connect to timeout!")
await self.remove_voice_client(summoned_channel.server)
return False
if success:
try:
await self.bot.say('Ready to play audio in ' + summoned_channel.name)
except discord.Forbidden:
pass
return success
def __init__(self, bot):
super().__init__(bot)
addr = getattr(bot.config, 'MONGO_LOC', None)
self.mongo_client = motor.motor_asyncio.AsyncIOMotorClient(addr)
self.bot.mongo = self.mongo_client
self.jose_db = self.mongo_client['jose']
self.config_coll = self.jose_db['config']
self.block_coll = self.jose_db['block']
self.bot.block_coll = self.block_coll
# querying the db every time is not worth it
self.config_cache = collections.defaultdict(dict)
# used to check if cache has all defined objects in it
self.default_keys = None
def can_use_box():
def pred(ctx):
if ctx.guild is None:
return True
if ctx.author.id == ctx.bot.owner_id:
return True
has_perms = ctx.channel.permissions_for(ctx.author).manage_messages
if not has_perms:
raise UnableToUseBox()
return True
return commands.check(pred)
# The tag data is heavily duplicated (denormalized) and heavily indexed to speed up
# retrieval at the expense of making inserts a little bit slower. This is a fine trade-off
# because tags are retrieved much more often than created.
def is_owner():
def predicate(ctx):
if is_owner_check(ctx):
return True
else:
raise errors.NotOwner
return commands.check(predicate)
def is_server_owner():
def predicate(ctx):
if is_server_owner_check(ctx):
return True
else:
raise errors.NotServerOwner
return commands.check(predicate)
def is_voice_connected():
def predicate(ctx):
if not is_voice_connected_check(ctx):
if is_server_owner_check(ctx) or utilities.get_permission(ctx, "join", id = ctx.message.author.id):
raise errors.PermittedVoiceNotConnected
else:
raise errors.NotPermittedVoiceNotConnected
return True
return commands.check(predicate)
def has_permissions(**permissions):
def predicate(ctx):
if has_permissions_check(ctx, permissions):
return True
else:
raise errors.MissingPermissions
return commands.check(predicate)
def dm_or_has_permissions(**permissions):
def predicate(ctx):
if ctx.message.channel.is_private or has_permissions_check(ctx, permissions):
return True
else:
raise errors.MissingPermissions
return commands.check(predicate)
def dm_or_has_capability(*permissions):
def predicate(ctx):
if ctx.message.channel.is_private or has_capability_check(ctx, permissions):
return True
else:
raise errors.MissingCapability(permissions)
return commands.check(predicate)
def has_permissions_and_capability(**permissions):
def predicate(ctx):
if ctx.message.channel.is_private:
return False
elif not has_permissions_check(ctx, permissions):
raise errors.MissingPermissions
elif not has_capability_check(ctx, permissions.keys()):
raise errors.MissingCapability(permissions.keys())
else:
return True
return commands.check(predicate)
def dm_or_has_permissions_and_capability(**permissions):
def predicate(ctx):
if ctx.message.channel.is_private:
return True
elif not has_permissions_check(ctx, permissions):
raise errors.MissingPermissions
elif not has_capability_check(ctx, permissions.keys()):
raise errors.MissingCapability(permissions.keys())
else:
return True
return commands.check(predicate)
def not_forbidden():
def predicate(ctx):
if not_forbidden_check(ctx):
return True
else:
raise errors.NotPermitted
return commands.check(predicate)
def is_permitted():
def predicate(ctx):
if is_permitted_check(ctx):
return True
else:
raise errors.NotPermitted
return commands.check(predicate)
def is_owner():
return commands.check(is_owner_check)
# The permission system of the bot is based on a "just works" basis
# You have permissions and the bot has permissions. If you meet the permissions
# required to execute the command (and the bot does as well) then it goes through
# and you can execute the command.
# If these checks fail, then there are two fallbacks.
# A role with the name of Bot Mod and a role with the name of Bot Admin.
# Having these roles provides you access to certain commands without actually having
# the permissions required for them.
# Of course, the owner will always be able to execute commands.
def role_or_permissions(ctx, check, **perms):
if check_permissions(ctx, perms):
return True
ch = ctx.message.channel
author = ctx.message.author
if ch.is_private:
return False # can't have roles in PMs
role = discord.utils.find(check, author.roles)
return role is not None
def serverowner_or_permissions(**perms):
def predicate(ctx):
if ctx.message.guild is None:
return False
guild = ctx.message.guild
owner = guild.owner
if ctx.message.author.id == owner.id:
return True
return check_permissions(ctx,perms)
return commands.check(predicate)
def is_owner():
return commands.check(lambda ctx: is_owner_check(ctx.message))
def owner():
return commands.check(is_owner_check)
def admin():
return commands.check(is_admin_check)
def serverowner():
def predicate(ctx):
if ctx.message.server is None:
return False
if ctx.message.author.id == ctx.message.server.owner.id:
return True
# return check_permissions(ctx, perms)
return False
return commands.check(predicate)
def need_db(command):
"""Decorator, not check, to mark the command as needing a DB connection."""
command._db = True
return command
def config_attr(attr):
return commands.check(lambda _: getattr(config, attr, None) is not None)
def owner_or_permissions(**perms):
return commands.check(lambda ctx: check_permissions(ctx, perms))