Python discord.ext.commands.check() Examples

The following are 30 code examples of discord.ext.commands.check(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module discord.ext.commands , or try the search function .
Example #1
Source File: decorators.py    From seasonalbot with MIT License 6 votes vote down vote up
def without_role(*role_ids: int) -> t.Callable:
    """Check whether the invoking user does not have all of the roles specified in role_ids."""
    async def predicate(ctx: Context) -> bool:
        if not ctx.guild:  # Return False in a DM
            log.debug(
                f"{ctx.author} tried to use the '{ctx.command.name}' command from a DM. "
                "This command is restricted by the without_role decorator. Rejecting request."
            )
            return False

        author_roles = [role.id for role in ctx.author.roles]
        check = all(role not in author_roles for role in role_ids)
        log.debug(
            f"{ctx.author} tried to call the '{ctx.command.name}' command. "
            f"The result of the without_role check was {check}."
        )
        return check
    return commands.check(predicate) 
Example #2
Source File: checks.py    From modmail with GNU Affero General Public License v3.0 6 votes vote down vote up
def has_permissions(permission_level: PermissionLevel = PermissionLevel.REGULAR):
    """
    A decorator that checks if the author has the required permissions.

    Parameters
    ----------

    permission_level : PermissionLevel
        The lowest level of permission needed to use this command.
        Defaults to REGULAR.

    Examples
    --------
    ::
        @has_permissions(PermissionLevel.OWNER)
        async def setup(ctx):
            print("Success")
    """

    return commands.check(has_permissions_predicate(permission_level)) 
Example #3
Source File: checks.py    From modmail with GNU Affero General Public License v3.0 6 votes vote down vote up
def thread_only():
    """
    A decorator that checks if the command
    is being ran within a Modmail thread.
    """

    async def predicate(ctx):
        """
        Parameters
        ----------
        ctx : Context
            The current discord.py `Context`.

        Returns
        -------
        Bool
            `True` if the current `Context` is within a Modmail thread.
            Otherwise, `False`.
        """
        return ctx.thread is not None

    predicate.fail_msg = "This is not a Modmail thread."
    return commands.check(predicate) 
Example #4
Source File: checks.py    From DHV3 with GNU Affero General Public License v3.0 6 votes vote down vote up
def voted_lately():
    async def predicate(ctx):
        player = ctx.message.author

        headers = {'authorization': ctx.bot.discordbots_org_key, 'content-type': 'application/json'}

        url = '{0}/bots/{1.user.id}/check?userId={2.id}'.format(DISCORD_BOTS_ORG_API, ctx.bot, player)
        async with session.get(url, headers=headers) as resp:
            cond = bool((await resp.json())['voted'])

        if cond:
            return True
        else:
            raise NoVotesOnDBL

    return commands.check(predicate) 
Example #5
Source File: checks.py    From DHV3 with GNU Affero General Public License v3.0 6 votes vote down vote up
def had_giveback():
    async def predicate(ctx):
        # await ctx.bot.wait_until_ready()

        channel = ctx.channel
        player = ctx.author
        if int(await ctx.bot.db.get_stat(channel, player, "banned")) == 1:
            cond = ctx.author.id in ctx.bot.admins  # User is super admin
            cond = cond or ctx.channel.permissions_for(ctx.author).administrator  # User have server administrator permission
            cond = cond or ctx.author.id in await ctx.bot.db.get_admins(ctx.guild)  # User is admin as defined in the database
            if not cond:  # Not even an admin so
                ctx.logger.debug("Banned player trying to play :(")
                return False

        lastGB = int(await ctx.bot.db.get_stat(channel, player, "lastGiveback"))
        if int(lastGB / 86400) != int(int(time.time()) / 86400):
            daygb = int(lastGB / 86400)
            daynow = int(int(time.time()) / 86400)
            ctx.logger.debug(f"Giveback needed : Last GiveBack was on day {daygb}, and we are now on day {daynow}.")
            await ctx.bot.db.giveback(channel=channel, user=player)

        return True

    return commands.check(predicate) 
Example #6
Source File: checks.py    From modmail with GNU Affero General Public License v3.0 6 votes vote down vote up
def is_mod():
    async def predicate(ctx):
        has_role = False
        roles = (await ctx.bot.get_data(ctx.guild.id))[3]
        for role in roles:
            role = ctx.guild.get_role(role)
            if not role:
                continue
            if role in ctx.author.roles:
                has_role = True
                break
        if has_role is False and ctx.author.guild_permissions.administrator is False:
            await ctx.send(
                embed=discord.Embed(
                    description=f"You do not have access to use this command.", colour=ctx.bot.error_colour,
                )
            )
            return False
        else:
            return True

    return commands.check(predicate) 
Example #7
Source File: checks.py    From modmail with GNU Affero General Public License v3.0 6 votes vote down vote up
def is_patron():
    async def predicate(ctx):
        async with ctx.bot.pool.acquire() as conn:
            res = await conn.fetchrow("SELECT identifier FROM premium WHERE identifier=$1", ctx.author.id)
        if res:
            return True
        slots = await ctx.bot.tools.get_premium_slots(ctx.bot, ctx.author.id)
        if slots is False:
            await ctx.send(
                embed=discord.Embed(
                    description="This command requires you to be a patron. Want to become a patron? More "
                    f"information is available with the `{ctx.prefix}premium` command.",
                    colour=ctx.bot.error_colour,
                )
            )
            return False
        else:
            async with ctx.bot.pool.acquire() as conn:
                await conn.execute(
                    "INSERT INTO premium (identifier, guild) VALUES ($1, $2)", ctx.author.id, [],
                )
            return True

    return commands.check(predicate) 
Example #8
Source File: checks.py    From modmail with GNU Affero General Public License v3.0 6 votes vote down vote up
def is_premium():
    async def predicate(ctx):
        async with ctx.bot.pool.acquire() as conn:
            res = await conn.fetch("SELECT guild FROM premium")
        all_premium = []
        for row in res:
            all_premium.extend(row[0])
        if ctx.guild.id not in all_premium:
            await ctx.send(
                embed=discord.Embed(
                    description="This server does not have premium. Want to get premium? More information "
                    f"is available with the `{ctx.prefix}premium` command.",
                    colour=ctx.bot.error_colour,
                )
            )
            return False
        else:
            return True

    return commands.check(predicate) 
Example #9
Source File: decorators.py    From seasonalbot with MIT License 6 votes vote down vote up
def in_month_listener(*allowed_months: Month) -> t.Callable:
    """
    Shield a listener from being invoked outside of `allowed_months`.

    The check is performed against current UTC month.
    """
    def decorator(listener: t.Callable) -> t.Callable:
        @functools.wraps(listener)
        async def guarded_listener(*args, **kwargs) -> None:
            """Wrapped listener will abort if not in allowed month."""
            current_month = resolve_current_month()

            if current_month in allowed_months:
                # Propagate return value although it should always be None
                return await listener(*args, **kwargs)
            else:
                log.debug(f"Guarded {listener.__qualname__} from invoking in {current_month!s}")
        return guarded_listener
    return decorator 
Example #10
Source File: decorators.py    From seasonalbot with MIT License 6 votes vote down vote up
def in_month_command(*allowed_months: Month) -> t.Callable:
    """
    Check whether the command was invoked in one of `enabled_months`.

    Uses the current UTC month at the time of running the predicate.
    """
    async def predicate(ctx: Context) -> bool:
        current_month = resolve_current_month()
        can_run = current_month in allowed_months

        log.debug(
            f"Command '{ctx.command}' is locked to months {human_months(allowed_months)}. "
            f"Invoking it in month {current_month!s} is {'allowed' if can_run else 'disallowed'}."
        )
        if can_run:
            return True
        else:
            raise InMonthCheckFailure(f"Command can only be used in {human_months(allowed_months)}")

    return commands.check(predicate) 
Example #11
Source File: decorators.py    From seasonalbot with MIT License 6 votes vote down vote up
def with_role(*role_ids: int) -> t.Callable:
    """Check to see whether the invoking user has any of the roles specified in role_ids."""
    async def predicate(ctx: Context) -> bool:
        if not ctx.guild:  # Return False in a DM
            log.debug(
                f"{ctx.author} tried to use the '{ctx.command.name}'command from a DM. "
                "This command is restricted by the with_role decorator. Rejecting request."
            )
            return False

        for role in ctx.author.roles:
            if role.id in role_ids:
                log.debug(f"{ctx.author} has the '{role.name}' role, and passes the check.")
                return True

        log.debug(
            f"{ctx.author} does not have the required role to use "
            f"the '{ctx.command.name}' command, so the request is rejected."
        )
        return False
    return commands.check(predicate) 
Example #12
Source File: karma.py    From rubbergod with GNU General Public License v3.0 5 votes vote down vote up
def vote(self, ctx, *args):
        if not await self.check.guild_check(ctx.message):
            await ctx.send(messages.server_warning)
        else:
            if ctx.message.channel.id == config.vote_room:
                try:
                    await ctx.message.delete()
                    await self.karma.emoji_vote_value(ctx.message)
                except discord.errors.Forbidden:
                    return
            else:
                dc_vote_room = discord.utils.get(ctx.guild.channels, id=config.vote_room)
                await ctx.send(utils.fill_message("vote_room_only", room=dc_vote_room)) 
Example #13
Source File: decorators.py    From seasonalbot with MIT License 5 votes vote down vote up
def in_month(*allowed_months: Month) -> t.Callable:
    """
    Universal decorator for season-locking commands and listeners alike.

    This only serves to determine whether the decorated callable is a command,
    a listener, or neither. It then delegates to either `in_month_command`,
    or `in_month_listener`, or raises TypeError, respectively.

    Please note that in order for this decorator to correctly determine whether
    the decorated callable is a cmd or listener, it **has** to first be turned
    into one. This means that this decorator should always be placed **above**
    the d.py one that registers it as either.

    This will decorate groups as well, as those subclass Command. In order to lock
    all subcommands of a group, its `invoke_without_command` param must **not** be
    manually set to True - this causes a circumvention of the group's callback
    and the seasonal check applied to it.
    """
    def decorator(callable_: t.Callable) -> t.Callable:
        # Functions decorated as commands are turned into instances of `Command`
        if isinstance(callable_, Command):
            logging.debug(f"Command {callable_.qualified_name} will be locked to {human_months(allowed_months)}")
            actual_deco = in_month_command(*allowed_months)

        # D.py will assign this attribute when `callable_` is registered as a listener
        elif hasattr(callable_, "__cog_listener__"):
            logging.debug(f"Listener {callable_.__qualname__} will be locked to {human_months(allowed_months)}")
            actual_deco = in_month_listener(*allowed_months)

        # Otherwise we're unsure exactly what has been decorated
        # This happens before the bot starts, so let's just raise
        else:
            raise TypeError(f"Decorated object {callable_} is neither a command nor a listener")

        return actual_deco(callable_)
    return decorator 
Example #14
Source File: checks.py    From EmoteCollector with GNU Affero General Public License v3.0 5 votes vote down vote up
def not_blacklisted():
	async def predicate(context):
		db = context.bot.cogs['Database']
		blacklist_reason = await db.get_user_blacklist(context.author.id)
		if blacklist_reason is None:
			return True
		raise BlacklistedError(context.prefix, blacklist_reason)

	return commands.check(predicate) 
Example #15
Source File: karma.py    From rubbergod with GNU General Public License v3.0 5 votes vote down vote up
def givingboard(self, ctx, start=1):
        if not await self.validate_leaderboard_offset(start, ctx):
            return

        await self.karma.leaderboard(ctx.message.channel, 'give', 'DESC', start)
        await self.check.botroom_check(ctx.message) 
Example #16
Source File: karma.py    From rubbergod with GNU General Public License v3.0 5 votes vote down vote up
def bajkarboard(self, ctx, start=1):
        if not await self.validate_leaderboard_offset(start, ctx):
            return

        await self.karma.leaderboard(ctx.message.channel, 'get', 'ASC', start)
        await self.check.botroom_check(ctx.message) 
Example #17
Source File: karma.py    From rubbergod with GNU General Public License v3.0 5 votes vote down vote up
def leaderboard(self, ctx, start=1):
        if not await self.validate_leaderboard_offset(start, ctx):
            return

        await self.karma.leaderboard(ctx.message.channel, 'get', 'DESC', start)
        await self.check.botroom_check(ctx.message) 
Example #18
Source File: checks.py    From EmoteCollector with GNU Affero General Public License v3.0 5 votes vote down vote up
def owner_or_permissions(**perms):
	"""Checks if the member is a bot owner or has any of the permissions necessary."""
	async def predicate(ctx):
		if await ctx.bot.is_owner(ctx.author):
			return True
		permissions = ctx.channel.permissions_for(ctx.author)
		return any(getattr(permissions, perm, None) == value
				   for perm, value in perms.items())
	return commands.check(predicate) 
Example #19
Source File: checks.py    From RubyRoseBot with Mozilla Public License 2.0 5 votes vote down vote up
def is_guild_owner():
    def predicate(ctx):
        if ctx.author.id == ctx.guild.owner_id:
            return True
        else:
            raise not_guild_owner
    return commands.check(predicate) 
Example #20
Source File: checks.py    From RubyRoseBot with Mozilla Public License 2.0 5 votes vote down vote up
def is_nsfw_channel():
    def predicate(ctx):
        if not isinstance(ctx.channel, discord.DMChannel) and ctx.channel.is_nsfw():
            return True
        else:
            raise not_nsfw_channel
    return commands.check(predicate) 
Example #21
Source File: checks.py    From modmail with GNU Affero General Public License v3.0 5 votes vote down vote up
def is_owner():
    def predicate(ctx):
        if ctx.author.id not in ctx.bot.config.owners:
            raise commands.NotOwner()
        else:
            return True

    return commands.check(predicate) 
Example #22
Source File: checks.py    From RubyRoseBot with Mozilla Public License 2.0 5 votes vote down vote up
def is_support():
    def predicate(ctx):
        if ctx.author.id in config.support_ids or ctx.author.id in config.dev_ids or ctx.author.id == config.owner_id:
            return True
        else:
            raise support_only
    return commands.check(predicate) 
Example #23
Source File: checks.py    From RubyRoseBot with Mozilla Public License 2.0 5 votes vote down vote up
def is_dev():
    def predicate(ctx):
        if ctx.author.id in config.dev_ids or ctx.author.id == config.owner_id:
            return True
        else:
            raise dev_only
    return commands.check(predicate) 
Example #24
Source File: checks.py    From RubyRoseBot with Mozilla Public License 2.0 5 votes vote down vote up
def is_owner():
    def predicate(ctx):
        if ctx.author.id == config.owner_id:
            return True
        else:
            raise owner_only
    return commands.check(predicate) 
Example #25
Source File: checks.py    From modmail with GNU Affero General Public License v3.0 5 votes vote down vote up
def is_admin():
    def predicate(ctx):
        if ctx.author.id not in ctx.bot.config.admins and ctx.author.id not in ctx.bot.config.owners:
            raise commands.NotOwner()
        else:
            return True

    return commands.check(predicate) 
Example #26
Source File: checks.py    From DHV3 with GNU Affero General Public License v3.0 5 votes vote down vote up
def is_channel_enabled():
    async def predicate(ctx):
        # await ctx.bot.wait_until_ready()
        cond = await ctx.bot.db.channel_is_enabled(ctx.channel)  # Coroutine
        ctx.logger.debug(f"Check for channel enabled returned {cond}")
        return cond

    return commands.check(predicate) 
Example #27
Source File: checks.py    From DHV3 with GNU Affero General Public License v3.0 5 votes vote down vote up
def is_server_admin():
    async def predicate(ctx):
        # await ctx.bot.wait_until_ready()
        cond = ctx.message.author.id in ctx.bot.admins  # User is super admin
        cond = cond or ctx.message.channel.permissions_for(ctx.message.author).administrator  # User have server administrator permission
        cond = cond or ctx.message.author.id in await ctx.bot.db.get_admins(ctx.guild)  # User is admin as defined in the database
        ctx.logger.debug(f"Check for admin returned {cond}")

        if cond:
            return True
        else:
            raise NotServerAdmin

    return commands.check(predicate) 
Example #28
Source File: checks.py    From DHV3 with GNU Affero General Public License v3.0 5 votes vote down vote up
def is_super_admin():
    async def predicate(ctx):
        # await ctx.bot.wait_until_ready()
        cond = ctx.message.author.id in ctx.bot.admins
        ctx.logger.debug(f"Check for super-admin returned {cond}")
        if cond:
            return True
        else:
            raise NotSuperAdmin

    return commands.check(predicate) 
Example #29
Source File: checks.py    From DHV3 with GNU Affero General Public License v3.0 5 votes vote down vote up
def is_ready():
    async def predicate(ctx):
        await ctx.bot.wait_until_ready()
        return True

    return commands.check(predicate) 
Example #30
Source File: checks.py    From modmail with GNU Affero General Public License v3.0 5 votes vote down vote up
def in_database():
    async def predicate(ctx):
        async with ctx.bot.pool.acquire() as conn:
            res = await conn.fetchrow("SELECT category FROM data WHERE guild=$1", ctx.guild.id)
        if not res or not res[0]:
            await ctx.send(
                embed=discord.Embed(
                    description=f"Your server has not been set up yet. Use `{ctx.prefix}setup` first.",
                    colour=ctx.bot.error_colour,
                )
            )
        return True if res and res[0] else False

    return commands.check(predicate)