Ejemplo n.º 1
0
    async def emboss(self,
                     ctx: context.Context,
                     image: typing.Optional[converters.ImageConverter],
                     radius: float = 3,
                     sigma: float = 1) -> None:
        """
        Converts the image to greyscale and creates a 3d effect.

        `image`: Can be a members name, id or @mention, an image url or an attachment.
        `radius`: Filter aperture size. Should be larger than sigma.
        `sigma`: Filter standard deviation. Should be lower than radius.
        """

        if radius < 0 or radius > 30:
            raise exceptions.ArgumentError(
                'Radius must be between `0` and `30`.')
        if sigma < 0 or sigma > 30:
            raise exceptions.ArgumentError(
                'Sigma must be between `0` and `30`.')

        async with ctx.channel.typing():
            embed = await self.bot.imaging.edit_image(ctx=ctx,
                                                      url=image,
                                                      edit_type='emboss',
                                                      radius=radius,
                                                      sigma=sigma)
            await ctx.send(embed=embed)
Ejemplo n.º 2
0
    async def charcoal(self,
                       ctx: context.Context,
                       image: typing.Optional[converters.ImageConverter],
                       radius: float = 1.5,
                       sigma: float = 0.5) -> None:
        """
        Redraw the image as if it were drawn with charcoal.

        `image`: Can be a members name, id or @mention, an image url or an attachment.
        `radius`: Filter aperture size. Should be larger than sigma.
        `sigma`: Filter standard deviation. Should be smaller than radius.
        """

        if radius < -10 or radius > 10:
            raise exceptions.ArgumentError(
                'Radius must be between `-10.0` and `10.0`.')

        if sigma < -5 or sigma > 5:
            raise exceptions.ArgumentError(
                'Sigma must be between `-5.0` and `5.0`.')

        async with ctx.channel.typing():
            embed = await self.bot.imaging.edit_image(ctx=ctx,
                                                      url=image,
                                                      edit_type='charcoal',
                                                      radius=radius,
                                                      sigma=sigma)
            await ctx.send(embed=embed)
Ejemplo n.º 3
0
    async def polaroid(self,
                       ctx: context.Context,
                       image: typing.Optional[converters.ImageConverter],
                       angle: float = 0.0,
                       *,
                       caption: str = None) -> None:
        """
        Puts the image in the center of a polaroid-like card.

        `image`: Can be a members name, id or @mention, an image url or an attachment.
        `angle`: The angle that the polaroid will be rotated at.
        `caption`: A caption that will appear on the polaroid.
        """

        if angle < -360 or angle > 360:
            raise exceptions.ArgumentError(
                'Angle must be between `-360` and `360`.')

        if caption and len(caption) > 100:
            raise exceptions.ArgumentError(
                'Caption must be `100` characters or less.')

        async with ctx.channel.typing():
            embed = await self.bot.imaging.edit_image(ctx=ctx,
                                                      url=image,
                                                      edit_type='polaroid',
                                                      angle=angle,
                                                      caption=caption)
            await ctx.send(embed=embed)
Ejemplo n.º 4
0
    async def kuwahara(self,
                       ctx: context.Context,
                       image: typing.Optional[converters.ImageConverter],
                       radius: float = 2,
                       sigma: float = 1.5) -> None:
        """
        Smooths the given image while preserving edges.

        `image`: Can be a members name, id or @mention, an image url or an attachment.
        `radius`: Filter aperture size.
        `sigma`: Filter standard deviation. Should be `0.5` lower than radius.
        """

        if radius < 0 or radius > 20:
            raise exceptions.ArgumentError(
                'Radius must be between `0` and `20`.')

        if sigma < 0 or sigma > 20:
            raise exceptions.ArgumentError(
                'Sigma must be between `0` and `20`.')

        async with ctx.channel.typing():
            embed = await self.bot.imaging.edit_image(ctx=ctx,
                                                      url=image,
                                                      edit_type='kuwahara',
                                                      radius=radius,
                                                      sigma=sigma)
            await ctx.send(embed=embed)
Ejemplo n.º 5
0
    async def sharpen(self,
                      ctx: context.Context,
                      image: typing.Optional[converters.ImageConverter],
                      radius: float = 8,
                      sigma: float = 4) -> None:
        """
        Sharpens the given image.

        `image`: Can be a members name, id or @mention, an image url or an attachment.
        `radius`: Filter aperture size. Should be larger than sigma.
        `sigma`: Filter standard deviation. Should be smaller than radius.
        """

        if radius < 0 or radius > 50:
            raise exceptions.ArgumentError(
                'Radius must be between `0` and `50`.')

        if sigma < 0 or sigma > 50:
            raise exceptions.ArgumentError(
                'Sigma must be between `0` and `50`.')

        async with ctx.channel.typing():
            embed = await self.bot.imaging.edit_image(ctx=ctx,
                                                      url=image,
                                                      edit_type='sharpen',
                                                      radius=radius,
                                                      sigma=sigma)
            await ctx.send(embed=embed)
Ejemplo n.º 6
0
Archivo: time.py Proyecto: vzymox/Life
    async def time(self, ctx: context.Context, *, timezone: str = None) -> None:
        """
        Displays the time of the member or the timezone provided.

        `timezone`: The timezone or members name, id or mention that you want to get.
        """

        if not timezone:
            member = ctx.author
            timezone = ctx.user_config.timezone

        else:
            try:
                member = None
                timezone = await converters.TimezoneConverter().convert(ctx=ctx, argument=timezone)
            except exceptions.ArgumentError as error:
                try:
                    member = await commands.MemberConverter().convert(ctx=ctx, argument=timezone)
                    user_config = self.bot.user_manager.get_user_config(user_id=member.id)
                    if user_config.timezone_private is True and member.id != ctx.author.id:
                        raise exceptions.ArgumentError('That users timezone is private.')
                    timezone = user_config.timezone
                except commands.BadArgument:
                    raise exceptions.ArgumentError(str(error))

        datetime = self.bot.utils.format_datetime(datetime=pendulum.now(tz=timezone), seconds=True)

        embed = discord.Embed(colour=ctx.colour, title=f'Time in {timezone.name} {f"({member})" if member else ""}', description=f'```py\n{datetime}\n```')
        await ctx.send(embed=embed)
Ejemplo n.º 7
0
Archivo: time.py Proyecto: vzymox/Life
    async def reminders_delete(self, ctx: context.Context, *, reminder_ids: str) -> None:
        """
        Deletes the reminder(s) with the given ID(s).

        `reminder_ids`: A list of reminders IDs to delete, separated by spaces.
        """

        reminder_ids_to_remove = []

        for reminder_id in reminder_ids.split(' '):

            try:
                reminder_id = int(reminder_id)
            except ValueError:
                raise exceptions.ArgumentError(f'`{reminder_id}` is not a valid reminder id.')

            reminder = await self.bot.user_manager.remind_manager.get_reminder(user_id=ctx.author.id, reminder_id=reminder_id)
            if not reminder:
                raise exceptions.ArgumentError(f'You do not have a reminder with the id `{reminder_id}`.')

            if reminder.id in reminder_ids_to_remove:
                raise exceptions.ArgumentError(f'You provided the reminder id `{reminder.id}` more than once.')

            reminder_ids_to_remove.append(reminder.id)

        for reminder_id in reminder_ids_to_remove:
            await self.bot.user_manager.remind_manager.delete_reminder(user_id=ctx.author.id, reminder_id=reminder_id)

        s = "s" if len(reminder_ids_to_remove) > 1 else ""
        await ctx.send(f'Deleted {len(reminder_ids_to_remove)} reminder{s} with id{s} {", ".join(f"`{reminder_id}`" for reminder_id in reminder_ids_to_remove)}.')
Ejemplo n.º 8
0
    async def birthday(self,
                       ctx: context.Context,
                       *,
                       person: converters.UserConverter = None) -> None:
        """
        Displays the birthday of you, or the member provided.

        `person`: The person to display the birthday of. Can be their name, id or mention. If this argument is not passed the command will display your birthday.
        """

        if person is None:
            person = ctx.author

        user_config = self.bot.user_manager.get_user_config(user_id=person.id)

        if user_config.birthday == pendulum.DateTime(
                2020, 1, 1, 0, 0, 0, tzinfo=pendulum.timezone('UTC')):
            raise exceptions.ArgumentError(
                f'`{person}` has not set their birthday.')
        if user_config.birthday_private and ctx.author.id != person.id:
            raise exceptions.ArgumentError(
                f'`{person}` has their birthday set to be private.')

        embed = discord.Embed(
            description=f'`{person.name}`**\'s birthday information:**\n\n'
            f'`Birthday:` {self.bot.utils.format_date(datetime=user_config.birthday)}\n'
            f'`Next birthday:` In {self.bot.utils.format_difference(datetime=user_config.next_birthday.subtract(days=1), suppress=[])}\n'
            f'`Age:` {user_config.age}\n',
            colour=user_config.colour)

        await ctx.send(embed=embed)
Ejemplo n.º 9
0
    async def paginate_choice(self, **kwargs) -> typing.Any:

        paginator = await self.paginate_embed(**kwargs)

        try:
            response = await self.bot.wait_for(
                'message',
                check=lambda msg: msg.author == self.author and msg.channel ==
                self.channel,
                timeout=30.0)
        except asyncio.TimeoutError:
            raise exceptions.ArgumentError('You took too long to respond.')

        response = await commands.clean_content().convert(
            ctx=self, argument=response.content)
        try:
            response = int(response) - 1
        except ValueError:
            raise exceptions.ArgumentError('That was not a valid number.')
        if response < 0 or response >= len(kwargs.get('entries')):
            raise exceptions.ArgumentError(
                'That was not one of the available options.')

        await paginator.stop()
        return kwargs.get('entries')[response]
Ejemplo n.º 10
0
    async def dev_blacklist_user_add(self,
                                     ctx: context.Context,
                                     user_id: int,
                                     *,
                                     reason: str = None):
        """
        Add a user to the blacklist.

        `user_id`: The users id.
        `reason`: Why the user is blacklisted.
        """

        try:
            user = await self.bot.fetch_user(user_id)
        except discord.NotFound:
            raise exceptions.ArgumentError(
                f'User with id `{user_id}` was not found.')

        if not reason:
            reason = user.name

        try:
            self.bot.user_blacklist[user.id] = reason
            await self.bot.db.execute(
                'INSERT INTO blacklist VALUES ($1, $2, $3)', user.id, 'user',
                reason)
            return await ctx.send(
                f'User: `{user.name} - {user.id}` has been blacklisted with reason `{reason}`'
            )

        except asyncpg.UniqueViolationError:
            raise exceptions.ArgumentError(
                f'User with id `{user.id}` is already blacklisted.')
Ejemplo n.º 11
0
    def parse_to_datetime(self,
                          *,
                          datetime_string: str,
                          timezone=pytz.UTC) -> typing.Tuple[str, dt.datetime]:

        settings = self.dateparser_settings.copy()
        if not timezone.zone == 'UTC':
            settings['TO_TIMEZONE'] = timezone.zone

        search = dateparser.search.search_dates(datetime_string,
                                                languages=['en'],
                                                settings=settings)

        if not search:

            search = ctparse.ctparse(datetime_string)

            if not search or not isinstance(search.resolution,
                                            ctparse.types.Time):
                raise exceptions.ArgumentError(
                    'I was not able to find a valid datetime within that query.'
                )

            return datetime_string, timezone.localize(search.resolution.dt)

        if len(search) > 1:
            raise exceptions.ArgumentError(
                'Two or more datetimes were detected within that query.')

        return search[0][0], search[0][1]
Ejemplo n.º 12
0
    async def todo_add(self, ctx: context.Context, *,
                       content: commands.clean_content):
        """
        Creates a todo.

        `content`: The content of your todo. Can not be more than 200 characters.
        """
        content = str(content)

        if len(content) > 100:
            raise exceptions.ArgumentError(
                'Your todo can not be more than 100 characters long.')

        todo_count = await self.bot.db.fetchrow(
            'SELECT count(*) as c FROM todos WHERE owner_id = $1',
            ctx.author.id)
        if todo_count['c'] > 100:
            raise exceptions.ArgumentError(
                f'You have too many todos, try doing some of them before adding more.'
            )

        query = 'INSERT INTO todos VALUES ($1, $2, $3, $4)'
        await self.bot.db.execute(query, ctx.author.id, datetime.now(),
                                  content, ctx.message.jump_url)

        embed = discord.Embed(title='Your todo was created.',
                              colour=ctx.colour)
        embed.add_field(name='Content:', value=content)
        return await ctx.send(embed=embed)
Ejemplo n.º 13
0
    async def tag_edit(self, ctx: context.Context, name: converters.TagName, *,
                       content: commands.clean_content) -> None:
        """
        Edit a tags content.

        `name`: The name of the tag to edit the content of.
        `content:` The content of the edited tag.
        """

        tag = await self.bot.db.fetchrow(
            'SELECT * FROM tags WHERE guild_id = $1 AND owner_id = $2 and name = $3',
            ctx.guild.id, ctx.author.id, name)
        if not tag:
            raise exceptions.ArgumentError(
                f'You do not have any tags in this server with the name `{name}`.'
            )

        if len(str(content)) > 1024:
            raise exceptions.ArgumentError(
                'Your tag content can not be more than 1024 characters.')

        await self.bot.db.execute(
            'UPDATE tags SET content = $1 WHERE guild_id = $2 AND name = $3',
            content, ctx.guild.id, name)

        embed = discord.Embed(colour=ctx.colour, title='Tag edited:')
        embed.add_field(name='Old content:',
                        value=f'{tag["content"]}',
                        inline=False)
        embed.add_field(name='New content:', value=f'{content}', inline=False)
        await ctx.send(embed=embed)
Ejemplo n.º 14
0
    async def tag_alias(self, ctx: context.Context, alias: converters.TagName,
                        original: converters.TagName) -> None:
        """
        Alias a name to a tag.

        `alias`: The alias of the tag you want.
        `name`: The name of the tag to point the alias at.
        """

        alias_tag = await self.bot.db.fetchrow(
            'SELECT * FROM tags WHERE guild_id = $1 AND alias = $2',
            ctx.guild.id, alias)
        if alias_tag:
            raise exceptions.ArgumentError(
                f'There is already a tag alias in this server with the name `{alias}`.'
            )

        original_tag = await self.bot.db.fetchrow(
            'SELECT * FROM tags WHERE guild_id = $1 AND name = $2',
            ctx.guild.id, original)
        if not original_tag:
            raise exceptions.ArgumentError(
                f'There are no tags in this server with the name `{original}`.'
            )

        query = 'INSERT INTO tags VALUES ($1, $2, $3, $4, $5, $6)'
        await self.bot.db.execute(query, ctx.author.id, ctx.guild.id, alias,
                                  None, original,
                                  pendulum.now(tz=pendulum.timezone('UTC')))

        embed = discord.Embed(colour=ctx.colour, title='Tag alias created:')
        embed.add_field(name='Alias:', value=f'{alias}', inline=False)
        embed.add_field(name='Links to:', value=f'{original}', inline=False)
        await ctx.send(embed=embed)
Ejemplo n.º 15
0
    async def tag_raw(self, ctx: context.Context, *,
                      name: converters.TagName) -> None:
        """
        Get a tags raw content.

        `name`: The name of the tag you want to find.
        """

        tags = await self.bot.db.fetch(
            'SELECT * FROM tags WHERE guild_id = $1 AND name % $2 ORDER BY name <-> $2 LIMIT 5',
            ctx.guild.id, name)
        if not tags:
            raise exceptions.ArgumentError(
                f'There are no tags in this server with the name `{name}`.')

        if not tags[0]['name'] == name:

            extra_msg = ''
            if len(tags) > 0:
                extras = '\n'.join([
                    f'`{index + 1}.` {tag["name"]}'
                    for index, tag in enumerate(tags[0:])
                ])
                extra_msg = f'Maybe you meant one of these?\n{extras}'

            raise exceptions.ArgumentError(
                f'There are no tags in this server with the name `{name}`. {extra_msg}'
            )

        if tags[0]['alias'] is not None:
            tags = await self.bot.db.fetch(
                'SELECT * FROM tags WHERE guild_id = $1 AND name = $2',
                ctx.guild.id, tags[0]['alias'])

        await ctx.send(discord.utils.escape_markdown(tags[0]['content']))
Ejemplo n.º 16
0
    async def tag_transfer(self, ctx: context.Context,
                           name: converters.TagName, *,
                           member: discord.Member) -> None:
        """
        Transfer a tag to another member.

        `name`: The name of the tag to transfer.
        `member`: The member to transfer the tag too. Can be a name, id or mention.
        """

        if member.bot:
            raise exceptions.ArgumentError(
                'You can not transfer tags to bots.')

        tag = await self.bot.db.fetchrow(
            'SELECT * FROM tags WHERE guild_id = $1 AND owner_id = $2 and name = $3',
            ctx.guild.id, ctx.author.id, name)
        if not tag:
            raise exceptions.ArgumentError(
                f'You do not have any tags in this server with the name `{name}`.'
            )

        await self.bot.db.execute(
            'UPDATE tags SET owner_id = $1 WHERE guild_id = $2 AND name = $3',
            member.id, ctx.guild.id, name)

        embed = discord.Embed(colour=ctx.colour, title='Tag transferred:')
        embed.add_field(name='Previous owner:',
                        value=f'{ctx.author.mention}',
                        inline=False)
        embed.add_field(name='New owner:',
                        value=f'{member.mention}',
                        inline=False)
        await ctx.send(embed=embed)
Ejemplo n.º 17
0
    async def edge(self,
                   ctx: context.Context,
                   image: typing.Optional[converters.ImageConverter],
                   radius: float = 3,
                   sigma: float = 1.5):
        """
        Outlines edges within an image.

        `image`: Can either be a direct image url, or a members name, id or mention.
        `radius`: Filter aperture size. Should be larger than sigma.
        `sigma`: Filter standard deviation. Should be lower than radius.
        """

        if radius < 0 or radius > 30:
            raise exceptions.ArgumentError(
                'Radius must be between `0` and `30`.')
        if sigma < 0 or sigma > 30:
            raise exceptions.ArgumentError(
                'Sigma must be between `0` and `30`.')

        async with ctx.channel.typing():
            embed = await self.bot.imaging.edit_image(ctx=ctx,
                                                      url=image,
                                                      edit_type='edge',
                                                      radius=radius,
                                                      sigma=sigma)
            return await ctx.send(embed=embed)
Ejemplo n.º 18
0
    async def dev_blacklist_guild_add(self, ctx: context.Context, guild_id: int, *, reason: str = None) -> None:
        """
        Add a guild to the blacklist.

        `guild`: The guild to add to the blacklist.
        `reason`: Reason why the guild is being blacklisted.
        """

        if 17 > guild_id > 20:
            raise exceptions.ArgumentError('That is not a valid guild id.')

        guild = self.bot.get_guild(guild_id)

        if guild:
            guild_name = guild.name
            if not reason:
                reason = f'{guild.name}'
        else:
            guild_name = 'Not found'
            if not reason:
                reason = 'No reason'

        guild_config = self.bot.guild_manager.get_guild_config(guild_id=guild_id)
        if guild_config.blacklisted is True:
            raise exceptions.ArgumentError(f'The guild `{guild_name} - {guild_id}` is already blacklisted.')

        await self.bot.guild_manager.edit_guild_config(guild_id=guild_id, attribute='blacklist', operation='set', value=reason)
        await ctx.send(f'The guild `{guild_name} - {guild_id}` is now blacklisted with reason:\n\n`{reason}`')
Ejemplo n.º 19
0
Archivo: dev.py Proyecto: vzymox/Life
    async def dev_blacklist_guild_remove(self, ctx: context.Context,
                                         guild_id: int) -> None:
        """
        Unblacklist a guild.

        `guild`: The guild to remove from the blacklist.
        """

        if 17 > guild_id > 20:
            raise exceptions.ArgumentError('That is not a valid guild id.')

        guild = self.bot.get_guild(guild_id)
        guild_name = guild.name if guild else 'Not found'

        guild_config = self.bot.guild_manager.get_guild_config(
            guild_id=guild_id)
        if guild_config.blacklisted is False:
            raise exceptions.ArgumentError(
                f'The guild `{guild_name} - {guild_id}` is not blacklisted.')

        await self.bot.guild_manager.edit_guild_config(
            guild_id=guild_id,
            editable=Editables.blacklist,
            operation=Operations.reset)
        await ctx.send(
            f'The guild `{guild_name} - {guild_id}` is now unblacklisted.')
Ejemplo n.º 20
0
    async def tag_claim(self, ctx: context.Context, *,
                        name: converters.TagName) -> None:
        """
        Claim a tag if it's owner has left the server.

        `name`: The name of the tag to claim.
        """

        tag = await self.bot.db.fetchrow(
            'SELECT * FROM tags WHERE guild_id = $1 AND name = $2',
            ctx.guild.id, name)
        if not tag:
            raise exceptions.ArgumentError(
                f'There are no tags in this server with the name `{name}`.')

        owner = ctx.guild.get_member(tag['owner_id'])
        if owner is not None:
            raise exceptions.ArgumentError(
                f'The owner of that tag is still in the server.')

        await self.bot.db.execute(
            'UPDATE tags SET owner_id = $1 WHERE guild_id = $2 AND name = $3',
            ctx.author.id, ctx.guild.id, name)

        embed = discord.Embed(colour=ctx.colour, title='Tag claimed:')
        embed.add_field(name='Previous owner:',
                        value=f'{tag["owner_id"]}',
                        inline=False)
        embed.add_field(name='New owner:',
                        value=f'{ctx.author.mention}',
                        inline=False)
        await ctx.send(embed=embed)
Ejemplo n.º 21
0
    async def tag_create(self, ctx: context.Context, name: converters.TagName,
                         *, content: commands.clean_content) -> None:
        """
        Create a tag.

        `name`: The name of the tag to create.
        `content`: The content of your tag.
        """

        tag = await self.bot.db.fetchrow(
            'SELECT * FROM tags WHERE guild_id = $1 AND name = $2',
            ctx.guild.id, name)
        if tag:
            raise exceptions.ArgumentError(
                f'There is already a tag in this server with the name `{name}`.'
            )

        if len(str(content)) > 1024:
            raise exceptions.ArgumentError(
                'Your tag content can not be more than 1024 characters.')

        query = 'INSERT INTO tags VALUES ($1, $2, $3, $4, $5, $6)'
        await self.bot.db.execute(query, ctx.author.id, ctx.guild.id, name,
                                  content, None,
                                  pendulum.now(tz=pendulum.timezone("UTC")))

        embed = discord.Embed(colour=ctx.colour, title='Tag created:')
        embed.add_field(name='Name:', value=f'{name}', inline=False)
        embed.add_field(name='Content:', value=f'{content}', inline=False)
        await ctx.send(embed=embed)
Ejemplo n.º 22
0
    async def config_colour(self,
                            ctx: context.Context,
                            operation: str = None,
                            *,
                            value: commands.ColourConverter = None) -> None:
        """
        Manage this server's colour settings.

        Please note that to view the colour, no permissions are needed, however to change it you require the `manage_guild` permission.

        If operation and value are not provided it will display the current colour.

        `operation`: The operation to perform, `set` to set the colour, `reset` to set it back to default and None for displaying the current colour.
        `value`: The colour to set it too. Can be in the format `0x<hex>`, `#<hex>`, `0x#<hex>` or a colour such as red, green, blue.
        """

        if not operation:
            await ctx.send(
                embed=discord.Embed(colour=ctx.guild_config.colour,
                                    title=str(ctx.guild_config.colour).upper())
            )
            return

        if await self.bot.is_owner(person=ctx.author) is False:
            await commands.has_guild_permissions(manage_guild=True
                                                 ).predicate(ctx=ctx)

        old_colour = ctx.guild_config.colour

        if operation not in ['set', 'reset']:
            raise exceptions.ArgumentError(
                f'That was not a valid operation. Use `set` or `reset`.')

        if operation == 'reset':
            await self.bot.guild_manager.edit_guild_config(
                guild_id=ctx.guild.id, attribute='colour', operation='reset')

        elif operation == 'set':

            if not value:
                raise exceptions.ArgumentError(
                    'You did not provide a valid colour argument. They can be `0x<hex>`, `#<hex>`, `0x#<hex>` or a colour such as red or green.'
                )

            await self.bot.guild_manager.edit_guild_config(
                guild_id=ctx.guild.id,
                attribute='colour',
                operation='set',
                value=f'0x{str(value).strip("#")}')

        await ctx.send(embed=discord.Embed(
            colour=old_colour, title=f'Old: {str(old_colour).upper()}'))
        await ctx.send(embed=discord.Embed(
            colour=ctx.guild_config.colour,
            title=f'New: {str(ctx.guild_config.colour).upper()}'))
Ejemplo n.º 23
0
    async def convert(self, ctx: context.Context, argument: str) -> str:

        argument = await super().convert(ctx, argument)
        argument = discord.utils.escape_markdown(argument)

        if not argument:
            raise commands.BadArgument

        if '`' in argument:
            raise exceptions.ArgumentError('Prefixes can not contain backtick characters.')
        if len(argument) > 15:
            raise exceptions.ArgumentError('Prefixes can not be more than 15 characters.')

        return argument
Ejemplo n.º 24
0
    async def todo_delete(self, ctx: context.Context, *, todo_ids: str):
        """
        Deletes a todo.

        `todo_ids`: The ids of the todos to delete. You can provide a list of ids and they will all be deleted.
        """

        todos = await self.bot.db.fetch(
            'SELECT * FROM todos WHERE owner_id = $1 ORDER BY time_added',
            ctx.author.id)
        if not todos:
            raise exceptions.ArgumentError('You do not have any todos.')

        todos = {index + 1: todo for index, todo in enumerate(todos)}
        todos_to_remove = []

        todo_ids = todo_ids.split(' ')
        for todo_id in todo_ids:

            try:
                todo_id = int(todo_id)
            except ValueError:
                todo_id = str(todo_id)

            if type(todo_id) == str:
                raise exceptions.ArgumentError(
                    f'`{todo_id}` is not a valid todo id.')
            if todo_id not in todos.keys():
                raise exceptions.ArgumentError(
                    f'You do not have a todo with the id `{todo_id}`.')
            if todo_id in todos_to_remove:
                raise exceptions.ArgumentError(
                    f'You provided the todo id `{todo_id}` more than once.')
            todos_to_remove.append(todo_id)

        query = 'DELETE FROM todos WHERE owner_id = $1 and time_added = $2'
        entries = [(todos[todo_id]['owner_id'], todos[todo_id]['time_added'])
                   for todo_id in todos_to_remove]
        await self.bot.db.executemany(query, entries)

        contents = '\n'.join([
            f'{todo_id}. {todos[todo_id]["todo"]}'
            for todo_id in todos_to_remove
        ])
        embed = discord.Embed(title=f'Deleted {len(todos_to_remove)} todo(s).',
                              colour=ctx.colour)
        embed.add_field(name='Contents:', value=contents)
        return await ctx.send(embed=embed)
Ejemplo n.º 25
0
    async def create_timecard(self, *, guild_id: int) -> io.BytesIO:

        guild = self.bot.get_guild(guild_id)

        configs = sorted(self.configs.items(),
                         key=lambda kv: kv[1].time.offset_hours)
        timezone_users = {}

        for user_id, config in configs:

            if config.timezone_private:
                continue

            user = guild.get_member(user_id)
            if not user:
                continue

            if timezone_users.get(config.time.format('HH:mm (ZZ)')) is None:
                timezone_users[config.time.format('HH:mm (ZZ)')] = [
                    io.BytesIO(await user.avatar_url_as(format='png',
                                                        size=256).read())
                ]

            else:
                timezone_users[config.time.format('HH:mm (ZZ)')].append(
                    io.BytesIO(await user.avatar_url_as(format='png',
                                                        size=256).read()))

        if not timezone_users:
            raise exceptions.ArgumentError(
                'There are no users with timezones set in this server.')

        buffer = await self.bot.loop.run_in_executor(
            None, self.create_timecard_image, timezone_users)
        return buffer
Ejemplo n.º 26
0
    async def config_prefix_delete(self, ctx: context.Context, prefix: converters.Prefix) -> None:
        """
        Delete a prefix from this server.

        You must have the `manage server` permission to use this command.

        `prefix`: The prefix to delete.
        """

        if not ctx.guild_config.prefixes:
            raise exceptions.ArgumentError(f'This server does not have any custom prefixes.')
        if prefix not in ctx.guild_config.prefixes:
            raise exceptions.ArgumentError(f'This server does not have the `{prefix}` prefix.')

        await self.set_guild_config(ctx=ctx, attribute='prefix', value=prefix, operation='remove')
        await ctx.send(f'Removed `{prefix}` from this servers prefixes.')
Ejemplo n.º 27
0
Archivo: tags.py Proyecto: vzymox/Life
    async def tag_info(self, ctx: context.Context, *,
                       name: converters.TagConverter) -> None:
        """
        Displays information about a tag.

        `name`: The name of the tag to get the information for.
        """

        tag = await self.bot.db.fetchrow(
            'SELECT * FROM tags WHERE guild_id = $1 AND name = $2',
            ctx.guild.id, name)
        if not tag:
            raise exceptions.ArgumentError(
                f'There are no tags in this server with the name `{name}`.')

        owner = ctx.guild.get_member(tag['owner_id'])

        embed = discord.Embed(colour=ctx.colour,
                              description=f'**{tag["name"]}**')
        embed.description = f'`Owner:` {owner.mention if owner else "None"} ({tag["owner_id"]})\n`Claimable:` {owner is None}\n`Alias:` {tag["alias"]}'
        embed.set_footer(
            text=
            f'Created on {self.bot.utils.format_datetime(datetime=tag["created_at"])}'
        )
        await ctx.send(embed=embed)
Ejemplo n.º 28
0
    async def tag_list(self,
                       ctx: context.Context,
                       *,
                       member: discord.Member = None) -> None:
        """
        Get a list of yours or someones else's tags.

        `member`: The member to get a tag list for. Can be a name, id or mention.
        """

        if not member:
            member = ctx.author

        tags = await self.bot.db.fetch(
            'SELECT * FROM tags WHERE guild_id = $1 and owner_id = $2',
            ctx.guild.id, member.id)
        if not tags:
            raise exceptions.ArgumentError(
                f'`{member}` has no tags in this server.')

        entries = [
            f'`{index + 1}.` {tag["name"]}' for index, tag in enumerate(tags)
        ]
        await ctx.paginate_embed(entries=entries,
                                 per_page=25,
                                 title=f'{member}\'s tags')
Ejemplo n.º 29
0
    async def tag_delete(self, ctx: context.Context, *,
                         name: converters.TagName) -> None:
        """
        Delete a tag.

        `name`: The name of the tag to delete.
        """

        tag = await self.bot.db.fetchrow(
            'SELECT * FROM tags WHERE guild_id = $1 AND owner_id = $2 AND name = $3',
            ctx.guild.id, ctx.author.id, name)
        if not tag:
            raise exceptions.ArgumentError(
                f'You do not have any tags in this server with the name `{name}`.'
            )

        await self.bot.db.execute(
            'DELETE FROM tags WHERE guild_id = $1 AND owner_id = $2 AND name = $3',
            ctx.guild.id, ctx.author.id, name)
        await self.bot.db.execute(
            'DELETE FROM tags WHERE guild_id = $1 AND alias = $2',
            ctx.guild.id, name)

        embed = discord.Embed(colour=ctx.colour, title='Tag deleted:')
        embed.add_field(name='Name:', value=f'{name}', inline=False)
        embed.add_field(name='Content:',
                        value=f'{tag["content"]}',
                        inline=False)
        await ctx.send(embed=embed)
Ejemplo n.º 30
0
    async def icon(self,
                   ctx: context.Context,
                   *,
                   guild: guild_converter.Guild = None):
        """
        Displays a servers icon.

        `guild`: The server of which to get the icon for. Can be it's ID or Name. Defaults to the current server.
        """

        if not guild:
            guild = ctx.guild

        if not guild.icon:
            raise exceptions.ArgumentError(
                f'The server `{guild}` does not have an icon.')

        embed = discord.Embed(colour=ctx.colour, title=f"{guild.name}'s icon")
        embed.description = f'[PNG]({guild.icon_url_as(format="png")}) | [JPEG]({guild.icon_url_as(format="jpeg")}) | [WEBP]({guild.icon_url_as(format="webp")})'
        embed.set_image(url=str(guild.icon_url_as(format='png')))

        if guild.is_icon_animated():
            embed.description += f' | [GIF]({guild.icon_url_as(format="gif")})'
            embed.set_image(
                url=str(guild.icon_url_as(size=1024, format='gif')))

        return await ctx.send(embed=embed)