Python discord.ext.commands.Paginator() Examples

The following are 12 code examples of discord.ext.commands.Paginator(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module discord.ext.commands , or try the search function .
Example #1
Source File: cog_base.py    From jishaku with MIT License 6 votes vote down vote up
def jsk_tasks(self, ctx: commands.Context):
        """
        Shows the currently running jishaku tasks.
        """

        if not self.tasks:
            return await ctx.send("No currently running tasks.")

        paginator = commands.Paginator(max_size=1985)

        for task in self.tasks:
            paginator.add_line(f"{task.index}: `{task.ctx.command.qualified_name}`, invoked at "
                               f"{task.ctx.message.created_at.strftime('%Y-%m-%d %H:%M:%S')} UTC")

        interface = PaginatorInterface(ctx.bot, paginator, owner=ctx.author)
        return await interface.send_to(ctx) 
Example #2
Source File: awaiter.py    From RulesBot with MIT License 6 votes vote down vote up
def guild_role(self, text: str, check=lambda role: True, list_ids=False) -> Role:
        async def converter(mes: Message):
            return discord.utils.get(self.guild.roles,
                                     id=int(mes.content.translate(digit_keeper)))

        if list_ids:
            guild: Guild = self.ctx.guild
            paginator = Paginator()
            for role in guild.roles:
                paginator.add_line(role.name + ' ' + str(role.id))

            for page in paginator.pages:
                await self.ctx.send(
                    embed=Embed(
                        color=Color.blurple(),
                        description=page))
        return await self.by_converter(
            text,
            check=check,
            converter=converter) 
Example #3
Source File: information.py    From bot with MIT License 5 votes vote down vote up
def raw(self, ctx: Context, *, message: Message, json: bool = False) -> None:
        """Shows information about the raw API response."""
        # I *guess* it could be deleted right as the command is invoked but I felt like it wasn't worth handling
        # doing this extra request is also much easier than trying to convert everything back into a dictionary again
        raw_data = await ctx.bot.http.get_message(message.channel.id, message.id)

        paginator = Paginator()

        def add_content(title: str, content: str) -> None:
            paginator.add_line(f'== {title} ==\n')
            # replace backticks as it breaks out of code blocks. Spaces seemed to be the most reasonable solution.
            # we hope it's not close to 2000
            paginator.add_line(content.replace('```', '`` `'))
            paginator.close_page()

        if message.content:
            add_content('Raw message', message.content)

        transformer = pprint.pformat if json else self.format_fields
        for field_name in ('embeds', 'attachments'):
            data = raw_data[field_name]

            if not data:
                continue

            total = len(data)
            for current, item in enumerate(data, start=1):
                title = f'Raw {field_name} ({current}/{total})'
                add_content(title, transformer(item))

        for page in paginator.pages:
            await ctx.send(page) 
Example #4
Source File: help.py    From xenon with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, **options):
        self.sort_commands = options.pop('sort_commands', True)
        self.commands_heading = options.pop('commands_heading', "Commands")
        self.dm_help = options.pop('dm_help', False)
        self.dm_help_threshold = options.pop('dm_help_threshold', 1000)
        self.aliases_heading = options.pop('aliases_heading', "Aliases:")
        self.no_category = options.pop('no_category', 'No Category')
        self.paginator = options.pop('paginator', None)

        if self.paginator is None:
            self.paginator = cmd.Paginator(suffix=None, prefix=None)

        super().__init__(**options) 
Example #5
Source File: cmds.py    From Discord-SelfBot with MIT License 5 votes vote down vote up
def cmds(self, ctx):
        """Show all custom commands."""
        if ctx.invoked_subcommand is None:
            ttl = None if ctx.message.content.endswith(' stay') else 20
            p = commands.Paginator(prefix='```css')
            cmds = read_json("commands")
            p.add_line('[List of Custom Commands]')
            msg = []
            for cmd in sorted(cmds):
                msg.append(cmd)
                if cmd == list(sorted(cmds))[-1] or len(msg) % 5 == 0 and len(msg) != 0:
                    p.add_line(', '.join(x for x in msg))
                    msg = []
            for page in p.pages:
                await ctx.send(page, delete_after=ttl)
            await ctx.message.delete()

    # List all custom commands with Links 
Example #6
Source File: cmds.py    From Discord-SelfBot with MIT License 5 votes vote down vote up
def long(self, ctx):
        """Display also their content"""
        ttl = None if ctx.message.content.endswith(' stay') else 20
        p = commands.Paginator(prefix='```css')
        cmds = read_json("commands")
        p.add_line('[List of Custom Commands]')
        width = len(max(cmds, key=len))
        for cmd in sorted(cmds):
            p.add_line('{0:<{width}}| {1}'.format(cmd, cmds.get(cmd), width=width))
        for page in p.pages:
            await ctx.send(page, delete_after=ttl)
        await ctx.message.delete() 
Example #7
Source File: exception_handling.py    From jishaku with MIT License 5 votes vote down vote up
def send_traceback(destination: discord.abc.Messageable, verbosity: int, *exc_info):
    """
    Sends a traceback of an exception to a destination.
    Used when REPL fails for any reason.

    :param destination: Where to send this information to
    :param verbosity: How far back this traceback should go. 0 shows just the last stack.
    :param exc_info: Information about this exception, from sys.exc_info or similar.
    :return: The last message sent
    """

    # to make pylint stop moaning
    etype, value, trace = exc_info

    traceback_content = "".join(traceback.format_exception(etype, value, trace, verbosity)).replace("``", "`\u200b`")

    paginator = commands.Paginator(prefix='```py')
    for line in traceback_content.split('\n'):
        paginator.add_line(line)

    message = None

    for page in paginator.pages:
        message = await destination.send(page)

    return message 
Example #8
Source File: help_command.py    From jishaku with MIT License 5 votes vote down vote up
def __init__(self, **options):
        paginator = options.pop('paginator', commands.Paginator(max_size=1985))

        super().__init__(paginator=paginator, **options) 
Example #9
Source File: help_command.py    From jishaku with MIT License 5 votes vote down vote up
def __init__(self, **options):
        paginator = options.pop('paginator', commands.Paginator(prefix=None, suffix=None, max_size=1985))

        super().__init__(paginator=paginator, **options) 
Example #10
Source File: paginators.py    From jishaku with MIT License 5 votes vote down vote up
def __init__(self, bot: commands.Bot, paginator: commands.Paginator, **kwargs):
        if not isinstance(paginator, commands.Paginator):
            raise TypeError('paginator must be a commands.Paginator instance')

        self._display_page = 0

        self.bot = bot

        self.message = None
        self.paginator = paginator

        self.owner = kwargs.pop('owner', None)
        self.emojis = kwargs.pop('emoji', EMOJI_DEFAULT)
        self.timeout = kwargs.pop('timeout', 7200)
        self.delete_message = kwargs.pop('delete_message', False)

        self.sent_page_reactions = False

        self.task: asyncio.Task = None
        self.send_lock: asyncio.Event = asyncio.Event()
        self.update_lock: asyncio.Lock = asyncio.Semaphore(value=kwargs.pop('update_max', 2))

        if self.page_size > self.max_page_size:
            raise ValueError(
                f'Paginator passed has too large of a page size for this interface. '
                f'({self.page_size} > {self.max_page_size})'
            ) 
Example #11
Source File: info.py    From RulesBot with MIT License 5 votes vote down vote up
def roles(self, ctx: CommandContext):
        guild: Guild = ctx.guild
        paginator = Paginator()
        for role in guild.roles:
            paginator.add_line(role.name + ' ' + str(role.id))

        for page in paginator.pages:
            await ctx.send(
                embed=Embed(
                    color=Color.blurple(),
                    description=page)) 
Example #12
Source File: dev_cog.py    From Firetail with MIT License 5 votes vote down vote up
def codeblock(contents, syntax="py"):
    """Returns a list of codeblock text for the given content.

    Content is broken into items with a character limitation to avoid
    going above single-message limits.
    """
    paginator = commands.Paginator(
        prefix='```{}'.format(syntax), max_size=2000)
    for line in contents.split('\n'):
        for wrapline in textwrap.wrap(line, width=1990):
            paginator.add_line(wrapline.rstrip().replace('`', '\u200b`'))
    return paginator.pages