示例#1
0
    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()
示例#2
0
    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()
    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()
示例#5
0
    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()
示例#6
0
    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)
示例#7
0
文件: Info.py 项目: AmeyWale/SleepBot
    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()
示例#8
0
    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()