How to loop with a reaction embed menu

I’ve created an easy enough to use ‘book-manager’. If you put all of your menuus into a list called pages you can use this function:

async def createbook(bot, ctx, title, pages, **kwargs):

        header = kwargs.get("header", "") # String
        results = kwargs.get("results", 0) # Int
        
        pagenum = 1

        def get_results():
            results_min = (pagenum - 1) * 8 + 1
            if pagenum == len(pages): results_max = results
            else: results_max = pagenum * 8
            return f"Showing {results_min} - {results_max} results out of {results}"

        pagemax = len(pages)
        if results:
            header = get_results()
            if len(pages) == 0: pagemax = 1

        embed = discord.Embed(title=title, description=f"{header}\n\n{pages[pagenum - 1]}", colour=0xF42F42)
        embed.set_footer(text=f"Page {pagenum}/{pagemax}", icon_url=fboturl)
        msg = await ctx.send(embed=embed)
        
        await msg.add_reaction("⬅️")
        await msg.add_reaction("➡")
        
        def check(reaction, user):
            return user == ctx.author and str(reaction.emoji) in ["⬅️", "➡"]
    
        while True:
            try:
                reaction, user = await bot.wait_for("reaction_add", timeout = 60, check=check)
                await msg.remove_reaction(reaction, user)
                
                if str(reaction.emoji) == "⬅️":
                    pagenum -= 1
                    if pagenum < 1: pagenum = len(pages)
                        
                elif str(reaction.emoji) == "➡":
                    pagenum += 1
                    if pagenum > len(pages): pagenum = 1

                header = get_results() if results else header
                if str(reaction.emoji) == "⬅️" or str(reaction.emoji) == "➡":
                    embed = discord.Embed(title=title, description=f"{header}\n\n{pages[pagenum - 1]}", colour=0xF42F42)
                    embed.set_footer(text=f"Page {pagenum}/{len(pages)}", icon_url=fboturl)
                    await msg.edit(embed=embed)
            except:
                header = get_results() if results else header
                embed = discord.Embed(title="FBot Server Status", description=f"{header}\n\n{pages[pagenum - 1]}", colour=0xF42F42)
                embed.set_footer(text=f"Request timed out", icon_url=fboturl)
                await msg.edit(embed=embed)
                break

(I avoid using numbers purely because books with more than 10 pages are annoying to manage)

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top