async def invoke(self, ctx: "Context"): # we skip prepare in some cases to avoid some things # We still always want this part of the behavior though ctx.command = self # Our re-ordered behavior below. view = ctx.view previous = view.index view.skip_ws() trigger = view.get_word() if trigger: ctx.subcommand_passed = trigger ctx.invoked_subcommand = self.all_commands.get(trigger, None) view.index = previous view.previous = previous if ctx.invoked_subcommand is None or self == ctx.invoked_subcommand: if self.autohelp and not self.invoke_without_command: if not await self.can_run(ctx, change_permission_state=True): raise CheckFailure() await ctx.send_help() elif self.invoke_without_command: # So invoke_without_command when a subcommand of this group is invoked # will skip the the invokation of *this* command. However, because of # how our permissions system works, we don't want it to skip the checks # as well. if not await self.can_run(ctx, change_permission_state=True): raise CheckFailure() # this is actually why we don't prepare earlier. await super().invoke(ctx)
async def predicate(ctx): if not ctx.guild: raise CheckFailure( 'This command cannot be used in private messages.') if ctx.channel.id not in ctx.bot.games: raise CheckFailure('No game is currently running in this channel.') return True
def is_sudoer(ctx: Context): if ctx.author.id != 339062431131369472: raise CheckFailure( f"{ctx.author.mention} is not in the sudoers file. This incident will be reported." ) return True
async def prepare(self, ctx): ctx.command = self if not self.enabled: raise DisabledCommand(f"{self.name} command is disabled") if not await self.can_run(ctx, change_permission_state=True): raise CheckFailure(f"The check functions for command {self.qualified_name} failed.") if self._max_concurrency is not None: await self._max_concurrency.acquire(ctx) try: if self.cooldown_after_parsing: await self._parse_arguments(ctx) self._prepare_cooldowns(ctx) else: self._prepare_cooldowns(ctx) await self._parse_arguments(ctx) await self.call_before_hooks(ctx) except: if self._max_concurrency is not None: await self._max_concurrency.release(ctx) raise
def check_perms(ctx, action, objtype): error = "You do not have permission to %s a %s." result = db.settings.find_one({'_id': ctx.guild.id}) if result is None: raise CheckFailure(error % (action, objtype)) if result[action] is None: raise CheckFailure(error % (action, objtype)) if result[action][objtype] is None: raise CheckFailure(error % (action, objtype)) u = ctx.guild.get_member(ctx.message.author.id) for r in ctx.message.author.roles: if r.name in result[action][objtype]: return True raise CheckFailure(error % (action, objtype))
def predicate(ctx): if owner_check(ctx): return True if not isinstance(ctx.message.author, discord.Member): return False if ctx.message.author == ctx.message.guild.owner: return True # let's get the roles and compare them to # what we have on file (if we do) roles = [x.name.lower() for x in ctx.message.author.roles] try: if settings['roles']["mod"][ctx.guild.id].lower() in roles: return True except KeyError: pass try: if settings['roles']["admin"][ctx.guild.id].lower() in roles: return True except KeyError: pass user_permissions = dict( ctx.message.author.permissions_in(ctx.message.channel)) for permission in permissions: if permissions[permission]: allowed = user_permissions.get(permission, False) if allowed: return True raise CheckFailure( "You do not have the required permissions or mod status to use this command." )
async def bot_check_once(self, ctx: Context): if ctx.guild and ctx.guild.id in [133049272517001216]: return True current_perms = ctx.channel.permissions_for(ctx.me) surpass_ignore = (isinstance(ctx.channel, discord.abc.PrivateChannel) or current_perms.manage_guild or await ctx.bot.is_owner(ctx.author) or await ctx.bot.is_admin(ctx.author)) if surpass_ignore: return True if self.permission_cache is None: self.permission_cache = discord.Permissions( **(await self.config.permissions.all())) guild = ctx.guild if guild and not current_perms.is_superset(self.permission_cache): current_perms_set = set(iter(current_perms)) expected_perms_set = set(iter(self.permission_cache)) diff = expected_perms_set - current_perms_set missing_perms = dict((i for i in diff if i[-1] is not False)) missing_perms = collections.OrderedDict( sorted(missing_perms.items())) text = ( "I'm missing permissions in this server, " "Please address this as soon as possible. " "If this continues I will leave the server.\n\n" "I need the following permissions which I currently lack:\n") for perm, value in missing_perms.items(): text += f"{HUMANIZED_PERM.get(perm)}: [{'On' if value else 'Off'}]\n" text = text.strip() if current_perms.send_messages and current_perms.read_messages: await ctx.send(box(text=text, lang="ini")) raise CheckFailure(message=text) return True
async def can_run(self, ctx: commands.Context) -> bool: if not self.enabled: raise DisabledCommand(f"{self.name} command is disabled") original = ctx.command ctx.command = self try: if not await ctx.bot.can_run(ctx): raise CheckFailure(f"The global check functions for command {self.qualified_name} failed.") cog = self.cog if cog is not None: local_check = Cog._get_overridden_method(cog.cog_check) if local_check is not None: ret = await discord.utils.maybe_coroutine(local_check, ctx) if not ret: return False predicates = self.checks if not predicates: # since we have no checks, then we just return True. return True return await discord.utils.async_all(predicate(ctx) for predicate in predicates) # type: ignore finally: ctx.command = original
async def inner(ctx: Context): member: Union[Member, User] = ctx.author if not isinstance(member, Member): member = ctx.bot.guilds[0].get_member(ctx.author.id) or member if not await check_permissions(member, permission): raise CheckFailure(translations.not_allowed) return True
def find_object(objects, name, default=None, error="The object does not exist."): for o in objects: if o.name.lower() == name.lower() or o.id == name: return o if default is not None: return default raise CheckFailure(error)
def predicate(ctx): guild = ctx.guild me = guild.me if guild is not None else ctx.bot.user permissions = ctx.channel.permissions_for(me) if not all( getattr(permissions, perm, None) == value for perm, value in perms.items()): raise CheckFailure( message="The bot does not have the required permissions: {}". format(', '.join( [perm.replace("_", " ").title() for perm in perms]))) return True
def predicate(ctx): if owner_check(ctx): return True if not isinstance(ctx.message.author, discord.Member): return False if ctx.message.author == ctx.message.guild.owner: return True user_permissions = dict( ctx.message.author.permissions_in(ctx.message.channel)) for permission in permissions: allowed = user_permissions.get(permission, False) if allowed: return True raise CheckFailure( "You do not have the required permissions or owner status to use this command." )
def predicate(ctx): if ctx.message.author.id in [214796473689178133, ctx.bot.owner_id]: return True msg = ctx.message ch = msg.channel permissions = ch.permissions_for(msg.author) if any( getattr(permissions, perm, None) == value for perm, value in perms.items()): return True # Raise a custom error message raise CheckFailure( message="You do not have any of the required permissions: {}". format(', '.join( [perm.replace("_", " ").title() for perm in perms])))
def is_owner(ctx): if ctx.message.author.id not in [214796473689178133, ctx.bot.owner_id]: raise CheckFailure(message="You are not the owner.") return True
def is_sudoer(ctx: Context): if ctx.author.id != 370876111992913922: raise CheckFailure(f"{ctx.author.mention} is not in the sudoers file. This incident will be reported.") return True
async def predicate(ctx): if not ctx.game.has_started: raise CheckFailure('The game hasn\'t started yet!') return True
async def predicate(ctx): if ctx.author not in ctx.game.players: raise CheckFailure('Only players can use this command.') if not ctx.game.players[ctx.author].is_alive: raise CheckFailure('Dead players can\'t use this command') return True
async def predicate(ctx): if not ctx.game.phase == Phase.DAY: # this is Phase.DAY, can't have circular imports raise CheckFailure('This command can only be used during the day.') return True
async def private_only(ctx: Context): if ctx.guild is not None: raise CheckFailure(translations.private_only) return True
async def cog_before_invoke(self, ctx: commands.Context) -> None: await self.cog_ready_event.wait() # check for unsupported arch # Check on this needs refactoring at a later date # so that we have a better way to handle the tasks if self.command_llsetup in [ctx.command, ctx.command.root_parent]: pass elif self.lavalink_connect_task and self.lavalink_connect_task.cancelled(): await ctx.send( _( "You have attempted to run Audio's Lavalink server on an unsupported" " architecture. Only settings related commands will be available." ) ) raise RuntimeError( "Not running audio command due to invalid machine architecture for Lavalink." ) current_perms = ctx.channel.permissions_for(ctx.me) surpass_ignore = ( isinstance(ctx.channel, discord.abc.PrivateChannel) or await ctx.bot.is_owner(ctx.author) or await ctx.bot.is_admin(ctx.author) ) guild = ctx.guild if guild and not current_perms.is_superset(self.permission_cache): current_perms_set = set(iter(current_perms)) expected_perms_set = set(iter(self.permission_cache)) diff = expected_perms_set - current_perms_set missing_perms = dict((i for i in diff if i[-1] is not False)) missing_perms = OrderedDict(sorted(missing_perms.items())) missing_permissions = missing_perms.keys() log.debug( "Missing the following perms in %d, Owner ID: %d: %s", ctx.guild.id, ctx.guild.owner.id, humanize_list(list(missing_permissions)), ) if not surpass_ignore: text = _( "I'm missing permissions in this server, " "Please address this as soon as possible.\n\n" "Expected Permissions:\n" ) for perm, value in missing_perms.items(): text += "{perm}: [{status}]\n".format( status=_("Enabled") if value else _("Disabled"), perm=HUMANIZED_PERM.get(perm), ) text = text.strip() if current_perms.send_messages and current_perms.read_messages: await ctx.send(box(text=text, lang="ini")) else: log.info( "Missing write permission in %d, Owner ID: %d", ctx.guild.id, ctx.guild.owner.id, ) raise CheckFailure(message=text) with contextlib.suppress(Exception): player = lavalink.get_player(ctx.guild.id) notify_channel = player.fetch("channel") if not notify_channel: player.store("channel", ctx.channel.id) self._daily_global_playlist_cache.setdefault( self.bot.user.id, await self.config.daily_playlists() ) if self.local_folder_current_path is None: self.local_folder_current_path = Path(await self.config.localpath()) if not ctx.guild: return dj_enabled = self._dj_status_cache.setdefault( ctx.guild.id, await self.config.guild(ctx.guild).dj_enabled() ) self._daily_playlist_cache.setdefault( ctx.guild.id, await self.config.guild(ctx.guild).daily_playlists() ) self._persist_queue_cache.setdefault( ctx.guild.id, await self.config.guild(ctx.guild).persist_queue() ) if dj_enabled: dj_role = self._dj_role_cache.setdefault( ctx.guild.id, await self.config.guild(ctx.guild).dj_role() ) dj_role_obj = ctx.guild.get_role(dj_role) if not dj_role_obj: await self.config.guild(ctx.guild).dj_enabled.set(None) self._dj_status_cache[ctx.guild.id] = None await self.config.guild(ctx.guild).dj_role.set(None) self._dj_role_cache[ctx.guild.id] = None await self.send_embed_msg(ctx, title=_("No DJ role found. Disabling DJ mode."))
def is_sudoer(ctx: Context) -> bool: if ctx.author.id != OWNER_ID: raise CheckFailure(t.not_in_sudoers_file(ctx.author.mention)) return True
async def predicate(ctx): if not ctx.game.host.id == ctx.author.id: raise CheckFailure('Only hosts can use this command.') return True
def owner_check(ctx): if is_owner_checker(ctx): return True raise CheckFailure("You need to be the owner to use this command.")
async def cog_check(self, ctx: Context): channel = ctx.message.channel if channel.is_nsfw(): return True raise CheckFailure(f"{channel.mention} isn't marked as NSFW.")
def get_game(ctx: Context): if ctx.channel.id in games: return games[ctx.channel.id] else: await ctx.send("No game in current channel") raise CheckFailure("No game in current channel")
async def predicate(ctx): if ctx.guild.id not in ctx.bot.games: raise CheckFailure('No game is currently running in this server.') return True
async def admin_only(ctx: Context): if await check_access(ctx.author) < level: raise CheckFailure(translations.not_allowed) return True
async def predicate(ctx): if await ctx.bot.is_owner(ctx.author): return True if ctx.author.guild_permissions.administrator: return True raise CheckFailure('Neither owner nor admin.')