async def predicate(ctx: commands.Context): if not ctx.guild: raise commands.NoPrivateMessage # mfw checks are run before __before_invoke hooks starboard = base.get_starboard(ctx.guild) if await starboard.resolve_starboard() is None: raise commands.CheckFailure("The current server has no starboard channel setup") if await starboard.is_ignored(ctx.author) and not ( await starboard.bot.is_owner(ctx.author) or await starboard.bot.is_mod(ctx.author) ): raise commands.CheckFailure("Command issuer is ignored from this server's starboard") return True
async def before_invoke_hook(self, ctx: commands.Context): if self.toggle and ctx.channel == ctx.author.dm_channel and ctx.author.id not in ctx.bot.owner_ids: if self.allowed: if ctx.author.id not in self.allowed: await self._error_message(ctx=ctx) raise commands.CheckFailure() elif self.blocked: if ctx.author.id in self.blocked: await self._error_message(ctx=ctx) raise commands.CheckFailure() else: await self._error_message(ctx=ctx) raise commands.CheckFailure()
async def ensure_can_modify(self, member: discord.Member): """Ensure the given member is allowed to modify this quote, and raise CheckFailure if not. """ if not await self.can_modify(member): raise commands.CheckFailure( "The specified quote exists, but the command issuer is not authorized to modify it" )
async def predicate(ctx): if not await bank.can_spend(ctx.author, cost): currency_name = await bank.get_currency_name(ctx.guild) raise commands.CheckFailure( f"You need {humanize_number(cost)} {currency_name} to be able to take parts in an adventures" ) return True
async def before_invoke_hook(ctx: commands.Context): guild = ctx.guild if not guild: return if guild.me == guild.owner: return if await ctx.bot.is_owner(guild.owner): return author, me = ctx.author, guild.me assert isinstance(author, discord.Member) # nosec if me.guild_permissions.administrator: if ( author.top_role > me.top_role or author == guild.owner ) and author.guild_permissions.manage_roles: with contextlib.suppress(Exception): await ctx.send( "This bot refuses to work with admin permissions. " "They are dangerous and lazy to give out." ) raise commands.CheckFailure()
async def before_invoke_hook(ctx: commands.Context): if not ctx.guild or isinstance(ctx.command, commands.commands._AlwaysAvailableCommand): return guild = ctx.guild if guild.me == guild.owner: return if await ctx.bot.is_owner(ctx.author): return cog = ctx.bot.get_cog("PermissionsLocker") if guild.id in cog._whitelist: return me = guild.me requiredPerms = discord.Permissions(cog.perms) myPerms = ctx.channel.permissions_for(me) if not myPerms.is_superset(requiredPerms): missingPerms = await cog.humanize_perms( discord.Permissions((myPerms.value ^ requiredPerms.value) & requiredPerms.value), True, ) await ctx.send( "Hello there!\nI'm missing the following permissions. Without these permissions, I cannot function properly. " "Please check your guild and channel permissions to ensure I have these permissions:" f"\n{box(missingPerms, 'diff')}", delete_after=60, ) raise commands.CheckFailure()
async def before_invoke_hook(ctx: commands.Context): if not ctx.guild: return guild = ctx.guild if guild.me == guild.owner: return if await ctx.bot.is_owner(ctx.author): return data = await ctx.bot.get_cog("PermissionsLocker").config.all() if guild.id in data["whitelisted"]: return author, me = ctx.author, guild.me assert isinstance(author, discord.Member) # nosec requiredPerms = discord.Permissions(data["permissions"]) myPerms = ctx.channel.permissions_for(me) if not myPerms.is_superset(requiredPerms): missingPerms = await ctx.bot.get_cog( "PermissionsLocker").humanize_perms( discord.Permissions((myPerms.value ^ requiredPerms.value) & requiredPerms.value), True, ) await ctx.send( "Hello there!\nI'm missing the following permissions. Without these permissions, I cannot function properly. " "Please check your guild and channel permissions to ensure I have these permissions:" f"\n{box(missingPerms, 'diff')}", delete_after=60, ) raise commands.CheckFailure()
async def cog_before_invoke(self, ctx): # use if commands need initialize() to finish async with ctx.typing(): await self._ready.wait() if self._ready_raised: await ctx.send( "There was an error during OnStudy's initialization. Check logs for more information." ) raise commands.CheckFailure()
async def predicate(ctx: commands.Context) -> bool: if ctx.guild is None: return False cog = cast(RSSNotifier, ctx.cog) ping_single_users = await cog.config.guild(ctx.guild ).ping_single_users() if ping_single_users: return True raise commands.CheckFailure( "User mentions in RSSNotifier are disabled for this server.")
async def __global_check(self, ctx: commands.Context): if not ctx.cog or await self.bot.is_owner(ctx.author): return True if not await self.is_whitelisted(ctx.cog.__class__.__name__, ctx.guild): log.debug( "Rejected attempted use of command '{ctx.command.qualified_name}' " "from cog {ctx.cog.__class__.__name__} in guild {ctx.guild!r}".format(ctx=ctx) ) raise commands.CheckFailure( "Cog {} requires a whitelist to use, but the current guild is not whitelisted." ) return True
async def embed_convert_error(ctx: commands.Context, error_type: str, error: Exception): embed = discord.Embed( color=await ctx.embed_color(), title=f"{error_type}: `{type(error).__name__}`", description=f"```py\n{error}\n```", ) embed.set_footer( text= f"Use `{ctx.prefix}help {ctx.command.qualified_name}` to see an example" ) asyncio.create_task(menus.menu(ctx, [embed], {"❌": menus.close_menu})) raise commands.CheckFailure()
async def predicate(ctx: commands.GuildContext) -> bool: session = ctx.cog._get_trivia_session(ctx.channel) if session is None: raise commands.CheckFailure( _("There is no ongoing trivia session in this channel.")) author = ctx.author auth_checks = ( await ctx.bot.is_owner(author), await ctx.bot.is_mod(author), await ctx.bot.is_admin(author), author == ctx.guild.owner, author == session.ctx.author, ) return any(auth_checks)
async def before_invoke_hook(self, ctx): if await self.is_redirect_immune(ctx): return True allowed_chans = await self.get_allowed_channels(ctx) if ctx.channel not in allowed_chans: chan_mentions = ", ".join(c.mention for c in allowed_chans) await ctx.send( f"{ctx.author.mention} This command is only available in {chan_mentions}", delete_after=30, ) raise commands.CheckFailure() # This is abuse. else: return True
async def cog_before_invoke(self, ctx): async with ctx.typing(): await self._ready.wait() if self._ready_raised and time.time( ) - self._ready_raised > INIT_RETRY_COOLDOWN: # Immediately update timestamp to prevent multiple calls during # the re-attempt self._ready_raised = time.time() init_success = await self.initialize() if init_success: self._ready_raised = False else: log.info('Initialization is still incomplete.') self._ready_raised = time.time() if self._ready_raised and time.time( ) - self._ready_raised < INIT_RETRY_COOLDOWN: # Catches both recent failures and failures on cooldown await ctx.send( "Something's not quite right. Please wait %d seconds and try again." % (int(time.time() - self._ready_raised) + 3, )) raise commands.CheckFailure()
async def before_invoke_hook(ctx: commands.Context): if ctx.channel == ctx.author.dm_channel and ctx.author.id not in ctx.bot.owner_ids: raise commands.CheckFailure()
def predicate(ctx): if isinstance(ctx.channel, discord.abc.GuildChannel): raise commands.CheckFailure("This command cannot be used in guild channels.") return True
async def rift_search(self, ctx: commands.Context, *, scope: str = "channel"): """ Provides info about rifts opened in the specified scope. """ author = Limited(message=ctx.message) if ctx.guild else ctx.author try: scoped = { "user": author, "member": author, "author": author, "channel": ctx.channel if ctx.guild else ctx.author, "guild": ctx.guild, "server": ctx.guild, "global": None, }[scope.casefold()] except KeyError: raise commands.BadArgument( _("Invalid scope. Scope must be author, channel, guild, server, or global.") ) if not scoped and not await ctx.bot.is_owner(ctx.author): raise commands.CheckFailure() if scoped == ctx.guild and not await mod.is_admin_or_superior(ctx.bot, ctx.author): raise commands.CheckFailure() def check(vector): if not scoped: return True if scoped in vector: return True if scoped in map(lambda c: getattr(c, "guild", None), vector): return True return False unique_rifts: Set[Vector[Messageable]] = set() for source, destination in self.rifts.vectors(): if check((source, destination)) and (destination, source) not in unique_rifts: unique_rifts.add((source, destination)) total_rifts = len(unique_rifts) if not total_rifts: return await ctx.send(_("No rifts are connected to this scope.")) pages: List[discord.Embed] = [] for i, (source, destination) in enumerate(unique_rifts, 1): if source in self.rifts.get(destination, ()): delim = "⟷" else: delim = "⟶" embed = discord.Embed( title=f"{source} {delim} {destination}", color=await ctx.embed_color() ) if topic := getattr(destination, "topic", None): embed.description = topic try: members = destination.users except AttributeError: members = destination.members # TODO: format and sort members member_str = humanize_list(list(map(str, members))) short_member_str = next(pagify(member_str, delims=[","])) if len(member_str) != len(short_member_str): short_member_str += " …" embed.add_field(name=f"Connected from {destination}", value=member_str) embed.set_footer(text=f"Rift {i} of {total_rifts}") pages.append(embed)
async def __global_check(self, ctx: commands.Context): if not await self.check(member=ctx.author): raise commands.CheckFailure() return True