async def update_data(menu): if menu.button_pressed(reload): response = await make_request() p = Page(title='Awesome Data', description='We can reload this data.') p.add_field(name='Random Updating Integer', value=response.get('random_data')) await menu.output.edit(embed=p.as_safe_embed()) elif menu.button_pressed(close): await menu.close()
async def poll(self, ctx): first = Page(title='Sun vs Moon Poll', description='Do you prefer the sun or the moon?') first.set_footer( text='Only vote once! Your vote won\'t count if you cheat!') first.buttons(['\U00002600', '\U0001F315']) first.on_next(self.finish) second = Page(title='Sun vs Moon Poll', description=f'Results are in!') menu = Poll(ctx).set_timeout(10).add_pages([first, second]) await menu.open()
def add_pages(self, pages: List['PageType'], template: 'Template' = None) -> 'BaseMenu': """Adds a list of pages to a menu, setting their index based on the position in the list. Returns itself for fluent-style chaining. :param pages: A list of pages to display; ordered from first to last in linear menus. :param template: An optional :class:`Template` to define a menu style. :rtype: :class:`BaseMenu` """ self._validate_pages(pages) for i, page in enumerate(pages): if not isinstance(page, Page): page = Page.convert_from(page) if template: page = page._apply_template(template) page.index = i self.pages.append(page) self.page = self.pages[0] return self
async def random(self, ctx): reload = '🔄' close = '❌' async def make_request(): return { 'mock': 'json', 'request': 'data', 'random_data': randint(1, 100) } async def update_data(menu): if menu.button_pressed(reload): response = await make_request() p = Page(title='Awesome Data', description='We can reload this data.') p.add_field(name='Random Updating Integer', value=response.get('random_data')) await menu.output.edit(embed=p.as_safe_embed()) elif menu.button_pressed(close): await menu.close() page1 = Page(title='Example', description='example') page1.on_next(update_data) page1.buttons([reload, close]) # workaround: we add an empty page since a menu requires 2+ pages quit_page = Page() menu = ButtonMenu(ctx) menu.add_pages([page1, quit_page]) await menu.open()
async def paginated2(self, ctx): data = generate_list_of_random_strings() 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 our first page 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.show_command_message() menu.add_pages(pages) await menu.open()
def create_menu(self, ctx: commands.Context, name: str): guild_id = ctx.guild.id guildcollections = [ extract_name(x) for x in database.db.list_collection_names() if extract_id(x) == str(guild_id) ] if name not in guildcollections: return None else: menu = PaginatedMenu(ctx) all_pages = {} collection_name = f"{guild_id}_{name}" entries_by_day = self.get_entries_by_day(collection_name) for i in range(7): day_entries = entries_by_day[i] x = "\n".join([ f"{num + 1}) " + (" ".join( list( map( str, list([ entry[key] for key in entry if key != "link" ])[2:])))).replace("\n", " ") for num, entry in enumerate(day_entries) ]) if x == "" or None or type(x) != str: break page_i = Page(title=f"Page {i + 1}", description=f"Slots for {TimeTable.days[i]}") page_i.add_field(name=TimeTable.days[i], value=x) all_pages[i] = page_i.as_safe_embed() menu.add_pages(list(all_pages.values())) menu.hide_cancel_button() menu.show_skip_buttons() menu.set_timeout(120) menu.allow_multisession() return menu
def add_pages(self, pages: List[PageType]) -> 'PaginatedMenu': """Helper method to convert embeds into Pagees and add them to a menu.""" for i, page in enumerate(pages): if isinstance(page, dict): page = Page.from_dict(page) # explicit type check here because Pages are instances of Embeds elif type(page) == Embed: page = Page.from_dict(page.to_dict()) if self.page_numbers: page.set_footer(text=f'{i + 1}/{len(pages)}') page.index = i self.pages.append(page) self.page = self.pages[0] return self
async def msgmenu(self, ctx, Benutzer: discord.User): zaehler = 0 zaehler2 = 0 zaehler3 = 0 pagelist = [] pagelist.append(Page(title='Seite 1')) nachrichtlist = [] while True: try: #Discord-Embeds koennen nur 24 Eintraege pro Seite. Sobald hier die 25 erreicht wird, wird ein neues Objekt in der Liste gespeichert und der zaehler resettet if zaehler == 25: zaehler2 +=2 pagelist.append(Page(title=f'Seite {zaehler2}')) zaehler2 -=1 zaehler = 0 insert = ' '.join(await self.config.user(Benutzer).comments.get_raw(str(zaehler3), 'text')) #Ich hole mir hier die Nachricht des Benutzers nach dem Wert von zaehler3 pagelist[zaehler2].add_field(name=f"{zaehler3}",value=f" {insert}",inline=False) #Neues Embed-Field wird angelegt, mit dem Wert von zaehler3 als Name und dem Wert von insert als Value zaehler +=1 zaehler3 +=1 except KeyError: break #Alter Code hier unten. Habe das vereinfacht und speichere die Nachricht nicht mehr in einer eigenen Liste -> Spart etwas an Leistung #zaehler = 0 #zaehler2 = 0 #zaehler3 = 0 #for i in nachrichtlist: # if zaehler == 25: # zaehler2 +=2 # testlist.append(Page(title=f'Seite {zaehler2}')) # zaehler2 -=1 # zaehler = 0 # testlist[zaehler2].add_field(name=f"{zaehler3}",value=f" {i}",inline=False) # zaehler +=1 # zaehler3 +=1 menu = PaginatedMenu(ctx) menu.set_timeout(25) menu.add_pages(pagelist) await menu.open()
async def shop(self, ctx): contentSize = len(ShopItems.items) newPage = None pageNumber = 1 pageArrays = [] print(1) newPage = Page(title=f"Pagina {pageNumber}", description="🤑🤑🤑") for i in range(1, contentSize + 1): newPage.add_field(name=ShopItems.items[i - 1].item, value=f"{ShopItems.items[i-1].description} ---" f" `${ShopItems.items[i-1].price:,d}`") print(newPage) if i % 10 == 0: pageArrays.append(newPage) pageNumber += 1 print(newPage) newPage = Page(title=f"Pagina {pageNumber}", description="🤑🤑🤑") pageArrays.append(newPage) menu = PaginatedMenu(ctx) menu.add_pages(pageArrays) await menu.open()
async def text(self, ctx): page1 = Page( title='Ping Menu', description='Are you absolutely sure you want to send a ping command?', ) page1.set_footer(text='Type `yes` if you are sure.\nType `quit` to cancel this menu.') page1.on_next(self.confirm) page2 = Page(title='Ping Menu', description='Pong!') menu = TextMenu(ctx) menu.add_pages([page1, page2]) menu.normalize_responses() await menu.open()
async def news(self, ctx): result = getAllNews() menu = PaginatedMenu(ctx) pages = [] # item = n = 2 r = [result[i:i + n] for i in range(0, len(result), n)] # print(r) for p in range(len(r)): items = r[p] page = Page(title=f"Page {p+1} of {len(r)}") # page = Page() for item in items: page.add_field(name=item.title, value=item.description, inline=False) page.add_field(name="Added By", value=item.added_by) page.add_field(name="Time Created", value=item.time_created) pages.append(page) menu.add_pages(pages) menu.show_command_message() menu.set_timeout(20) await menu.open()
async def paginated4(self, ctx, page: str = None): """This alternate example will show how to use strings instead of page numbers; for example, users can jump to a specific section of your help menu via the page mapping below. Try with `!paginated4 mod` to see it in action. There are other ways to design this, but a simple dictionary mapping is probably enough for most use cases.""" e1 = Page(title='User Help', description='User help page test!') e1.add_field(name='Example A', value='Example B') e2 = Page(title='Mod Help', description='Mod help page test!') e2.add_field(name='Example C', value='Example D') e3 = Page(title='Admin Help', description='Admin help page test!') e3.add_field(name='Example E', value='Example F') page_map = {None: e1, 'user': e1, 'mod': e2, 'admin': e3} menu = PaginatedMenu(ctx) menu.add_pages([e1, e2, e3]) menu.set_initial_page(page_map[page].index) await menu.open()
async def paginated3(self, ctx, page: int = 0): e1 = Page(title='Page 1', description='First page test!') e1.add_field(name='Example A', value='Example B') e2 = Page(title='Page 2', description='Second page test!') e2.add_field(name='Example C', value='Example D') e3 = Page(title='Page 3', description='Third page test!') e3.add_field(name='Example E', value='Example F') menu = PaginatedMenu(ctx) menu.add_pages([e1, e2, e3]) menu.set_initial_page( max(0, page - 1) ) # this is a very naive way to handle a user-friendly 1-based index await menu.open()
async def buttons(self, ctx): page1 = Page(title='Button Menu', description='Follow the arrows!') page1.add_field(name='Example A', value='Example B') page1.buttons([forward, stop]).on_next(self.first) page2 = Page(title='Button Menu', description='So many buttons! What do they do?') page2.add_field(name='Example C', value='Example D') page2.buttons([reverse, stop, forward]).on_next(self.second) page3 = Embed(title='Button Menu', description='We reached the end!') page3.add_field(name='Example E', value='Example F') menu = ButtonMenu(ctx).add_pages([page1, page2, page3]) await menu.open()
async def paginated(self, ctx): e1 = Page(title='Page 1', description='First page test!') e1.add_field(name='Example A', value='Example B') e2 = Page(title='Page 2', description='Second page test!') e2.add_field(name='Example C', value='Example D') e3 = Page(title='Page 3', description='Third page test!') e3.add_field(name='Example E', value='Example F') cancel = Page(title='Cancel Page', description='Cancel page test.') cancel.add_field(name='Example E', value='Example F') timeout = Page(title='Timeout Page', description='Timeout page test.') timeout.add_field(name='Example E', value='Example F') menu = PaginatedMenu(ctx) menu.add_pages([e1, e2, e3]) menu.set_timeout(5) menu.persist_on_close() await menu.open()
async def templates(self, ctx): e1 = Page(description='First page test!') e2 = Page(title='Page 2', description='Second page test!', color=discord.Color.green()) e2.add_field(name='Example C', value='Example D') e3 = Page(description='Third page test!') e3.add_field(name='Example E', value='Example F') e3.set_footer(text='A defined footer overrides templates!') template = Template( title='Template Example Default Title', description='This is a default description!', color=discord.Color.blue(), footer={'text': 'This is a templated footer.'}, ) menu = PaginatedMenu(ctx) menu.show_command_message() menu.add_pages([e1, e2, e3], template=template) await menu.open()
async def hooks(self, ctx): self.ctx = ctx e1 = Page(title='Page 1', description='First page test!') e1.add_field(name='Example A', value='Example B') e2 = Page(title='Page 2', description='Second page test!') e2.add_field(name='Example C', value='Example D') e3 = Page(title='Page 3', description='Third page test!') e3.add_field(name='Example E', value='Example F') menu = PaginatedMenu(ctx) menu.add_pages([e1, e2, e3]) menu.add_hook(hooks.BEFORE, hooks.UPDATE, self.counter) menu.add_hook(hooks.AFTER, hooks.CLOSE, self.show_total) await menu.open()
async def yt(self, ctx, *, term: str = ''): l = searchYT(term) # print(l) l = l[:5] menu = PaginatedMenu(ctx) i: YoutubeResult pages = [] for i in l: # embed = discord.Embed( ) # embed.set_thumbnail(url=i.thumbnail[0]) # embed.add_field(name="Views",value=i.views) page = Page(title=i.title[0], description=i.description[0], color=0x00ff00, url=i.url[0]) page.set_image(url=i.thumbnail[0]) page.add_field(name="Views", value=i.views, inline=True) page.add_field(name="duration", value=i.duration, inline=True) page.add_field(name="channel", value=i.channel, inline=True) page.add_field(name="publish time", value=i.publish_time, inline=True) pages.append(page) # await ctx.message.channel.send(embed=embed) menu.add_pages(pages) menu.show_command_message() await menu.open()
async def templates2(self, ctx): e1 = Page(description='First page test!') e2 = Page(title='Page 2', description='Second page test!', color=discord.Color.green()) e2.add_field(name='Example C', value='Example D') e3 = Page(description='Third page test!') e3.add_field(name='Example E', value='Example F') e3.set_footer(text='A defined footer overrides templates!') template = Template( title='Template Example Default Title', description='This is a default description!', color=discord.Color.blue(), footer={'text': 'This is a templated footer.'}, fields=[ { 'name': 'Template Field A', 'value': 'Templated field description for A.', 'inline': False }, { 'name': 'Template Field B', 'value': 'Templated field description for B.', 'inline': True }, ], field_style=FieldStyle. COMBINE, # this will force our template fields to combine with existing fields field_sort=FieldSort. LAST, # our template fields will always come after existing fields ) menu = PaginatedMenu(ctx) menu.show_command_message() menu.add_pages([e1, e2, e3], template=template) await menu.open()