Exemple #1
0
    def predicate(ctx: Context) -> bool:
        """Check if command was issued in a blacklisted context."""
        not_blacklisted = not in_whitelist_check(
            ctx, channels, categories, roles, fail_silently=True)
        overridden = in_whitelist_check(ctx,
                                        roles=override_roles,
                                        fail_silently=True)

        success = not_blacklisted or overridden

        if not success and not fail_silently:
            raise NotInBlacklistCheckFailure(redirect)

        return success
Exemple #2
0
    async def user_info(
            self,
            ctx: Context,
            user_or_message: Union[MemberOrUser, Message] = None) -> None:
        """Returns info about a user."""
        if isinstance(user_or_message, Message):
            user = user_or_message.author
        else:
            user = user_or_message

        if user is None:
            user = ctx.author

        # Do a role check if this is being executed on someone other than the caller
        elif user != ctx.author and await has_no_roles_check(
                ctx, *constants.MODERATION_ROLES):
            await ctx.send(
                "You may not use this command on users other than yourself.")
            return

        # Will redirect to #bot-commands if it fails.
        if in_whitelist_check(ctx,
                              roles=constants.STAFF_PARTNERS_COMMUNITY_ROLES):
            embed = await self.create_user_embed(ctx, user)
            await ctx.send(embed=embed)
Exemple #3
0
 def test_in_whitelist_check_complex(self):
     """`in_whitelist_check` test with multiple parameters"""
     self.ctx.author.roles = (MagicMock(id=1), MagicMock(id=2))
     self.ctx.channel.category_id = 3
     self.ctx.channel.id = 5
     self.assertTrue(
         checks.in_whitelist_check(self.ctx,
                                   channels=[1],
                                   categories=[8],
                                   roles=[2]))
Exemple #4
0
 def cog_check(self, ctx: commands.Context) -> bool:
     """Only allow moderators to invoke the commands in this cog."""
     checks = [
         with_role_check(ctx, *constants.MODERATION_ROLES),
         in_whitelist_check(
             ctx,
             channels=[constants.Channels.dm_log],
             redirect=None,
             fail_silently=True,
         )
     ]
     return all(checks)
Exemple #5
0
 def cog_check(self, ctx: Context) -> bool:
     """Only allow moderators inside moderator channels to invoke the commands in this cog."""
     checks = [
         with_role_check(ctx, *constants.MODERATION_ROLES),
         in_whitelist_check(
             ctx,
             channels=constants.MODERATION_CHANNELS,
             categories=[constants.Categories.modmail],
             redirect=None,
             fail_silently=True,
         )
     ]
     return all(checks)
Exemple #6
0
 def predicate(ctx: Context) -> bool:
     """Check if command was issued in a whitelisted context."""
     return in_whitelist_check(ctx, channels, categories, roles, redirect,
                               fail_silently)
    def predicate(ctx: Context) -> bool:
        kwargs = default_kwargs.copy()
        allow_dms = False

        # Update kwargs based on override
        if hasattr(ctx.command.callback, "override"):
            # Handle DM invocations
            allow_dms = ctx.command.callback.override_dm

            # Remove default kwargs if reset is True
            if ctx.command.callback.override_reset:
                kwargs = {}
                log.debug(
                    f"{ctx.author} called the '{ctx.command.name}' command and "
                    f"overrode default checks."
                )

            # Merge overwrites and defaults
            for arg in ctx.command.callback.override:
                default_value = kwargs.get(arg)
                new_value = ctx.command.callback.override[arg]

                # Skip values that don't need merging, or can't be merged
                if default_value is None or isinstance(arg, int):
                    kwargs[arg] = new_value

                # Merge containers
                elif isinstance(default_value, Container):
                    if isinstance(new_value, Container):
                        kwargs[arg] = (*default_value, *new_value)
                    else:
                        kwargs[arg] = new_value

            log.debug(
                f"Updated default check arguments for '{ctx.command.name}' "
                f"invoked by {ctx.author}."
            )

        if ctx.guild is None:
            log.debug(f"{ctx.author} tried using the '{ctx.command.name}' command from a DM.")
            result = allow_dms
        else:
            log.trace(f"Calling whitelist check for {ctx.author} for command {ctx.command.name}.")
            result = in_whitelist_check(ctx, fail_silently=True, **kwargs)

        # Return if check passed
        if result:
            log.debug(
                f"{ctx.author} tried to call the '{ctx.command.name}' command "
                f"and the command was used in an overridden context."
            )
            return result

        log.debug(
            f"{ctx.author} tried to call the '{ctx.command.name}' command. "
            f"The whitelist check failed."
        )

        # Raise error if the check did not pass
        channels = set(kwargs.get("channels") or {})
        categories = kwargs.get("categories")

        # Only output override channels + community_bot_commands
        if channels:
            default_whitelist_channels = set(WHITELISTED_CHANNELS)
            default_whitelist_channels.discard(Channels.community_bot_commands)
            channels.difference_update(default_whitelist_channels)

        # Add all whitelisted category channels, but skip if we're in DMs
        if categories and ctx.guild is not None:
            for category_id in categories:
                category = ctx.guild.get_channel(category_id)
                if category is None:
                    continue

                channels.update(channel.id for channel in category.text_channels)

        if channels:
            channels_str = ", ".join(f"<#{c_id}>" for c_id in channels)
            message = f"Sorry, but you may only use this command within {channels_str}."
        else:
            message = "Sorry, but you may not use this command."

        raise InChannelCheckFailure(message)
Exemple #8
0
 def test_in_whitelist_check_fail_silently(self):
     """`in_whitelist_check` test no exception raised if `fail_silently` is `True`"""
     self.assertFalse(checks.in_whitelist_check(self.ctx, roles=[2, 6], fail_silently=True))
Exemple #9
0
 def test_in_whitelist_check_incorrect_role(self):
     """`in_whitelist_check` raises InWhitelistCheckFailure if there's no role match."""
     self.ctx.author.roles = (MagicMock(id=1), MagicMock(id=2))
     with self.assertRaises(InWhitelistCheckFailure):
         checks.in_whitelist_check(self.ctx, roles=[4])
Exemple #10
0
 def test_in_whitelist_check_correct_role(self):
     """`in_whitelist_check` returns `True` if any of the `Context.author.roles` are in the roles list."""
     self.ctx.author.roles = (MagicMock(id=1), MagicMock(id=2))
     self.assertTrue(checks.in_whitelist_check(self.ctx, roles=[2, 6]))
Exemple #11
0
 def test_in_whitelist_check_incorrect_category(self):
     """`in_whitelist_check` raises InWhitelistCheckFailure if there's no category match."""
     self.ctx.channel.category_id = 3
     with self.assertRaises(InWhitelistCheckFailure):
         checks.in_whitelist_check(self.ctx, categories=[4])
Exemple #12
0
 def test_in_whitelist_check_correct_category(self):
     """`in_whitelist_check` returns `True` if `Context.channel.category_id` is in the category list."""
     category_id = 3
     self.ctx.channel.category_id = category_id
     self.assertTrue(checks.in_whitelist_check(self.ctx, categories=[category_id]))
Exemple #13
0
 def test_in_whitelist_check_incorrect_channel(self):
     """`in_whitelist_check` raises InWhitelistCheckFailure if there's no channel match."""
     self.ctx.channel.id = 3
     with self.assertRaises(InWhitelistCheckFailure):
         checks.in_whitelist_check(self.ctx, [4])
Exemple #14
0
 def test_in_whitelist_check_correct_channel(self):
     """`in_whitelist_check` returns `True` if `Context.channel.id` is in the channel list."""
     channel_id = 3
     self.ctx.channel.id = channel_id
     self.assertTrue(checks.in_whitelist_check(self.ctx, [channel_id]))
Exemple #15
0
            user = user_or_message.author
        else:
            user = user_or_message

        if user is None:
            user = ctx.author

        # Do a role check if this is being executed on someone other than the caller
        elif user != ctx.author and await has_no_roles_check(
                ctx, *constants.MODERATION_ROLES):
            await ctx.send(
                "You may not use this command on users other than yourself.")
            return

        # Will redirect to #bot-commands if it fails.
        if in_whitelist_check(ctx,
                              roles=constants.STAFF_PARTNERS_COMMUNITY_ROLES):
            embed = await self.create_user_embed(ctx, user, passed_as_message)
            await ctx.send(embed=embed)

    async def create_user_embed(self, ctx: Context, user: MemberOrUser,
                                passed_as_message: bool) -> Embed:
        """Creates an embed containing information on the `user`."""
        on_server = bool(await get_or_fetch_member(ctx.guild, user.id))

        created = discord_timestamp(user.created_at, TimestampFormats.RELATIVE)

        name = str(user)
        if on_server and user.nick:
            name = f"{user.nick} ({name})"
        name = escape_markdown(name)