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 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 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 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 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
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 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 demo(self, ctx): e1 = Embed(title='Page 1', description='First page test!') e1.add_field(name='Example A', value='Example B') e2 = Embed(title='Page 2', description='Second page test!') e2.add_field(name='Example C', value='Example D') e3 = Embed(title='Page 3', description='Third page test!') e3.add_field(name='Example E', value='Example F') cancel = Embed(title='Cancel Page', description='Cancel page test.') cancel.add_field(name='Example E', value='Example F') timeout = Embed(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(10) 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()
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 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 ask(self,ctx, result_limit: typing.Optional[int] = 3, *, term: str=None): embedColour = random.randint(0, 0xffffff) if term!=None: googlequery=term q=googlequery.replace(" ","+") cq=googlequery.replace(" ","%20") searchurl='https://www.google.com/search?q='+q originurl='https://www.codegrepper.com/search.php?q='+cq # print(searchurl,q) # The initial embed which shows what you searched for startEmbed = discord.Embed( title ="You asked", description =f'{term} \n [source]({originurl})', colour=embedColour ) startEmbed.set_author(name=ctx.message.author,icon_url=ctx.message.author.avatar_url) # print(term) # List which will contain the results results=[] # fetch results from codegrepper async with aiohttp.ClientSession() as session: async with session.get('https://www.codegrepper.com/api/search.php', params ={"q":term}) as r : result = await r.json() results=result['answers'] answerEmbed=discord.Embed( title='Answers', colour=embedColour ) # print(len(results),'length') # embed.set_footer(text=f'{ctx.message}') print(len(results)) # If less than 1 result stored, send notFoundEmbed if len(results)<1: notFoundEmbed=discord.Embed( title="Answer Not Found", description=f'''[Search yourself]({searchurl}) \nYou can also contribute to this by installing [codegrepper](https://www.codegrepper.com/) extension and marking an answer when you find it ''', colour=embedColour ) await ctx.send(embed=startEmbed) await ctx.send(embed=notFoundEmbed) # if there is exactly 1 result, send directly instead of using pages elif len(results)==1: print(len(results)) await ctx.send(embed=startEmbed) data=results resultList = [] for i in range(len(data)): # print(i) # print(i['answer']) if i >= result_limit : break j=data[i] ans = j['answer'] lang =j['language'] source=" " source=j['source_url'] print(source,"source") answer=f'```{lang}\n {ans}```' answerEmbed=discord.Embed( # name="name", description=answer, colour=embedColour ) notGotEmbed=discord.Embed( title=":frowning2: Did Not Find Your Answer?", description=f'''[Search yourself]({searchurl}) \nYou can also contribute to this by installing [codegrepper](https://www.codegrepper.com/) extension and marking an answer when you find it ''', colour=embedColour ) await ctx.send(embed=answerEmbed) await ctx.send(embed=notGotEmbed) # if more than or equal to 2 results, make multiple embeds and send a menu elif len(results)>=2: await ctx.send(embed=startEmbed) data=results resultList = [] for i in range(len(data)): # print(i) # print(i['answer']) if i >= result_limit : break j=data[i] ans = j['answer'] lang =j['language'] source=" " source=j['source_url'] print(source,"source") answer=f'```{lang}\n {ans}```' answerEmbed=discord.Embed( # name="name", description=answer, colour=embedColour ) # add the embed to resultList resultList.append(answerEmbed) #await ctx.send(embed=answerEmbed) notGotEmbed=discord.Embed( title=":frowning2: Did Not Find Your Answer?", description=f'''[Search yourself]({searchurl}) \nYou can also contribute to this by installing [codegrepper](https://www.codegrepper.com/) extension and marking an answer when you find it ''', colour=embedColour ) # page related stuff menu = PaginatedMenu(ctx) menu.add_pages(resultList) menu.set_timeout(30) menu.show_command_message() menu.persist_on_close() menu.show_page_numbers() menu.show_skip_buttons() menu.allow_multisession() await menu.open() print('menu opened') await ctx.send(embed=notGotEmbed) else: pass # if no argument is passed else: noargEmbed=discord.Embed( title="Ask Something, it can't be blank", description=''' something expected `?ask what you want to ask` ''', colour=embedColour ) await ctx.send(embed=noargEmbed)
async def howtoask(self, ctx, page=0, target: discord.Member = None): embedcolour = random.randint(0, 0xffffff) helpEmbed = discord.Embed( title="How to ask", description= "Here is a short explanation on how you should ask a question efficiently:", colour=embedcolour) helpEmbed.set_thumbnail( url= "https://res.cloudinary.com/zeusabhijeet/image/upload/v1607099122/SleepBot/Info%20Commands/ask_question.png" ) if target != None: helpEmbed.set_author(name=target, icon_url=target.avatar_url) else: helpEmbed.set_author(name=ctx.message.author, icon_url=ctx.message.author.avatar_url) helpEmbed.add_field( name="No Hello", value= "It's alright if you don't greet. You can directly ask your question right away; it saves your's and the other person's time. More on that [here](https://www.nohello.com/).", ) helpEmbed1 = discord.Embed( title="Asking a Code Related Question", description= """To ask a question on a code, refrain from sending screenshots or photos of the code as they are usually barely visible. Here are two ways you can share your code:""", colour=embedcolour) helpEmbed1.set_thumbnail( url= 'https://res.cloudinary.com/zeusabhijeet/image/upload/v1607100500/SleepBot/Info%20Commands/howtoask_code.png' ) helpEmbed1.add_field(name="1. Use an Online Code Sharing Service", value=""" Use these if the code you are sharing is larger than 12 lines. Below are some of the code sharing services that you can use: [GitHub Gist](https://gist.github.com/), [JSfiddle](https://jsfiddle.net/), [Codepen](https://codepen.io/), [Pastebin](https://pastebin.com/), [OnlineGDB](https://www.onlinegdb.com/), [repl.it](https://repl.it/), etc""", inline=False) helpEmbed1.add_field( name="2. Use a Code Snippet", value= """Use these when the code you are sharing is less than or about 12 lines. To make a code snippet, encase your code between a pair of 3 backticks \``` Like This \``` So when a code is sent, it will look something like this: ```py # python3 Hello World Program print("Hello World!") ``` You can read more about how Discord's Markdown works [here](https://gist.github.com/matthewzring/9f7bbfd102003963f9be7dbcf7d40e51).""", inline=False) if target != None: helpEmbed1.set_author(name=target, icon_url=target.avatar_url) else: helpEmbed1.set_author(name=ctx.message.author, icon_url=ctx.message.author.avatar_url) if target != None: await ctx.send("<@!{}>".format(target.id)) if page == 1: await ctx.send(embed=helpEmbed) elif page == 2: await ctx.send(embed=helpEmbed1) else: menu = PaginatedMenu(ctx) menu.add_pages([helpEmbed, helpEmbed1]) menu.set_timeout(30) menu.show_command_message() menu.persist_on_close() menu.show_page_numbers() menu.allow_multisession() await menu.open()
async def corona(self, ctx, *, target_country = None): """Display COVID-19 data from countries or the world Usage: !c !c br !c brazil """ if not target_country: url_td = "https://disease.sh/v3/covid-19/all" url_yt = "https://disease.sh/v3/covid-19/all?yesterday=true" url_2d = "https://disease.sh/v3/covid-19/all?twoDaysAgo=true" country_flag = "https://cdn.discordapp.com/attachments/587051836050112512/696495396628988014/W31X.gif" else: url_td = "https://disease.sh/v3/covid-19/countries/" + target_country.lower() url_yt = "https://disease.sh/v3/covid-19/countries/" + target_country.lower() + "?yesterday=true" url_2d = "https://disease.sh/v3/covid-19/countries/" + target_country.lower() + "?twoDaysAgo=true" country_flag = None try: data_today = requests.get(url_td).json() data_yesterday = requests.get(url_yt).json() data_twoDaysAgo = requests.get(url_2d).json() country_flag = country_flag if country_flag else data_today['countryInfo']['flag'] except: await ctx.send("Unable to get information right now. Try again later or contact Cow... idk") return try: title = data_today['country'] except: title = "World" time = int((datetime.utcnow() - datetime.utcfromtimestamp(data_today['updated']/1000)).total_seconds()/60) def create_embed(data, flag, title, day, time): embed = discord.Embed( colour=discord.Colour.purple(), title=title + " Covid-19 " + day, url="https://www.worldometers.info/coronavirus/") embed.set_thumbnail(url=flag) if time < 1: embed.set_footer(text="Updated less than a min. ago") else: embed.set_footer(text="Updated " + str(time) + "min ago") todayCases = prettify(data['todayCases']) todayDeaths = prettify(data['todayDeaths']) todayRecovered = prettify(data['todayRecovered']) activeCases = millify(data['active'], precision=2) population = millify(data['population'], precision=2) totalCases = millify(data['cases'], precision=2) tests = millify(data['tests'], precision=2) recovered = millify(data['recovered'], precision=2) totalDeaths = millify(data['deaths'], precision=2) embed.add_field(name="<:casesarrow:696516134962462771> New Cases", value=todayCases) embed.add_field(name="<:deathsarrow:696493553697947690> New Deaths", value=todayDeaths) embed.add_field(name="⛑️ New Recoveries", value=todayRecovered) embed.add_field(name="<:totalcases:696506315131846717> Total Cases", value=totalCases + " **({:.2f}%)**".format(calc_percentage(data['cases'], data['population'])) ) embed.add_field(name="<:coronadeaths:696408166988120124> Total Deaths", value=totalDeaths + " **({:.2f}%)**".format(calc_percentage(data['deaths'], data['cases'])) ) embed.add_field(name="<:coronarecovered:696408101078827049> Total Recovered", value=recovered + " **({:.2f}%)**".format(calc_percentage(data['recovered'], data['cases'])) ) embed.add_field(name="<a:coronacases:696408215675732078> Active Cases", value=activeCases + " **({:.2f}%)**".format(calc_percentage(data['active'], data['population'])) ) embed.add_field(name="🧪 Tests", value=tests) embed.add_field(name="<:coronapopulation:813592002293792788> Population", value=population) return embed def calc_percentage(cases, population): percentage = int(cases)/int(population)*100 return percentage embed_today = create_embed(data_today, country_flag, title, "today", time) embed_yesterday = create_embed(data_yesterday, country_flag, title, "yesterday", time) embed_ereyesterday = create_embed(data_twoDaysAgo, country_flag, title, "two days ago", time) menu = PaginatedMenu(ctx) menu.add_pages([embed_today, embed_yesterday, embed_ereyesterday]) menu.set_timeout(60) menu.show_command_message() menu.hide_cancel_button() menu.allow_multisession() menu.set_timeout_page(embed_today) await menu.open()