Пример #1
0
 def songembed(song, queued: bool = False):
     e = Embed(title = song.title if not queued else f'Queued - {song.title}', url=song.url)
     e.set_image(url=song.thumbnail)
     e.description=f"- {song.channel} : {song.channel_url}"
     e.timestamp=discord.utils.utcnow()
     e.set_footer(text=f'Views: {song.views} | Duration: {round(song.duration/60)} minutes',icon_url=song.thumbnail)
     return e
Пример #2
0
 async def build_embed(self) -> discord.Embed:
     embed = Embed(
         title="Guess your character!",
         description=("```swift\n"
                      f"Question-Number  : {self.questions}\n"
                      f"Progression-Level: {self.aki.progression}\n```\n"
                      f"{self.build_bar()}"),
     )
     embed.add_field(name="- Question -", value=self.aki.question)
     embed.set_footer(
         text="Figuring out the next question | This may take a second")
     return embed
    async def get_waifu(self) -> Tuple[Embed, str]:
        """Returns a random waifu from the api

        :return: tuple of (Embed, name)
        :rtype: Tuple[Embed, str]
        """
        waifu = await self.bot.dagpi.waifu()
        pic = waifu["display_picture"]
        name = waifu["name"]
        likes_rank = waifu["like_rank"]
        trash_rank = waifu["trash_rank"]
        anime = waifu["appearances"][0]["name"]
        url = waifu["url"]

        e = Embed(title=name)
        e.add_field(name="**Anime**", value=anime, inline=True)
        e.add_field(name="**:heartbeat:**", value=likes_rank, inline=True)
        e.add_field(name="**:wastebasket:**", value=trash_rank, inline=True)
        e.add_field(name="**:link:**", value=f"[Know More]({url})")
        e.set_image(url=pic)
        e.set_footer(text="React with any emoji in 30 sec to claim him/her")
        return e, name
    async def mangasearch(self, ctx: commands.Context, *, manga_name: str):
        """Searches Manga from MAL and displays the first 10 search result."""
        search = MangaSearch(str(manga_name).strip(" ").lower())
        search_results = search.results[:10]
        description = ""
        for i, k in enumerate(search_results):
            description += f"{i+1}. **{k.title}**\n"
        e1 = Embed(
            title=f"Manga search results for {str(manga_name).capitalize()}",
            description=description,
            timestamp=ctx.message.created_at,
        )
        e1.set_footer(
            text=
            f"Showing 10 results out of {len(search.results)} | Use the recations of this message to paginate",
            icon_url=
            "https://cdn.myanimelist.net/images/event/15th_anniversary/top_page/item7.png",
        )
        embeds = [e1]
        for i in search_results:
            e = Embed(title=i.title,
                      description=i.synopsis,
                      timestamp=ctx.message.created_at)
            if i.score:
                e.add_field(name="**Score**", value=f"{i.score} :star:")
            if i.type:
                e.add_field(name="**Manga Type**", value=i.type)
            if i.url:
                e.add_field(name="**MAL Url**", value=f"[CLICK HERE]({i.url})")
            if i.mal_id:
                e.add_field(name="**MAL ID**", value=i.mal_id)
            if i.image_url:
                e.set_image(url=i.image_url)
            e.set_footer(text=f"{i.title} | {i.mal_id} | {i.score} stars",
                         icon_url=i.image_url)
            embeds.append(e)

        paginator = EmbedPaginator(entries=embeds, ctx=ctx)
        await paginator.start()
    async def animesearch(self, ctx: commands.Context, *, anime_name: str):
        """Searches Anime from MAL and displays the first 10 search result."""
        search = AnimeSearch(str(anime_name).strip(" ").lower())
        search_results = search.results[:10]
        description = ""
        for i, k in enumerate(search_results):
            description += f"{i+1}. **{k.title}**\n"
        e1 = Embed(
            title=f"Anime search results for {str(anime_name).capitalize()}",
            description=description[:4096],
            timestamp=ctx.message.created_at,
        )
        e1.set_footer(
            text=
            f"Showing 10 results out of {len(search.results)} | Use the reactions of this message to paginate",
            icon_url=LinksAndVars.mal_logo.value,
        )
        embeds = [e1]
        for i in search_results:
            e = Embed(title=i.title,
                      description=i.synopsis,
                      timestamp=ctx.message.created_at)
            if i.score:
                e.add_field(name="**Score**", value=f"{i.score} :star:")
            if i.type:
                e.add_field(name="**Anime Type**", value=i.type)
            if i.url:
                e.add_field(name="**MAL Url**", value=f"[CLICK HERE]({i.url})")
            if i.mal_id:
                e.add_field(name="**MAL ID**", value=i.mal_id)
            # if i.image_url:
            #     e.set_image(url=i.image_url) #later it the comment will be removed
            e.set_footer(text=f"{i.title} | {i.mal_id} | {i.score} stars",
                         icon_url=i.image_url)
            embeds.append(e)

        paginator = EmbedPaginator(entries=embeds, ctx=ctx)
        await paginator.start()
Пример #6
0
 def make_embed(
     self,
     character: Optional[Characters] = None,
     author: Optional[discord.Member] = None,
     color: Optional[discord.Color] = None,
 ) -> Embed:
     character = character or (self.character1 if self.turn == self.player1
                               else self.character2)
     author = author or (self.player1
                         if character == self.character1 else self.player2)
     embed = Embed()
     embed.title = character.name
     embed.set_image(url=random.choice(character.images))
     embed.set_footer(
         text=
         f'{self.special_moves1 if character == self.character1 else self.special_moves2} special moves left | {self.heal_moves1 if character == self.character1 else self.heal_moves2} heal operations left'
     )
     embed.description = self.percentage_and_progess_bar(
         self.health1 if character == self.character1 else self.health2)
     embed.set_author(name=author.display_name,
                      icon_url=author.display_avatar.url)
     if color is not None:
         embed.color = color
     return embed
    async def new(self, ctx):
        """
        Create a new reaction role using some interactive setup.

        ``Note: You can have upto 15 reaction buttons in a message, if it exceeds that it will automatically proceed to next step``
        """
        if not await ctx.prompt(
                "Welcome to the Reaction Light creation program. Please provide the required information once requested. If you would like to abort the creation then click cancel",
                author_id=ctx.author.id,
        ):
            return

        error_messages = []
        user_messages = []
        rl_object = {}
        sent_reactions_message = await ctx.send(
            "Attach roles and emojis separated by one space (one combination"
            " per message). When you are done type `done`. Example:\n:smile:"
            " `@Role`")
        rl_object["reactions"] = {}

        def check(message):
            return message.author.id == ctx.message.author.id and message.content != ""

        try:
            n = 0
            while True:
                if n > 15:
                    break
                reactions_message = await self.bot.wait_for("message",
                                                            timeout=120,
                                                            check=check)
                user_messages.append(reactions_message)
                if reactions_message.content.lower() != "done":
                    reaction = (reactions_message.content.split())[0]
                    try:
                        role = reactions_message.role_mentions[0].id
                    except IndexError:
                        error_messages.append((await ctx.send(
                            "Mention a role after the reaction. Example:\n:smile:"
                            " `@Role`")))
                        continue

                    if reaction in rl_object["reactions"]:
                        error_messages.append((await ctx.send(
                            "You have already used that reaction for another role. Please choose another reaction"
                        )))
                        continue
                    else:
                        try:
                            await reactions_message.add_reaction(reaction)
                            rl_object["reactions"][reaction] = role
                            n += 1
                        except discord.HTTPException:
                            error_messages.append((await ctx.send(
                                "You can only use reactions uploaded to servers the bot has"
                                " access to or standard emojis.")))
                            continue
                else:
                    break
        except asyncio.TimeoutError:
            await ctx.author.send(
                "Reaction Light creation failed, you took too long to provide the requested information."
            )
            return
        finally:
            await sent_reactions_message.delete()
            for message in error_messages + user_messages:
                await message.delete()

        sent_limited_message = await ctx.send(
            "Would you like to limit users to select only have one of the roles at a given time? Please react with a \U0001f512 to limit users or with a \U0000267e to allow users to select multiple roles."
        )

        def reaction_check(payload):
            return (payload.member.id == ctx.message.author.id
                    and payload.message_id == sent_limited_message.id
                    and str(payload.emoji) in ("\U0001f512", "\U0000267e"))

        try:
            await sent_limited_message.add_reaction("\U0001f512")
            await sent_limited_message.add_reaction("\U0000267e")
            limited_message_response_payload = await self.bot.wait_for(
                "raw_reaction_add", timeout=120, check=reaction_check)

            if str(limited_message_response_payload.emoji) == "\U0001f512":
                rl_object["limit_to_one"] = 1
            else:
                rl_object["limit_to_one"] = 0
        except asyncio.TimeoutError:
            await ctx.author.send(
                "Reaction Light creation failed, you took too long to provide the requested information."
            )
            return
        finally:
            await sent_limited_message.delete()

        sent_channel_message = await ctx.send(
            "Mention the #channel where to send the auto-role message.")
        try:
            while True:
                channel_message = await self.bot.wait_for("message",
                                                          timeout=120,
                                                          check=check)
                if channel_message.channel_mentions:
                    target_channel = channel_message.channel_mentions[0]
                    break
                else:
                    error_messages.append((await message.channel.send(
                        "The channel you mentioned is invalid.")))
        except asyncio.TimeoutError:
            await ctx.author.send(
                "Reaction Light creation failed, you took too long to provide the requested information."
            )
            return
        finally:
            await sent_channel_message.delete()
            for message in error_messages:
                await message.delete()

        error_messages = []
        selector_embed = Embed(
            title="Embed_title",
            description="Embed_content",
        )
        selector_embed.set_footer(text=f"{self.bot.user.name}",
                                  icon_url=self.bot.user.display_avatar.url)

        sent_message_message = await message.channel.send(
            "What would you like the message to say?\nFormatting is:"
            " `Message // Embed_title // Embed_content`.\n\n`Embed_title`"
            " and `Embed_content` are optional. You can type `none` in any"
            " of the argument fields above (e.g. `Embed_title`) to make the"
            " bot ignore it.\n\n\nMessage",
            embed=selector_embed,
        )
        try:
            while True:
                message_message = await self.bot.wait_for("message",
                                                          timeout=120,
                                                          check=check)
                # I would usually end up deleting message_message in the end but users usually want to be able to access the
                # format they once used incase they want to make any minor changes
                msg_values = message_message.content.split(" // ")
                # This whole system could also be re-done using wait_for to make the syntax easier for the user
                # But it would be a breaking change that would be annoying for thoose who have saved their message commands
                # for editing.
                selector_msg_body = (msg_values[0] if
                                     msg_values[0].lower() != "none" else None)
                selector_embed = Embed()
                selector_embed.set_footer(
                    text=self.bot.user.name,
                    icon_url=self.bot.user.display_avatar.url,
                )

                if len(msg_values) > 1:
                    if msg_values[1].lower() != "none":
                        selector_embed.title = msg_values[1]
                    if len(msg_values) > 2 and msg_values[2].lower() != "none":
                        selector_embed.description = msg_values[2]

                    # Prevent sending an empty embed instead of removing it
                selector_embed = (selector_embed if selector_embed.title
                                  or selector_embed.description else None)
                database = await self.database_class()
                if selector_msg_body or selector_embed:
                    sent_final_message = None
                    try:
                        custom_id = [
                            str(uuid.uuid4()) for i in rl_object["reactions"]
                        ]
                        sent_final_message = await target_channel.send(
                            content=selector_msg_body,
                            embed=selector_embed,
                            view=ReactionPersistentView(
                                reactions_dict=rl_object["reactions"],
                                custom_id=custom_id,
                                database=database,
                            ),
                        )
                        rl_object["custom_id"] = custom_id
                        rl_object["jump_url"] = str(
                            sent_final_message.jump_url)
                        break
                    except discord.Forbidden:
                        error_messages.append((await message.channel.send(
                            "I don't have permission to send messages to"
                            f" the channel {target_channel.mention}. Please check my permissions and try again."
                        )))
        except asyncio.TimeoutError:
            await ctx.author.send(
                "Reaction Light creation failed, you took too long to provide the requested information."
            )
            return
        finally:
            await sent_message_message.delete()
            for message in error_messages:
                await message.delete()
        await database.set(sent_final_message.id, rl_object)
    async def whosthatpokemon(self, ctx: commands.Context):
        """Play Who\'s That Pokemon?"""
        async with ctx.typing():
            wtp = await self.bot.dagpi.wtp()
            question = wtp.question
            answer = wtp.name.lower()

            e = Embed(title="Who's That Pokemon?",
                      timestamp=ctx.message.created_at)
            e.set_footer(
                text=f"{ctx.message.author} reply within 30secs to answer.",
                icon_url=ctx.message.author.avatar.url,
            )
            e.set_image(url=question)

            question_message = await ctx.send(
                "You have 3 chances, **Chance: 1/3**", embed=e)

        answerembed = discord.Embed(
            title=f"The Pokemon is: {wtp.name.capitalize()}",
            description=
            f"```Here is the Info\n\nAbilities: {', '.join(list(map(lambda x: x.capitalize(),wtp.abilities)))}```",
            timestamp=ctx.message.created_at,
        )
        answerembed.add_field(name="**Height**", value=f"{round(wtp.height)}m")
        answerembed.add_field(name="**Weight**",
                              value=f"{round(wtp.weight)} kg")
        answerembed.add_field(name=":id:", value=wtp.id)
        answerembed.set_image(url=wtp.answer)
        answerembed.set_footer(text=wtp.name.capitalize(), icon_url=wtp.answer)
        answerembed.set_author(name=wtp.name.capitalize(),
                               url=wtp.link,
                               icon_url=wtp.answer)
        for i in range(3):
            try:
                answer_content = await self.bot.wait_for(
                    "message",
                    timeout=30,
                    check=lambda m: m.author == ctx.author and m.channel == ctx
                    .channel,
                )
            except asyncio.TimeoutError:
                try:
                    await answer_content.delete()
                except (discord.NotFound, discord.Forbidden,
                        discord.HTTPException):
                    pass
                await ctx.send(embed=ErrorEmbed(
                    description=
                    "Well you didn't atleast once.\n Thus I won't be telling you the answer! :rofl:. **Baka**"
                ))
                return
            await asyncio.sleep(0.8)
            if answer_content.content.lower() != answer:
                try:
                    await answer_content.delete()
                except (discord.NotFound, discord.Forbidden,
                        discord.HTTPException):
                    pass
                await ctx.send(
                    embed=ErrorEmbed(
                        description="Please try again! :no_entry:"),
                    delete_after=3,
                )
                await question_message.edit(
                    content=f"You have {3-(i+1)} chances, **Chance: {i+1}/3**",
                    embed=e,
                )
                pass
            elif answer_content.content.lower() == answer:
                try:
                    await answer_content.delete()
                except (discord.NotFound, discord.Forbidden,
                        discord.HTTPException):
                    pass
                answerembed.color = discord.Color.green()
                await question_message.edit(
                    content=
                    f"**Yes you guessed it right!** in {i+1} chance(s), {ctx.author.mention}",
                    embed=answerembed,
                )
                return
            elif i + 1 == 3 and answer_content.content.lower() != answer:
                try:
                    await answer_content.delete()
                except (discord.NotFound, discord.Forbidden,
                        discord.HTTPException):
                    pass
                answerembed.color = discord.Color.red()
                await question_message.edit(
                    content=
                    f"Well you couldn't **guess it right in 3 chances**. Here is your **answer**!, {ctx.author.mention}",
                    embed=answerembed,
                )
                return

        try:
            await answer_content.delete()
        except (discord.NotFound, discord.Forbidden, discord.HTTPException):
            pass
        answerembed.color = discord.Color.red()
        await question_message.edit(
            content=
            f"Well you couldn't **guess it right in 3 chances**. Here is your **answer**!, {ctx.author.mention}",
            embed=answerembed,
        )
 async def aboutmanga(self, ctx: commands.Context, mal_id: int):
     """Displays about the manga using the MAL MANGA ID. get it by using mangasearch command."""
     message = await ctx.send(":mag: Searching...", delete_after=5)
     manga = Manga(int(mal_id))
     embeds = []
     e = Embed(
         title=manga.title,
         description=manga.synopsis[:4096],
         timestamp=ctx.message.created_at,
     )
     if manga.title_japanese:
         e.add_field(
             name=":japanese_castle: **Title in Japanese**",
             value=f"{manga.title_japanese}",
         )
     if manga.title_synonyms:
         e.add_field(name="**Title Synonyms**",
                     value=" ,".join(manga.title_synonyms))
     if manga.score:
         e.add_field(name=":star: **Score**", value=f"{manga.score} :star:")
     if manga.type:
         e.add_field(name=":dividers: **Type**", value=manga.type)
     if manga.url:
         e.add_field(name=":link: **MAL Url**",
                     value=f"[CLICK HERE]({manga.url})")
     if manga.mal_id:
         e.add_field(name=":id: **MAL ID**", value=manga.mal_id)
     if manga.status:
         e.add_field(name=":hourglass_flowing_sand: **Status**",
                     value=manga.status)
     if manga.genres:
         e.add_field(name=":arrow_right: **Genre**",
                     value=" ,".join(manga.genres))
     if manga.rank:
         e.add_field(name=":trophy: **Rank**", value=manga.rank)
     if manga.popularity:
         e.add_field(name="**Popularity**", value=f"#{manga.popularity}")
     if manga.chapters:
         e.add_field(name=":book: **No. of Chapters**",
                     value=manga.chapters)
     if manga.volumes:
         e.add_field(name=":books: **Volumes**", value=manga.volumes)
     if manga.authors:
         e.add_field(name=":pen_fountain: **Author(s)**",
                     value="\n・".join(manga.authors))
     if manga.published:
         e.add_field(name=":map: **Published**", value=manga.published)
     if manga.characters and len(format_manga_characters(
             manga.characters)) <= 600:
         e.add_field(name="**Characters**",
                     value=format_manga_characters(manga.characters))
     else:
         if manga.characters:
             e1 = Embed(
                 title="Characters",
                 description=format_manga_characters(
                     manga.characters)[:4096],
             )
             e1.set_footer(
                 text=
                 f"{manga.title_japanese} | {manga.mal_id} | {manga.score} stars",
                 icon_url=manga.image_url,
             )
             embeds.append(e1)
     if (manga.related_manga and
             len(format_related_anime_manga(manga.related_manga)) < 1024):
         e.add_field(
             name="**Related Manga**",
             value=format_related_anime_manga(manga.related_manga),
         )
     else:
         if manga.related_manga:
             e1 = Embed(
                 title="Related Manga",
                 description=format_related_anime_manga(
                     manga.related_manga)[:4096],
             )
             e1.set_footer(
                 text=
                 f"{manga.title_japanese} | {manga.mal_id} | {manga.score} stars",
                 icon_url=manga.image_url,
             )
             embeds.append(e1)
     if manga.image_url:
         e.set_image(url=manga.image_url)
     e.set_footer(
         text=
         f"{manga.title_japanese} | {manga.mal_id} | {manga.score} stars",
         icon_url=manga.image_url,
     )
     paginator = EmbedPaginator(entries=[e] + embeds, ctx=ctx)
     await paginator.start()
 async def aboutanime(self, ctx: commands.Context, mal_id: int):
     """Displays about the anime using the MAL ANIME ID. get it by using animesearch command."""
     await ctx.send(":mag: Searching...", delete_after=5)
     anime = Anime(int(mal_id))
     embeds = []
     e = Embed(
         title=anime.title,
         description=anime.synopsis[:4096],
         timestamp=ctx.message.created_at,
     )
     if anime.title_japanese:
         e.add_field(
             name=":japanese_castle: **Title in Japanese**",
             value=f"{anime.title_japanese}",
         )
     if anime.title_synonyms:
         e.add_field(name="**Title Synonyms**",
                     value=" ,".join(anime.title_synonyms))
     if anime.score:
         e.add_field(name=":star: **Score**", value=f"{anime.score} :star:")
     if anime.type:
         e.add_field(name=":dividers: **Type**", value=anime.type)
     if anime.url:
         e.add_field(name=":link: **MAL Url**",
                     value=f"[CLICK HERE]({anime.url})")
     if anime.mal_id:
         e.add_field(name=":id: **MAL ID**", value=anime.mal_id)
     if anime.status:
         e.add_field(name=":hourglass_flowing_sand: **Status**",
                     value=anime.status)
     if anime.genres:
         e.add_field(name=":arrow_right: **Genre**",
                     value=" ,".join(anime.genres))
     if anime.rank:
         e.add_field(name=":trophy: **Rank**", value=anime.rank)
     if anime.popularity:
         e.add_field(name="**Popularity**", value=f"#{anime.popularity}")
     if anime.episodes:
         e.add_field(name=":minidisc: **No. of Episodes**",
                     value=anime.episodes)
     if anime.premiered:
         e.add_field(name="**Premire(d)**", value=anime.premiered)
     if anime.aired:
         e.add_field(name=":calendar_spiral: **Air(ed/ing)**",
                     value=anime.aired)
     if anime.broadcast:
         e.add_field(name="**Broadcast**", value=anime.broadcast)
     if anime.producers:
         e.add_field(name="**Producers**", value=" ,".join(anime.producers))
     if anime.licensors:
         e.add_field(name="**Licensors**", value=" ,".join(anime.licensors))
     if anime.studios:
         e.add_field(name=":microphone2: **Studios**",
                     value=" ,".join(anime.studios))
     if anime.source:
         e.add_field(name=":information_source: **Source**",
                     value=anime.source)
     if anime.duration:
         e.add_field(name=":stopwatch: **Duration**", value=anime.duration)
     if anime.rating:
         e.add_field(name="**Rating**", value=anime.rating)
     if (anime.related_anime and
             len(format_related_anime_manga(anime.related_anime)) < 1024):
         e.add_field(
             name="**Related Anime**",
             value=format_related_anime_manga(anime.related_anime),
         )
     else:
         if anime.related_anime:
             e1 = Embed(
                 title="Related Anime",
                 description=format_related_anime_manga(
                     anime.related_anime)[:4096],
             )
             e1.set_footer(
                 text=
                 f"{anime.title_japanese} | {anime.mal_id} | {anime.score} stars",
                 icon_url=anime.image_url,
             )
             embeds.append(e1)
     if anime.opening_themes and len(" ,".join(
             anime.opening_themes)) <= 1000:
         e.add_field(
             name=":play_pause: **Opening Theme(s)**",
             value="・\n".join(anime.opening_themes),
         )
     else:
         if anime.opening_themes:
             e1 = Embed(
                 title=":play_pause: Opening Theme(s)",
                 description="・\n".join(anime.opening_themes)[:4096],
             )
             e1.set_footer(
                 text=
                 f"{anime.title_japanese} | {anime.mal_id} | {anime.score} stars",
                 icon_url=anime.image_url,
             )
             embeds.append(e1)
     if anime.ending_themes and len(" ,".join(anime.ending_themes)) <= 1000:
         e.add_field(
             name=":stop_button: **Ending Theme(s)**",
             value="・\n".join(anime.ending_themes),
         )
     else:
         if anime.ending_themes:
             e1 = Embed(
                 title=":stop_button: Ending Theme(s)",
                 description="・\n".join(anime.ending_themes)[:4096],
             )
             e1.set_footer(
                 text=
                 f"{anime.title_japanese} | {anime.mal_id} | {anime.score} stars",
                 icon_url=anime.image_url,
             )
             embeds.append(e1)
     if anime.staff and len(format_staff(anime.staff)) <= 700:
         e.add_field(name=":factory_worker: Staff",
                     value=format_staff(anime.staff))
     else:
         if anime.staff:
             e1 = Embed(
                 title=":factory_worker: Staff",
                 description=format_staff(anime.staff)[:4096],
             )
             e1.set_footer(
                 text=
                 f"{anime.title_japanese} | {anime.mal_id} | {anime.score} stars",
                 icon_url=anime.image_url,
             )
             embeds.append(e1)
     if anime.characters and len(format_characters(
             anime.characters)) <= 600:
         e.add_field(name="**Characters**",
                     value=format_characters(anime.characters))
     else:
         if anime.characters:
             e1 = Embed(
                 title="Characters",
                 description=format_characters(anime.characters)[:4096],
             )
             e1.set_footer(
                 text=
                 f"{anime.title_japanese} | {anime.mal_id} | {anime.score} stars",
                 icon_url=anime.image_url,
             )
             embeds.append(e1)
     if anime.image_url:
         e.set_image(url=anime.image_url)
     e.set_footer(
         text=
         f"{anime.title_japanese} | {anime.mal_id} | {anime.score} stars",
         icon_url=anime.image_url,
     )
     paginator = EmbedPaginator(entries=[e] + embeds, ctx=ctx)
     await paginator.start()
Пример #11
0
    async def create_giveaway(self, ctx: commands.Context):
        """Allowes you to to create giveaway by answering some simple questions!"""
        # Ask Questions
        embed = Embed(
            title="Giveaway Time!! \U00002728",
            description=
            "Time for a new Giveaway. Answer the following questions in 25 seconds each for the Giveaway",
            color=ctx.author.color,
        )
        await ctx.send(embed=embed)
        questions = [
            "In Which channel do you want to host the giveaway?",
            "For How long should the Giveaway be hosted ? type number followed (s|m|h|d)",
            "What is the Prize?",
            "What role should a person must have in order to enter? If no roles required then type `none`",
            "Tasks that the person should do in order to participate? If no tasks then type `none`",
        ]
        answers = []

        def check(m):
            return m.author == ctx.author and m.channel == ctx.channel

        for i, question in enumerate(questions):
            embed = Embed(title=f"Question {i+1}", description=question)
            await ctx.send(embed=embed)
            try:
                message = await self.bot.wait_for("message",
                                                  timeout=25,
                                                  check=check)
            except TimeoutError:
                await ctx.send("You didn't answer the questions in Time")
                return
            answers.append(message.content)

        # Check if Channel Id is valid
        try:
            channel_id = int(answers[0][2:-1])
        except:
            await ctx.send(
                f"The Channel provided was wrong. The channel provided should be like {ctx.channel.mention}"
            )
            return

        channel = self.bot.get_channel(channel_id)

        # Check if the role is valid
        role = answers[3]
        if role.lower() in ("none", "no", "no roles"):
            role = None
        else:
            try:
                int(answers[3][3:-1])
            except:
                i = ctx.guild.roles
                for j in i:
                    if j.name in ("@everyone", "@here"):
                        i.remove(j)
                bot_roles = choice(i)
                await ctx.send(
                    f"The role provided was wrong. The role should be like {bot_roles.mention}"
                )
                return

        time_ends = convert(answers[1]) * 1000

        # Check if Time is valid
        if time == -1:
            await ctx.send("The Time format was wrong")
            return
        if time == -2:
            await ctx.send("The Time was not conventional number")
            return
        prize = answers[2]

        task = answers[4]
        if task.lower() in ("none", "no", "no task"):
            task = None

        embed = Embed(
            title="**:tada::tada: Giveaway Time !! :tada::tada:**",
            description=f":gift: Win a **{prize}** today",
            colour=0x00FFFF,
        )
        embed.set_author(name=ctx.author.display_name,
                         icon_url=ctx.author.display_avatar.url)
        embed.set_image(url=self.giveaway_image)
        embed.add_field(
            name="Giveway ends in",
            value=
            f"{format_relative(discord.utils.utcnow() + timedelta(milliseconds=time_ends))} | [Timer]({LinksAndVars.website.value}/giveaway_timer.html?start={int(time.time() * 1000)}&length={time_ends})",
        )
        if role:
            embed.add_field(name="Role Required", value=f"{role}")
        if task:
            embed.add_field(name="\U0001f3c1 Tasks", value=task)
        newMsg = await channel.send(embed=embed)
        embed.set_footer(text=f"Giveaway ID: {newMsg.id}")
        await newMsg.edit(embed=embed)
        await newMsg.add_reaction(discord.PartialEmoji(name="\U0001f389"))
        await ctx.send(
            f"Your giveaway will be hosted in {channel.mention} and will last for {answers[1]}\n{newMsg.jump_url}"
        )
        await self.create_timer_for_giveaway(
            newMsg, (discord.utils.utcnow() +
                     timedelta(milliseconds=time_ends)).timestamp())
Пример #12
0
    async def determine_winner(
            self, giveaway_id: discord.Message,
            bot: commands.Bot) -> Union[str, discord.Member]:
        """Determines winner

        :param giveaway_id: The giveaway id
        :type giveaway_id: discord.Message
        :param bot: The bot class
        :type bot: commands.Bot
        :return: The winner details
        :rtype: Union[str, discord.Member]
        """
        reactions = discord.utils.find(
            lambda a: str(a) == str(discord.PartialEmoji(name="\U0001f389")),
            giveaway_id.reactions)
        if reactions is None:
            return "The channel or ID mentioned was incorrect"
        try:
            giveaway_config = await self.get_giveaway_config(
                giveaway_id.
                id if not isinstance(giveaway_id.id, int) else giveaway_id)
        except AttributeError as e:
            return str(e)

        reacted_users = await reactions.users().flatten()
        if discord.utils.get(reacted_users, id=bot.application_id):
            reacted_users.remove(
                discord.utils.get(reacted_users, id=bot.application_id))
        if giveaway_config.role_required is not None and len(
                reacted_users) <= 0:
            reacted_users = list(
                filter(
                    lambda a: discord.utils.get(
                        a.roles,
                        id=int(
                            giveaway_config.role_required.lstrip('<@&').lstrip(
                                '<&').rstrip('>'))) is not None,
                    reacted_users))
        if len(reacted_users) <= 0:
            emptyEmbed = Embed(
                title=
                "\U0001f389\U0001f389 Giveaway Time !! \U0001f389\U0001f389",
                description="\U0001f381 Win a Prize today")
            emptyEmbed.set_author(
                name=giveaway_config.host.display_name,
                icon_url=giveaway_config.host.display_avatar.url)
            emptyEmbed.add_field(
                name="No winners",
                value="Not enough participants to determine the winners",
            )
            emptyEmbed.set_image(url=self.giveaway_image)
            emptyEmbed.set_footer(text="No one won the Giveaway")
            await giveaway_id.edit(embed=emptyEmbed)
            return f"No one won the giveaway! As there were not enough participants!\n{giveaway_config.jump_url}"
        winner = choice(reacted_users)
        winnerEmbed = giveaway_config.embed
        if discord.utils.find(
                lambda a: a["name"].lower() == "\U0001f389 Winner \U0001f389".
                lower(), giveaway_config.embed_dict["fields"]) is None:
            winnerEmbed.add_field(name="\U0001f389 Winner \U0001f389",
                                  value=winner.mention,
                                  inline=False)
        await giveaway_id.edit(embed=winnerEmbed)
        return winner
Пример #13
0
    async def polltime(self, ctx):
        """Create polls easily"""
        def check(m):
            return m.author == ctx.author and m.channel == ctx.channel

        questions = [
            "What should be the **strawpoll title**?",
            "Write the **description** of the strawpoll.",
            "How many option(s) should be there? (Min 2 and Max 10)",
            "In which channel do you want to host this **strawpoll**?",
        ]

        answers = []
        options = []
        all_messages = [ctx.message]

        for i, question in enumerate(questions):
            embed = Embed(title=f"Question {i+1}", description=question)
            question_message = await ctx.send(embed=embed)
            all_messages.append(question_message)
            try:
                message = await self.bot.wait_for("message",
                                                  timeout=60,
                                                  check=check)
                if i == 2:
                    all_messages.append(message)
                    try:
                        int(message.content)
                    except:
                        await ctx.send(embed=ErrorEmbed(
                            description=
                            f"{message.content} you provided is **not an number**, Please **rerun the command again**!"
                        ),
                                       delete_after=2)
                        await self.delete_message(all_messages)
                        return
                    if int(message.content) < 2:
                        await ctx.send(embed=ErrorEmbed(
                            description=
                            "The no. of options cannot be **less than 2**, Please **rerun the command again**!"
                        ),
                                       delete_after=2)
                        await self.delete_message(all_messages)
                        return
                    if int(message.content) > len(self.reactions):
                        await ctx.send(embed=ErrorEmbed(
                            description=
                            "The no. of options cannot be **greater than 10**, Please **rerun the command again**!"
                        ),
                                       delete_after=2)
                        await self.delete_message(all_messages)
                        return
                    for i in range(int(message.content)):
                        option_question = await ctx.send(f"**Option {i+1}**")
                        all_messages.append(option_question)
                        try:
                            options_message = await self.bot.wait_for(
                                "message", timeout=60, check=check)
                            all_messages.append(option_question)
                        except:
                            await ctx.send(
                                "You didn't answer the questions in Time",
                                delete_after=2)
                            await self.delete_message(all_messages)
                            return
                        options.append(options_message.content)

            except:
                await ctx.send("You didn't answer the questions in Time",
                               delete_after=2)
                await self.delete_message(all_messages)
                return
            answers.append(message.content)

        question, description, poll_channel = (
            answers[0],
            answers[1],
            await
            commands.TextChannelConverter(answers[-1]
                                          ).convert(ctx=ctx,
                                                    argument=answers[-1]),
        )
        if not isinstance(poll_channel, discord.TextChannel):
            await ctx.send(embed=ErrorEmbed(
                description=
                "Wrong text channel provided! Try again and mention the channel next time! :wink:"
            ),
                           delete_after=2)
            await self.delete_message(all_messages)
            return

        if len(options) == 2 and options[0] == "yes" and options[1] == "no":
            reactions = ["\U00002705", "\U0000274c"]
        else:
            reactions = self.reactions

        description = []
        for x, option in enumerate(options):
            description += "\n\n {} {}".format(reactions[x], option)
        embed = Embed(title=question, description="".join(description))
        react_message = await poll_channel.send(embed=embed)
        for reaction in reactions[:len(options)]:
            await react_message.add_reaction(reaction)
        embed.set_footer(text="Poll ID: {}".format(react_message.id))
        await react_message.edit(embed=embed)
        await ctx.send(
            f'Done :ok_hand: Hosted the poll in {poll_channel.mention}',
            delete_after=2)
        await self.delete_message(all_messages)