Пример #1
0
def test_without_role_check_without_unwanted_role(context):
    context.guild = True
    role = MagicMock()
    role.id = 42
    context.author.roles = (role,)

    assert checks.without_role_check(context, role.id + 10)
Пример #2
0
 def bot_check(ctx: Context) -> bool:
     """Block any command within the verification channel that is not !accept."""
     if ctx.channel.id == constants.Channels.verification and without_role_check(
             ctx, *constants.MODERATION_ROLES):
         return ctx.command.name == "accept"
     else:
         return True
Пример #3
0
    async def new_reminder(self, ctx: Context, expiration: Duration, *, content: str) -> t.Optional[discord.Message]:
        """
        Set yourself a simple reminder.

        Expiration is parsed per: http://strftime.org/
        """
        embed = discord.Embed()

        # If the user is not staff, we need to verify whether or not to make a reminder at all.
        if without_role_check(ctx, *STAFF_ROLES):

            # If they don't have permission to set a reminder in this channel
            if ctx.channel.id not in WHITELISTED_CHANNELS:
                embed.colour = discord.Colour.red()
                embed.title = random.choice(NEGATIVE_REPLIES)
                embed.description = "Sorry, you can't do that here!"

                return await ctx.send(embed=embed)

            # Get their current active reminders
            active_reminders = await self.bot.api_client.get(
                'bot/reminders',
                params={
                    'author__id': str(ctx.author.id)
                }
            )

            # Let's limit this, so we don't get 10 000
            # reminders from kip or something like that :P
            if len(active_reminders) > MAXIMUM_REMINDERS:
                embed.colour = discord.Colour.red()
                embed.title = random.choice(NEGATIVE_REPLIES)
                embed.description = "You have too many active reminders!"

                return await ctx.send(embed=embed)

        # Now we can attempt to actually set the reminder.
        reminder = await self.bot.api_client.post(
            'bot/reminders',
            json={
                'author': ctx.author.id,
                'channel_id': ctx.message.channel.id,
                'jump_url': ctx.message.jump_url,
                'content': content,
                'expiration': expiration.isoformat()
            }
        )

        now = datetime.utcnow() - timedelta(seconds=1)
        humanized_delta = humanize_delta(relativedelta(expiration, now))

        # Confirm to the user that it worked.
        await self._send_confirmation(
            ctx,
            on_success=f"Your reminder will arrive in {humanized_delta}!",
            reminder_id=reminder["id"],
            delivery_dt=expiration,
        )

        self.schedule_task(reminder["id"], reminder)
Пример #4
0
    async def _check_mentions(ctx: Context, mentions: t.Iterable[Mentionable]) -> t.Tuple[bool, str]:
        """
        Returns whether or not the list of mentions is allowed.

        Conditions:
        - Role reminders are Mods+
        - Reminders for other users are Helpers+

        If mentions aren't allowed, also return the type of mention(s) disallowed.
        """
        if without_role_check(ctx, *STAFF_ROLES):
            return False, "members/roles"
        elif without_role_check(ctx, *MODERATION_ROLES):
            return all(isinstance(mention, discord.Member) for mention in mentions), "roles"
        else:
            return True, ""
Пример #5
0
    async def new_reminder(self, ctx: Context, expiration: ExpirationDate, *,
                           content: str):
        """
        Set yourself a simple reminder.
        """

        embed = Embed()

        # If the user is not staff, we need to verify whether or not to make a reminder at all.
        if without_role_check(ctx, *STAFF_ROLES):

            # If they don't have permission to set a reminder in this channel
            if ctx.channel.id not in WHITELISTED_CHANNELS:
                embed.colour = Colour.red()
                embed.title = random.choice(NEGATIVE_REPLIES)
                embed.description = "Sorry, you can't do that here!"

                return await ctx.send(embed=embed)

            # Get their current active reminders
            active_reminders = await self.bot.api_client.get(
                'bot/reminders', params={'user__id': str(ctx.author.id)})

            # Let's limit this, so we don't get 10 000
            # reminders from kip or something like that :P
            if len(active_reminders) > MAXIMUM_REMINDERS:
                embed.colour = Colour.red()
                embed.title = random.choice(NEGATIVE_REPLIES)
                embed.description = "You have too many active reminders!"

                return await ctx.send(embed=embed)

        # Now we can attempt to actually set the reminder.
        reminder = await self.bot.api_client.post('bot/reminders',
                                                  json={
                                                      'author':
                                                      ctx.author.id,
                                                      'channel_id':
                                                      ctx.message.channel.id,
                                                      'content':
                                                      content,
                                                      'expiration':
                                                      expiration.isoformat()
                                                  })

        # Confirm to the user that it worked.
        await self._send_confirmation(
            ctx, on_success="Your reminder has been created successfully!")

        loop = asyncio.get_event_loop()
        self.schedule_task(loop, reminder["id"], reminder)
Пример #6
0
 async def predicate(ctx: Context) -> bool:
     return without_role_check(ctx, *role_ids)
Пример #7
0
 def test_without_role_check_returns_true_without_unwanted_role(self):
     """`without_role_check` returns `True` if `Context.author` does not have unwanted role."""
     role_id = 42
     self.ctx.author.roles.append(MockRole(id=role_id))
     self.assertTrue(checks.without_role_check(self.ctx, role_id + 10))
Пример #8
0
 def test_without_role_check_returns_false_with_unwanted_role(self):
     """`without_role_check` returns `False` if `Context.author` has unwanted role."""
     role_id = 42
     self.ctx.author.roles.append(MockRole(id=role_id))
     self.assertFalse(checks.without_role_check(self.ctx, role_id))
Пример #9
0
 def test_without_role_check_without_guild(self):
     """`without_role_check` should return `False` when `Context.guild` is None."""
     self.ctx.guild = None
     self.assertFalse(checks.without_role_check(self.ctx))
Пример #10
0
def test_without_role_check_without_guild(context):
    context.guild = None

    assert not checks.without_role_check(context)
Пример #11
0
    async def new_reminder(self, ctx: Context, mentions: Greedy[Mentionable],
                           expiration: Duration, *, content: str) -> None:
        """
        Set yourself a simple reminder.

        Expiration is parsed per: http://strftime.org/
        """
        # If the user is not staff, we need to verify whether or not to make a reminder at all.
        if without_role_check(ctx, *STAFF_ROLES):

            # If they don't have permission to set a reminder in this channel
            if ctx.channel.id not in WHITELISTED_CHANNELS:
                await send_denial(ctx, "Sorry, you can't do that here!")
                return

            # Get their current active reminders
            active_reminders = await self.bot.api_client.get(
                'bot/reminders', params={'author__id': str(ctx.author.id)})

            # Let's limit this, so we don't get 10 000
            # reminders from kip or something like that :P
            if len(active_reminders) > MAXIMUM_REMINDERS:
                await send_denial(ctx, "You have too many active reminders!")
                return

        # Remove duplicate mentions
        mentions = set(mentions)
        mentions.discard(ctx.author)

        # Filter mentions to see if the user can mention members/roles
        if not await self.validate_mentions(ctx, mentions):
            return

        mention_ids = [mention.id for mention in mentions]

        # Now we can attempt to actually set the reminder.
        reminder = await self.bot.api_client.post('bot/reminders',
                                                  json={
                                                      'author':
                                                      ctx.author.id,
                                                      'channel_id':
                                                      ctx.message.channel.id,
                                                      'jump_url':
                                                      ctx.message.jump_url,
                                                      'content':
                                                      content,
                                                      'expiration':
                                                      expiration.isoformat(),
                                                      'mentions':
                                                      mention_ids,
                                                  })

        now = datetime.utcnow() - timedelta(seconds=1)
        humanized_delta = humanize_delta(relativedelta(expiration, now))
        mention_string = (f"Your reminder will arrive in {humanized_delta} "
                          f"and will mention {len(mentions)} other(s)!")

        # Confirm to the user that it worked.
        await self._send_confirmation(
            ctx,
            on_success=mention_string,
            reminder_id=reminder["id"],
            delivery_dt=expiration,
        )

        self.schedule_reminder(reminder)
Пример #12
0
    async def new_reminder(self, ctx: Context, duration: str, *, content: str):
        """
        Set yourself a simple reminder.
        """

        embed = Embed()

        # If the user is not staff, we need to verify whether or not to make a reminder at all.
        if without_role_check(ctx, *STAFF_ROLES):

            # If they don't have permission to set a reminder in this channel
            if ctx.channel.id not in WHITELISTED_CHANNELS:
                embed.colour = Colour.red()
                embed.title = random.choice(NEGATIVE_REPLIES)
                embed.description = "Sorry, you can't do that here!"

                return await ctx.send(embed=embed)

            # Get their current active reminders
            response = await self.bot.http_session.get(
                url=URLs.site_reminders_user_api.format(user_id=ctx.author.id),
                headers=self.headers)

            active_reminders = await response.json()

            # Let's limit this, so we don't get 10 000
            # reminders from kip or something like that :P
            if len(active_reminders) > MAXIMUM_REMINDERS:
                embed.colour = Colour.red()
                embed.title = random.choice(NEGATIVE_REPLIES)
                embed.description = "You have too many active reminders!"

                return await ctx.send(embed=embed)

        # Now we can attempt to actually set the reminder.
        try:
            response = await self.bot.http_session.post(
                url=URLs.site_reminders_api,
                headers=self.headers,
                json={
                    "user_id": str(ctx.author.id),
                    "duration": duration,
                    "content": content,
                    "channel_id": str(ctx.channel.id)
                })

            response_data = await response.json()

        # AFAIK only happens if the user enters, like, a quintillion weeks
        except ClientResponseError:
            embed.colour = Colour.red()
            embed.title = random.choice(NEGATIVE_REPLIES)
            embed.description = (
                "An error occurred while adding your reminder to the database. "
                "Did you enter a reasonable duration?")

            log.warn(
                f"User {ctx.author} attempted to create a reminder for {duration}, but failed."
            )

            return await ctx.send(embed=embed)

        # Confirm to the user whether or not it worked.
        failed = await self._send_confirmation(
            ctx,
            response_data,
            on_success="Your reminder has been created successfully!")

        # If it worked, schedule the reminder.
        if not failed:
            loop = asyncio.get_event_loop()
            reminder = response_data["reminder"]

            self.schedule_task(loop, reminder["id"], reminder)