Advertisement
NaroxEG

Pagination for Discord.py | Narox

Sep 29th, 2023
1,382
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.31 KB | None | 0 0
  1. import discord
  2. from discord.ext import commands
  3.  
  4. client = commands.Bot(command_prefix="-", intents=discord.Intents.default())
  5. tree = client.tree
  6.  
  7.  
  8. @client.event
  9. async def on_ready():
  10.     synced = await tree.sync()
  11.     print(f"Synced {len(synced)} Command(s)")
  12.  
  13. content = ["Message 1", "Message 2", "Message 3",
  14.            "Message 4", "Message 5", "Message 6",
  15.            "Message 7", "Message 8", "Message 9",
  16.            "Message 10", "Message 11", "Message 12"]
  17.  
  18.  
  19. class Pagination(discord.ui.View):
  20.     def __init__(self, chunks: list, page: int, embed: discord.Embed):
  21.         super().__init__(timeout=None)
  22.         self.page = page
  23.         self.embed = embed
  24.         self.chunks = chunks
  25.  
  26.     @discord.ui.button(label="Previous", emoji="⏮")
  27.     async def prev(self, interaction: discord.Interaction, button: discord.ui.Button):
  28.         self.page -= 1
  29.         if self.page < 1:
  30.             self.page = len(self.chunks)
  31.         self.embed.description = "\n".join(
  32.             x for x in self.chunks[self.page - 1])
  33.         self.embed.set_footer(text=f"Page: {self.page} / {len(self.chunks)}")
  34.         await interaction.response.defer()
  35.         await interaction.message.edit(embed=self.embed)
  36.  
  37.     @discord.ui.button(label="Next", emoji="⏭")
  38.     async def next(self, interaction: discord.Interaction, button: discord.ui.Button):
  39.         self.page += 1
  40.         if self.page > len(self.chunks):
  41.             self.page = 1
  42.         self.embed.description = "\n".join(
  43.             x for x in self.chunks[self.page - 1])
  44.         self.embed.set_footer(text=f"Page: {self.page} / {len(self.chunks)}")
  45.         await interaction.response.defer()
  46.         await interaction.message.edit(embed=self.embed)
  47.  
  48.  
  49. @tree.command(name="test", description="test pagination")
  50. async def _test(interaction: discord.Interaction):
  51.     chunks = list(chunk(content, 6))
  52.     page = 1
  53.     embed = discord.Embed(color=discord.Color.dark_gold(),
  54.                           title="Discord Pagination")
  55.     embed.description = "\n".join(x for x in chunks[page - 1])
  56.     embed.set_footer(text=f"Page: {page} / {len(chunks)}")
  57.     await interaction.response.send_message(embed=embed, view=Pagination(chunks, page, embed))
  58.  
  59.  
  60. def chunk(list, n):
  61.     for i in range(0, len(list), n):
  62.         yield list[i:i+n]
  63.  
  64.  
  65. client.run("TOKEN")
  66.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement