Example #1
0
    async def predicate(ctx):
        if ctx.author.id in Configuration.get_master_key("hard_coded_devs"):
            return True

        cooldown_pybass = Configuration.get_master_key("cooldown_bypass",
                                                       error=False)
        if cooldown_pybass:
            if ctx.author.id in cooldown_pybass["users"]:
                return True
            elif ctx.guild.id in cooldown_pybass["servers"]:
                return True
            elif ctx.channel.id in cooldown_pybass["channels"]:
                return True

        cd = await ctx.bot.redis.pttl(
            f"{ctx.author.id}-{ctx.guild.id}-{ctx.command.qualified_name}")
        if cd == -2:

            await ctx.bot.redis.execute(
                "SET",
                f"{ctx.author.id}-{ctx.guild.id}-{ctx.command.qualified_name}",
                "cooldown",
                "EX",
                cooldown,
            )
            return True

        raise commands.CommandOnCooldown(retry_after=cd / 1000, cooldown=None)
Example #2
0
    async def _create_muted_role(self, ctx):
        # Creating roles can take sooooo f*****g much time. Better release the pool.
        await ctx.release()

        bucket = self._mute_role_create_cooldowns.get_bucket(ctx.message)
        if not bucket.get_tokens():
            retry_after = bucket.update_rate_limit() or 0
            raise commands.CommandOnCooldown(bucket, retry_after)

        if not await ctx.ask_confirmation(
                'No `muted` role found. Create a new one?',
                delete_after=False):
            await ctx.send(
                f'A `muted` role couldn\'t be found. Set one with `{ctx.clean_prefix}setmuterole Role`'
            )
            return None

        bucket.update_rate_limit()
        async with ctx.typing():
            ctx.__new_mute_role_message__ = await ctx.send(
                'Creating `muted` role. Please wait...')
            role = await ctx.guild.create_role(
                name='Vale.py-Muted',
                color=discord.Color.red(),
                reason='Creating new muted role')

            with contextlib.suppress(discord.HTTPException):
                await role.edit(position=ctx.me.top_role.position - 1)

            await self._regen_muted_role_perms(role, *ctx.guild.channels)
            await ctx.acquire()
            await self._update_muted_role(ctx.guild, role, ctx.db)
            return role
Example #3
0
 async def minecraftAPI(self, ctx, *, user):
     """Searches minecraft players."""
     uuid = await self.getMinecraftUUID(user)
     if not uuid:
         raise commands.BadArgument(message='User not found')
     history = await REST(f"https://api.mojang.com/user/profiles/{uuid['id']}/names")
     names = []
     user = history[-1]['name']
     for i in range(len(history)):
         names.append(history[i]['name'])
         # Escape special markdown characters
         names[i] = names[i].replace('*', '\\*').replace('_', '\\_').replace('~', '\\~')
     names.reverse()
     names[0] += ' **[CURRENT]**'
     skin = await self.getMinecraftSkinUrl(uuid['id'])
     if not skin:
         raise commands.CommandOnCooldown(commands.BucketType.default, 10)
     embed = discord.Embed(title='Minecraft User', colour=0x82540f)
     embed.set_author(name=user)
     embed.set_thumbnail(url='attachment://head.png')
     embed.add_field(name='Name history', value='\n'.join(names), inline=False)
     embed.add_field(name='UUID', value=uuid['id'], inline=False)
     try:
         embed.add_field(name='Skin URL', value='[Click me]('+skin['textures']['SKIN']['url']+')')
         await skinRenderer2D(skin['textures']['SKIN']['url'])
         await headRenderer(skin['textures']['SKIN']['url'])
         skinFile = discord.File(f"skins/2d/{skin['textures']['SKIN']['url'].split('/')[-1]}.png", filename='skin.png')
         headFile = discord.File(f"skins/head/{skin['textures']['SKIN']['url'].split('/')[-1]}.png", filename='head.png')
     except:
         # TODO: Try to find a official steve skin in mojang's skin server
         await skinRenderer2D('https://gamepedia.cursecdn.com/minecraft_gamepedia/3/37/Steve_skin.png')
         await headRenderer('https://gamepedia.cursecdn.com/minecraft_gamepedia/3/37/Steve_skin.png')
         skinFile = discord.File('skins/2d/Steve_skin.png', filename='skin.png')
         headFile = discord.File('skins/head/Steve_skin.png', filename='head.png')
     embed.set_footer(text='\U00002063', icon_url='https://minecraft.net/favicon-96x96.png')
     embed.set_image(url='attachment://skin.png')
     embed.timestamp = datetime.utcnow()
     
     # Minecraft Cape
     cape = False
     if 'CAPE' in skin['textures']:
         cape = discord.Embed(title='Minecraft Cape', colour=0x82540f)
         cape.set_author(name=user, icon_url='attachment://head.png')
         cape.set_image(url=skin['textures']['CAPE']['url'])
         headFile2 = discord.File(f"skins/head/{skin['textures']['SKIN']['url'].split('/')[-1]}.png", filename='head.png')
     
     # Optifine Cape
     OF = False
     OFCape = await REST(f"http://s.optifine.net/capes/{user}.png", returns='status')
     if OFCape == 200:
         OF = discord.Embed(title='Optifine Cape', colour=0x82540f)
         OF.set_author(name=user, icon_url='attachment://head.png')
         OF.set_image(url=f"http://s.optifine.net/capes/{user}.png")
         headFile3 = discord.File(f"skins/head/{skin['textures']['SKIN']['url'].split('/')[-1]}.png", filename='head.png')
     await ctx.send(files=[skinFile, headFile], embed=embed)
     
     if cape:
         await ctx.send(file=headFile2, embed=cape)
     if OF:
         await ctx.send(file=headFile3, embed=OF)
Example #4
0
    def __call__(self, ctx: commands.Context):
        if (ctx.command.name in (
                "bird",
                "song",
                "goatsucker",
                "check",
                "skip",
        ) and database.exists("cooldown:global")
                and int(database.get("cooldown:global")) > 1):
            bucket = self.rate_limit_mapping.get_bucket(ctx.message)

        elif not self.disable and ctx.guild is None:
            bucket = self.dm_mapping.get_bucket(ctx.message)

        elif ctx.channel.name.startswith(
                "racing") and ctx.command.name.startswith("check"):
            bucket = self.race_mapping.get_bucket(ctx.message)

        else:
            bucket = self.default_mapping.get_bucket(ctx.message)

        retry_after = bucket.update_rate_limit()
        if retry_after:
            raise commands.CommandOnCooldown(bucket, retry_after)
        return True
Example #5
0
 async def check_for_answer_questions(self, msg: discord.Message,
                                      min_tiers: list) -> bool:
     if msg.author.bot:
         return False
     if (len(msg.clean_content) > 100
             and not min_tiers["min_g_t1"]) or (len(msg.clean_content) > 200
                                                and min_tiers["min_g_t1"]):
         return False
     if msg.guild is not None:
         if self.bot.log.get_guild_chat_channel(
                 msg.guild) != msg.channel.id:
             if msg.guild.me not in msg.mentions:
                 return False
     # if msg.guild is not None:
     #   muted = self.bot.log.get_guild_muted(msg.guild)
     #   if muted == 1 or muted is True:
     #     return False
     # if not await self.global_chat_checks(msg):
     #   return False
     bucket_minute, bucket_hour = self.spam_control_minute.get_bucket(
         msg), self.spam_control_hour.get_bucket(msg)
     current = msg.created_at.replace(
         tzinfo=datetime.timezone.utc).timestamp()
     retry_after_minute, retry_after_hour = bucket_minute.update_rate_limit(
         current), bucket_hour.update_rate_limit(current)
     if (retry_after_minute or
             retry_after_hour):  # and msg.author.id != self.bot.owner_id:
         raise commands.CommandOnCooldown(bucket_minute, retry_after_minute)
         return False
     return True
Example #6
0
    async def bot_check(self, ctx):
        if ctx.invoked_with.lower() == "help":
            return True

        bucket = self.cd.get_bucket(ctx.message)
        if retry_after := bucket.update_rate_limit():
            raise commands.CommandOnCooldown(bucket, retry_after)
Example #7
0
    async def _create_muted_role(self, ctx):
        # Needs to be released as the process of creating a new role
        # and creating the overwrites can take a hell of a long time
        await ctx.release()

        bucket = self._mute_role_create_cooldowns.get_bucket(ctx.message)
        if not bucket.get_tokens():
            retry_after = bucket.update_rate_limit() or 0  # e d g e c a s e s
            raise commands.CommandOnCooldown(bucket, retry_after)

        if not await ctx.ask_confirmation(
                'No muted role found. Create a new one?', delete_after=False):
            await ctx.send("A muted role couldn't be found. "
                           f'Set one with `{ctx.clean_prefix}setmuterole Role`'
                           )
            return None

        bucket.update_rate_limit()
        async with ctx.typing():
            ctx.__new_mute_role_message__ = await ctx.send(
                'Creating muted role. Please wait...')
            role = await ctx.guild.create_role(
                name='Chiaki-Muted',
                colour=discord.Colour.red(),
                reason='Creating new muted role')

            with contextlib.suppress(discord.HTTPException):
                await role.edit(position=ctx.me.top_role.position - 1)

            await self._regen_muted_role_perms(role, *ctx.guild.channels)
            await ctx.acquire()
            await self._update_muted_role(ctx.guild, role, ctx.db)
            return role
Example #8
0
    async def predicate(ctx):
        data = getattr(ctx, "character_data", None)
        if not data:
            alliance = await ctx.bot.pool.fetchval(
                'SELECT alliance FROM guild WHERE "id"=(SELECT guild FROM profile WHERE'
                ' "user"=$1);',
                ctx.author.id,
            )
        else:
            guild = data["guild"]
            alliance = await ctx.bot.pool.fetchval(
                'SELECT alliance FROM guild WHERE "id"=$1;', guild)

        command_ttl = await ctx.bot.redis.execute_command(
            "TTL", f"alliancecd:{alliance}:{ctx.command.qualified_name}")
        if command_ttl == -2:
            await ctx.bot.redis.execute_command(
                "SET",
                f"alliancecd:{alliance}:{ctx.command.qualified_name}",
                ctx.command.qualified_name,
                "EX",
                cooldown,
            )
            return True
        else:
            raise commands.CommandOnCooldown(ctx, command_ttl,
                                             commands.BucketType.guild)
Example #9
0
async def global_cooldown(ctx):
    """Global bot cooldown to prevent spam."""
    bucket = ctx.bot.global_cd.get_bucket(ctx.message)
    retry_after = bucket.update_rate_limit()
    if retry_after:
        raise commands.CommandOnCooldown(bucket, retry_after)
    else:
        return True
Example #10
0
    async def before_invoke(self, ctx: commands.Context):
        """Proper rate limiting to avoid abuse"""
        await ctx.trigger_typing()

        for cd in self.cds:
            bucket = cd.get_bucket(ctx.message)
            if retry_after := bucket.update_rate_limit():
                raise commands.CommandOnCooldown(cd, retry_after)
Example #11
0
    async def cog_check(self, ctx):
        bucket = self._cd.get_bucket(ctx.message)
        retry_after = bucket.update_rate_limit()

        if retry_after:
            raise commands.CommandOnCooldown(self._cd, retry_after)
        else:
            return True
Example #12
0
    async def global_cooldown(self, ctx: commands.Context):
        bucket = self.config.cooldown.get_bucket(ctx.message)
        retry_after = bucket.update_rate_limit()

        if retry_after:
            raise commands.CommandOnCooldown(bucket, retry_after)
        else:
            return True
Example #13
0
    async def cog_check(self, ctx):
        if not ctx.guild:
            raise commands.NoPrivateMessage()

        bucket = self.cd_mapping.get_bucket(ctx.message)
        retry_after = bucket.update_rate_limit()
        if retry_after:
            raise commands.CommandOnCooldown(bucket, retry_after)
        return True
Example #14
0
 async def predicate(ctx):
     if ctx.invoked_with.lower() == 'help':
         return True
     key = f"cooldown:{ctx.author.id}:{ctx.command.qualified_name}"
     cooldown = await ctx.redis.ttl(key)
     if cooldown > 0:
         raise commands.CommandOnCooldown(None, cooldown)
     await ctx.redis.set(key, 1, expire=seconds)
     return True
Example #15
0
 async def global_cooldown(self, ctx):
     if ctx.invoked_with == self.help_command.command_attrs.get(
             'name', 'help'):
         return True
     bucket = self._cd.get_bucket(ctx.message)
     retry_after = bucket.update_rate_limit()
     if retry_after:
         raise commands.CommandOnCooldown(bucket, retry_after)
     return True
Example #16
0
    async def bot_check(self, ctx):
        if ctx.invoked_with.lower() in ("help", "market", "auction"):
            return True

        bucket = self.cd.get_bucket(ctx.message)
        retry_after = bucket.update_rate_limit()
        if retry_after:
            raise commands.CommandOnCooldown(bucket, retry_after)

        return True
Example #17
0
 async def cog_check(self, ctx):
     if not ctx.guild:
         raise commands.NoPrivateMessage()
     if not ctx.author.guild_permissions.administrator:
         raise AdminPermsRequiredError()
     bucket = self.cd_mapping.get_bucket(ctx.message)
     retry_after = bucket.update_rate_limit()
     if retry_after:
         raise commands.CommandOnCooldown(bucket, retry_after)
     return True
Example #18
0
 async def cog_check(self, ctx):
     bucket = self._cd.get_bucket(ctx.message)
     retry_after = bucket.update_rate_limit()
     if retry_after:
         if ctx.author.id == self.bot.owner:
             return True
         cooldown = FakeCoolDown(1, 30, commands.BucketType.user)
         raise commands.CommandOnCooldown(cooldown,
                                          bucket.get_retry_after())
     return True
Example #19
0
    async def __call__(self, ctx: commands.Context):
        isPremium = await ctx.bot.Hamood.user_is_premium(ctx.author.id)
        mapping = self.premium_mapping if isPremium else self.regular_mapping
        bucket = mapping.get_bucket(ctx.message)

        retry_after = bucket.update_rate_limit()
        if retry_after:
            raise commands.CommandOnCooldown(bucket, retry_after)

        return True
Example #20
0
    async def predicate(ctx):
        user_cooldown = await ctx.bot.redis.pttl(
            f"{ctx.author.id}-{ctx.command.qualified_name}"
        )
        if user_cooldown == -2:
            return True

        raise commands.CommandOnCooldown(
            retry_after=user_cooldown / 1000, cooldown=None
        )
Example #21
0
    async def cooldown_check(ctx):
        if ctx.guild.id == 291184728944410624:
            bucket = _cd_rw_guild.get_bucket(ctx.message)
        else:
            bucket = _cd.get_bucket(ctx.message)

        retry_after = bucket.update_rate_limit()
        if retry_after:
            raise commands.CommandOnCooldown(bucket, retry_after)
        return True
Example #22
0
    async def _check_api_cooldowns(self, ctx: NewCtx):
        """Waits and complies with the api's rate limit"""
        msg = ctx.message

        bucket = aiojikan.API_COOLDOWNS.long.get_bucket(msg)

        if retry_after := bucket.update_rate_limit():
            if retry_after >= 5.0:
                raise commands.CommandOnCooldown(bucket, retry_after)
            await asyncio.sleep(retry_after)
Example #23
0
async def cooldown_check(ctx):
    """Global bot cooldown to prevent spam"""
    # prevent users getting rate limited when help command does filter_commands()
    if str(ctx.invoked_with).lower() == "help":
        return True

    bucket = ctx.bot.global_cd.get_bucket(ctx.message)
    retry_after = bucket.update_rate_limit()
    if retry_after:
        raise commands.CommandOnCooldown(bucket, retry_after)
    return True
Example #24
0
    def __call__(self, ctx: commands.Context):
        mapping = self.premium_mapping if self.is_premium(
            ctx) else self.default_mapping
        bucket = mapping.get_bucket(ctx.message)

        retry_after = bucket.update_rate_limit()
        if retry_after:
            error = commands.CommandOnCooldown(bucket, retry_after)
            error.premium = mapping is self.premium_mapping
            error.premium_mapping = self.premium_mapping
            raise error
        return True
Example #25
0
 def __call__(self, ctx: commands.Context):
     bucket = self.default_mapping.get_bucket(ctx.message)
     retry_after = bucket.update_rate_limit()
     # check if TooEarly but not in cache
     print(GuildCache.data)
     if ctx.guild.id not in GuildCache.data:
         GuildCache[ctx.guild.id] = -1
     if GuildCache[ctx.guild.id] == -1:
         return True
     if retry_after:
         raise commands.CommandOnCooldown(bucket, retry_after)
     return True
Example #26
0
    async def lookup_from_message(
        self,
        ctx: commands.Context[Erasmus],
        message: discord.Message,
        /,
    ) -> None:
        try:
            verse_ranges = VerseRange.get_all_from_string(
                message.content,
                only_bracketed=self.bot.user not in message.mentions,
            )

            if len(verse_ranges) == 0:
                return

            bucket = self._user_cooldown.get_bucket(ctx.message)
            assert bucket is not None

            retry_after = bucket.update_rate_limit()

            if retry_after:
                raise commands.CommandOnCooldown(
                    bucket, retry_after, commands.BucketType.user
                )

            async with ctx.typing():
                async with Session() as session:
                    user_bible = await BibleVersion.get_for_user(
                        session, ctx.author, ctx.guild
                    )

                    for i, verse_range in enumerate(verse_ranges):
                        if i > 0:
                            bucket.update_rate_limit()

                        bible: BibleVersion | None = None

                        if isinstance(verse_range, Exception):
                            raise verse_range

                        if verse_range.version is not None:
                            bible = await BibleVersion.get_by_abbr(
                                session, verse_range.version
                            )

                        if bible is None:
                            bible = user_bible

                        await self.__lookup(ctx, bible, verse_range)
        except Exception as exc:
            await self.cog_command_error(ctx, exc)
            await self.bot.on_command_error(ctx, exc)
Example #27
0
    def cog_check(self, ctx: Union[Context, SlashContext]) -> Literal[True]:
        """
		F**k you Khalooody.
		"""
        if ctx.invoked_with == "help":
            return True

        bucket = self._cd.get_bucket(ctx.message)
        retry_after = bucket.update_rate_limit()
        if retry_after:
            raise commands.CommandOnCooldown(bucket, retry_after)

        return True
Example #28
0
 def predicate(ctx):
     cooldown_end = cooldown_actions.get_cooldown_end_time(
         ctx.message.author)
     if cooldown_end is None:
         return True
     else:
         now = int(time.time())
         if not now > cooldown_end:
             seconds_remaining = cooldown_end - now
             raise commands.CommandOnCooldown(commands.cooldown(1, 900),
                                              seconds_remaining)
         else:
             return True
Example #29
0
    async def cog_before_invoke(self, ctx: core.Context):

        await ctx.author.send('applied rate limits')

        for cd in self.aiojikan.api_cooldowns:
            bucket = cd.get_bucket(ctx.message)
            retry_after = bucket.update_rate_limit()

            if retry_after:
                if retry_after < 3:
                    await asyncio.sleep(retry_after)
                else:
                    raise commands.CommandOnCooldown(bucket, retry_after)
Example #30
0
    async def bot_check(self, ctx):
        if ctx.invoked_with.lower() in ("help", "market", "auction"):
            return True

        if (await self.bot.mongo.db.blacklist.count_documents(
            {"_id": ctx.author.id}) > 0):
            raise Blacklisted

        bucket = self.cd.get_bucket(ctx.message)
        retry_after = bucket.update_rate_limit()
        if retry_after:
            raise commands.CommandOnCooldown(bucket, retry_after)

        return True