robertwayne / dpymenus

Simplified menus for discord.py developers.
https://dpymenus.com/
MIT License
26 stars 4 forks source link

Have a List Worth of Content - Paginate Content? #41

Closed shubhamshah02 closed 3 years ago

shubhamshah02 commented 3 years ago

Hey there, I have a list of content I want to display but its not a static amount. The list can be 10 items, or 30 items etc and so how would I have embed pagination where I can have like 10 items per page for instance. Thank you!

robertwayne commented 3 years ago

Unfortunately I haven't wired up code to automate this yet. You can manually chunk your page and generate a list of pages pretty easily however.

Here is a working example:

import random

from discord.ext import commands
from dpymenus import Page, PaginatedMenu

class MyPaginatedMenu(commands.Cog):
    def __init__(self, client):
        self.client = client

    @commands.command()
    async def test(self, ctx):
        data = generate_list_of_random_strings()  # generate 1 to 100 random strings as pseudo-data
        paginated = split_data(data, 10)  # paginate our data in chunks of 10
        pages = []

        for index, chunk in enumerate(paginated):
            page = Page(title=f'Page {index + 1} of {len(paginated)}')  # define a new page for each chunk
            for item in chunk:
                page.add_field(name='Data', value=item)  # add each data point to a separate field
            pages.append(page)

        menu = PaginatedMenu(ctx)
        menu.add_pages(pages)
        await menu.open()

def setup(client):
    client.add_cog(MyPaginatedMenu(client))

def generate_list_of_random_strings():
    r = random.randint(1, 100)
    return [f'This is random data {i}.' for i in range(r)]

def split_data(data, chunk_size):
    return [data[i:i + chunk_size] for i in range(0, len(data), chunk_size)]

Basically you take your data source of any size, use a method like I wrote above split_data to chunk it out as a list of lists. You can iterate over that list and then each sublist, generating each page programmatically however you want. The above code should be self-explanatory, and you should be able to copy/paste it into your own bot for testing pretty easily.

If you have any questions, let me know.

shubhamshah02 commented 3 years ago

Awesome help, worked great! Thanks a lot for your hard work :)