Exemple #1
0
    async def predicate(ctx: commands.Context):
        db = await Database.connect()
        perms = await db.player_permissions.get(ctx)

        ctx.author = await ctx.guild.fetch_member(ctx.author.id) or ctx.author

        if not perms.has_author_permission(ctx, perms.admin):
            raise PlayerPermissionError(permission='Admin')
        else:
            return True
Exemple #2
0
 async def distort(self, ctx: commands.Context,
                   link: Optional[Union[PartialEmoji, Member, str]]):
     """
     creates a distorted version of an image, works with direct upload and
     image link
     IMPORTANT: image link needs to end in a filename (gif,png,jpg)
     """
     message = ctx.message
     if message.attachments:
         url = str(message.attachments[0].url)
         filetype = url[url.rfind('.') + 1:]
         pos = url.rfind("/")
         filename = url[pos + 1:]
         if filetype.lower() not in self.allowed_file_extensions:
             await ctx.send(
                 "not allowed filetype only images or gifs allowed")
             return
         await message.attachments[0].save(f"data/{filename}")
     else:
         if link is None:
             return await ctx.send(
                 "Please provide either a direct link to an image, "
                 "a custom emote or a user mention/user id or upload a picture"
             )
         elif isinstance(link, PartialEmoji):
             filetype = str(link.url)[str(link.url).rfind("."):]
             filename = f"{link.name}{filetype}"
             await link.url.save(f"data/{filename}")
         elif isinstance(link, Member):
             ctx.author = link
             await ctx.invoke(self._me)
             return
         else:
             try:
                 async with self.session.get(url=link) as r:
                     filetype = r.headers["Content-Type"].split("/")[1]
                     filename = f"{uuid.uuid4()}.{filetype}"
                     if filetype.lower(
                     ) not in self.allowed_file_extensions:
                         await ctx.send(
                             "not allowed filetype only images or gifs allowed"
                         )
                         return
                     if r.status == 200:
                         with open(f"data/{filename}", "wb") as f:
                             buffer = io.BytesIO(await r.read())
                             f.write(buffer.read())
             except aiohttp.InvalidURL:
                 await ctx.send(
                     "this command only works with custom emojis, direct image links or usernames or mentions."
                 )
                 return
     async with ctx.typing():
         output_file = await self.spawn_magick(filename, f".{filetype}")
         await self.send_if_possible_and_delete(ctx, output_file)
Exemple #3
0
    async def add_(self, ctx: commands.Context, member: MemberOrID, *,
                   reason: str) -> None:
        """Warn a user

        Can also be used as `warn <member> [reason]`"""
        if get_perm_level(member, await self.bot.db.get_guild_config(
                ctx.guild.id))[0] >= get_perm_level(
                    ctx.author, await self.bot.db.get_guild_config(ctx.guild.id
                                                                   ))[0]:
            await ctx.send('User has insufficient permissions')
        else:
            guild_config = await self.bot.db.get_guild_config(ctx.guild.id)
            guild_warns = guild_config.warns
            warn_punishments = guild_config.warn_punishments
            warn_punishment_limits = [i.warn_number for i in warn_punishments]
            warns = list(
                filter(lambda w: w['member_id'] == str(member.id),
                       guild_warns))

            cmd = None
            punish = False

            num_warns = len(warns) + 1
            fmt = f'You have been warned in **{ctx.guild.name}**, reason: {reason}. This is warning #{num_warns}.'

            if warn_punishments:
                punishments = list(
                    filter(lambda x: int(x) == num_warns,
                           warn_punishment_limits))
                if not punishments:
                    punish = False
                    above = list(
                        filter(lambda x: int(x) > num_warns,
                               warn_punishment_limits))
                    if above:
                        closest = min(map(int, above))
                        cmd = warn_punishments.get_kv('warn_number',
                                                      closest).punishment
                        if cmd == 'ban':
                            cmd = 'bann'
                        fmt += f' You will be {cmd}ed on warning {closest}.'
                else:
                    punish = True
                    cmd = warn_punishments.get_kv(
                        'warn_number', max(map(int, punishments))).punishment
                    if cmd == 'ban':
                        cmd = 'bann'
                    fmt += f' You have been {cmd}ed from the server.'

            try:
                await member.send(fmt)
            except discord.Forbidden:
                if ctx.author != ctx.guild.me:
                    await ctx.send(
                        'The user has PMs disabled or blocked the bot.')
            finally:
                guild_config = await self.bot.db.get_guild_config(ctx.guild.id)
                current_date = (ctx.message.created_at + timedelta(
                    hours=guild_config.time_offset)).strftime('%Y-%m-%d')
                if len(guild_warns) == 0:
                    case_number = 1
                else:
                    case_number = guild_warns[-1]['case_number'] + 1
                push = {
                    'case_number': case_number,
                    'date': current_date,
                    'member_id': str(member.id),
                    'moderator_id': str(ctx.author.id),
                    'reason': reason
                }
                await self.bot.db.update_guild_config(
                    ctx.guild.id, {'$push': {
                        'warns': push
                    }})
                if ctx.author != ctx.guild.me:
                    await ctx.send(self.bot.accept)
                await self.send_log(ctx, member, reason, case_number)

                # apply punishment
                if punish:
                    if cmd == 'bann':
                        cmd = 'ban'
                    ctx.command = self.bot.get_command(cmd)
                    ctx.author = ctx.guild.me
                    await ctx.invoke(ctx.command,
                                     member,
                                     reason=f'Hit warn limit {num_warns}')
Exemple #4
0
    async def _flags(self, ctx: commands.Context, member: typing.Optional[discord.Member]):
        """
        display a user's flags

        defaults to your own

        examples:
            `>flags`
            `>flags 310418322384748544`
        """

        author = ctx.author

        if (member):
            ctx = copy.copy(ctx)
            ctx.author = member

        flags = list()

        if (checks.is_owner_check(ctx)):
            flags.append("owner")

        if (checks.is_supervisor_check(ctx)):
            flags.append("supervisor")

        if (checks.is_support_check(ctx)):
            flags.append("support team")

        if (checks.is_alpha_check(ctx)):
            flags.append("alpha tester")

        if (checks.is_beta_check(ctx)):
            flags.append("beta tester")

        if (checks.is_dj_check(ctx)):
            flags.append("dj")

        if (ctx.author.id in ctx.bot._settings.whitelist):
            flags.append("whitelisted")

        if (ctx.author.id in ctx.bot._settings.blacklist):
            flags.append("blacklisted")

        if (not flags):
            await ctx.send("no results")
            return

        message = ", ".join(flags)

        color = ctx.me.color if ctx.guild else discord.Color.blurple()
        e = discord.Embed(color=color)
        e.add_field(name="Flags for {0}".format(ctx.author), value=message)
        e.set_footer(
            text = "{0} | {1}".format(
                author.name,
                format.humanize_datetime()
            ),
            icon_url=author.avatar_url
        )

        await ctx.send(embed=e)
    async def cog_before_invoke(self, ctx: commands.Context):
        """ Command before-invoke handler. """
        guild_check = ctx.guild is not None
        ctx.author = await ctx.guild.fetch_member(ctx.author.id) or ctx.author

        return guild_check