def __init__(self,
              msg: Message,
              targetMember: Union[Member, User],
              timeoutSeconds: int,
              options: Dict[lib.emojis.dumbEmoji, ReactionMenuOption] = {},
              returnTriggers: List[lib.emojis.dumbEmoji] = [],
              titleTxt: str = "",
              desc: str = "",
              col: Colour = Colour.blue(),
              footerTxt: str = "",
              img: str = "",
              thumb: str = "",
              icon: str = "",
              authorName: str = ""):
     """
     :param returnTriggers: List of menu options that trigger the returning of the menu
     :type returnTriggers: List[lib.emojis.dumbEmoji]
     :param int timeoutSeconds: The number of seconds that this menu should last before timing out
     """
     if footerTxt == "":
         footerTxt = "This menu will expire in " + str(
             timeoutSeconds) + " seconds."
     super().__init__(msg,
                      targetMember=targetMember,
                      options=options,
                      titleTxt=titleTxt,
                      desc=desc,
                      col=col,
                      footerTxt=footerTxt,
                      img=img,
                      thumb=thumb,
                      icon=icon,
                      authorName=authorName)
     self.returnTriggers = returnTriggers
     self.timeoutSeconds = timeoutSeconds
    def fromDict(cls, rmDict : dict, **kwargs) -> ReactionRolePicker:
        """Reconstruct a ReactionRolePicker from its dictionary-serialized representation.

        :param dict rmDict: A dictionary containing all information needed to construct the desired ReactionRolePicker
        :return: A new ReactionRolePicker object as described in rmDict
        :rtype: ReactionRolePicker
        """
        if "msg" in kwargs:
            raise NameError("Required kwarg not given: msg")
        msg = kwargs["msg"]
        dcGuild = msg.guild

        reactionRoles = {BasedEmoji.fromStr(k): dcGuild.get_role(v["role"]) \
                        for k, v in rmDict["options"].items()}

        timeoutTT = None
        if "timeout" in rmDict:
            expiryTime = datetime.utcfromtimestamp(rmDict["timeout"])
            timeoutTT = timedTask.TimedTask(expiryTime=expiryTime,
                                            expiryFunction=reactionMenu.markExpiredMenu,
                                            expiryFunctionArgs=msg.id)
            botState.reactionMenusTTDB.scheduleTask(timeoutTT)

        menuColour = Colour.from_rgb(rmDict["col"][0], rmDict["col"][1], rmDict["col"][2]) \
                        if "col" in rmDict else Colour.blue()

        return ReactionRolePicker(**cls._makeDefaults(rmDict, msg=msg, reactionRoles=reactionRoles, dcGuild=dcGuild,
                                                        col=menuColour, timeout=timeoutTT,
                                                        targetMember=dcGuild.get_member(rmDict["targetMember"]) \
                                                                        if "targetMember" in rmDict else None,
                                                        targetRole=dcGuild.get_role(rmDict["targetRole"]) \
                                                                    if "targetRole" in rmDict else None))
Beispiel #3
0
    async def on_raw_reaction_add(self, raw_reaction: RawReactionActionEvent):
        thumbs_down = "\N{THUMBS DOWN SIGN}"
        if all(
            (
                str(raw_reaction.emoji) == thumbs_down,
                raw_reaction.channel_id == QUOTES_CHANNEL_ID,
            )
        ):
            quotes_channel = self.bot.get_channel(QUOTES_CHANNEL_ID)
            logs_channel = self.bot.get_channel(LOGGING_CHANNEL_ID)
            message = await quotes_channel.fetch_message(raw_reaction.message_id)
            reaction = [
                react for react in message.reactions if str(react.emoji) == thumbs_down
            ][0]
            if reaction.count >= QUOTES_DELETION_QUOTA:
                async with self.bot.pool.acquire() as connection:
                    await connection.execute(
                        "DELETE FROM quotes WHERE quote_id = $1", reaction.message.id
                    )
                mentions = ", ".join(user.mention async for user in reaction.users())
                for quote_embed in reaction.message.embeds:
                    embed = Embed(
                        color=Colour.blue(),
                        title="Quote Deleted",
                        description=quote_embed.description
                    )
                    embed.add_field(name="Deleted By", value=mentions)
                    embed.set_author(name=quote_embed.author.name, icon_url=quote_embed.author.icon_url)

                await reaction.message.delete()
                await logs_channel.send(embed=embed)
Beispiel #4
0
    async def wallet_overall_stats(ctx, utc_now, transaction_stats: dict):
        tx_stats = Embed(title='__Global Account Statistics__',
                         timestamp=utc_now,
                         colour=Colour.blue())
        tx_stats.set_thumbnail(url=ctx.author.avatar_url)
        tx_stats.add_field(name=f':abacus: Outgoing ',
                           value=transaction_stats["sentTxCount"] +
                           transaction_stats["rolePurchase"],
                           inline=True)
        tx_stats.add_field(name=f':abacus: Incoming',
                           value=transaction_stats["receivedCount"],
                           inline=True)

        tx_stats.add_field(name=f':incoming_envelope: Sent P2P ',
                           value=transaction_stats["sentTxCount"],
                           inline=True)

        tx_stats.add_field(name=f':slight_smile: Sent P2P ',
                           value=transaction_stats["emojiTxCount"],
                           inline=True)

        tx_stats.add_field(name=f':cloud_rain: Multi Transactions',
                           value=transaction_stats["multiTxCount"],
                           inline=True)

        tx_stats.add_field(name=f':man_juggling: Role Purchases  ',
                           value=transaction_stats["rolePurchase"],
                           inline=True)
        await ctx.author.send(embed=tx_stats)
Beispiel #5
0
def user_voice_preference_embed(ctx: Context,
                                preference: UserVoicePreference) -> Embed:
    """
    音声設定の表示用のEmbedを生成します。

    :param ctx: Context
    :param preference: 表示する設定
    :return: 生成したEmbed
    """
    embed = Embed(title=f"{ctx.author}さんのボイス設定", colour=Colour.blue())
    embed.add_field(
        name="読み上げ速度",
        value=
        f"**{preference.speed}**\n\n`{ctx.prefix}pref speed <0.5 以上 2.0 以下>`で設定できます。",
        inline=False)
    embed.add_field(
        name="音量",
        value=
        f"**{preference.volume}**\n\n`{ctx.prefix}pref volume <-20.0以上 0.0 以下>`で設定できます。",
        inline=False)
    embed.add_field(
        name="トーン",
        value=
        f"**{preference.tone}**\n\n`{ctx.prefix}pref tone <-20.0以上 20.0 以下>`で設定できます。",
        inline=False)
    embed.add_field(
        name="イントネーション",
        value=
        f"**{preference.intone}**\n\n`{ctx.prefix}pref tone <0.0以上 4.0 以下>`で設定できます。",
        inline=False)
    embed.set_footer(text=f"{ctx.prefix}pref reset で設定をリセットできます。")
    return embed
Beispiel #6
0
    async def list(self, ctx):
        """
        Displays options for filtering list of TTS narrator voices.

        parameters:
            ctx [Context]: context object representing command invocation
        """
        # Check if subcommand invoked
        if not ctx.invoked_subcommand:
            prefix = self.prefixes[ctx.guild]
            embed = Embed(
                title=":book: Voice Directory",
                description=(f":information_source: **Use** `{prefix}list "
                              "[Option]` **to see more filter options**"),
                colour=Colour.blue())

            # Generate information about possible subcommands
            embed.add_field(
                name="**Gender:**",
                value=f"`{prefix}list gender`,\n`{prefix}list gend`")
            embed.add_field(
                name="**Language:**",
                value=f"`{prefix}list language`,\n`{prefix}list lang`")

            await ctx.send(embed=embed)
Beispiel #7
0
    async def snowflake(self, ctx: Context, *snowflakes: Snowflake) -> None:
        """Get Discord snowflake creation time."""
        if not snowflakes:
            raise BadArgument("At least one snowflake must be provided.")

        embed = Embed(colour=Colour.blue())
        embed.set_author(
            name=
            f"Snowflake{'s'[:len(snowflakes)^1]}",  # Deals with pluralisation
            icon_url=
            "https://github.com/twitter/twemoji/blob/master/assets/72x72/2744.png?raw=true"
        )

        lines = []
        for snowflake in snowflakes:
            created_at = snowflake_time(snowflake)
            lines.append(
                f"**{snowflake}**\nCreated at {created_at} ({time_since(created_at)})."
            )

        await LinePaginator.paginate(lines,
                                     ctx=ctx,
                                     embed=embed,
                                     max_lines=5,
                                     max_size=1000)
Beispiel #8
0
    async def csnotes(self, ctx, section=None):
        embed = Embed(title="**MV16 Computer Science 2019-2021**",
                      description="Class code: 7vhujps",
                      color=Colour.blue())

        async with self.bot.pool.acquire() as connection:
            if section == "all":
                temp = await connection.fetch("SELECT * FROM classroom")
                notes_ids = sorted(temp, key=lambda x: x[0])
                for item in notes_ids:
                    embed.add_field(
                        name=f"**Section {item[0]} ({item[2]}) notes**",
                        value=
                        f"    [Click here!](https://docs.google.com/document/d/{item[1]})"
                    )

            elif section != None:
                try:
                    notes = await connection.fetch(
                        "SELECT * FROM classroom WHERE section = ($1)",
                        int(section))
                    embed.add_field(
                        name=f"**Section {section} ({notes[0][2]}) notes**",
                        value=
                        f"    [Click here!](https://docs.google.com/document/d/{notes[0][1]})"
                    )
                except ValueError:
                    await ctx.send("Section ID must be an integer!")
            await ctx.send(embed=embed)
Beispiel #9
0
 async def approve(self, ctx, member: Member):
     """Approve members"""
     try:
         member = ctx.message.mentions[0]
     except IndexError:
         await ctx.send("Please mention a user.")
         return
     if self.bot.approved_role not in member.roles:
         try:
             await member.add_roles(self.bot.approved_role)
             dm_msg = "You have been approved. Welcome to {}!".format(
                 ctx.guild.name)
             await self.dm(member, dm_msg)
             await ctx.send(":thumbsup: {} has been approved".format(member)
                            )
             emb = Embed(title="Member Approved", colour=Colour.blue())
             emb.add_field(name="Member:", value=member, inline=True)
             emb.add_field(name="Mod:",
                           value=ctx.message.author,
                           inline=True)
             logchannel = self.bot.logs_channel
             await logchannel.send("", embed=emb)
         except errors.Forbidden:
             await ctx.send("💢 I dont have permission to do this.")
     elif self.bot.approved_role in member.roles:
         await ctx.send("{} is already approved!".format(member))
Beispiel #10
0
    async def on_message(self, message: Message) -> None:
        """ Listening for DM. """
        if not self.channel:
            self.channel = self.bot.get_channel(self.bot.config.dm_channel_id)
        """
        RULES/CHECKS
        - Author must not be a bot.
        - Author must not be owner.
        - Guild needs to be None, that means It's on Bot DM or GROUP.
        """

        if any((
                message.author.bot,  # Author must not be a bot
                message.author.id == self.bot.owner_id,  # Ignore owner.
                message.guild != None  # Need to be direct message.
        )):
            return

        user = message.author

        # Create an Embed
        embed = Embed(colour=Colour.blue())
        embed.set_author(name=f"New message from {user}#{user.discriminator}",
                         icon_url=user.avatar_url)
        embed.description = user.id  # You can hold down an embed in phone, and It will copy description
        embed.add_field(name="Message:", value=message.content)

        await self.channel.send(embed=embed)  # Send to mod channel
Beispiel #11
0
    async def wallets(self, ctx):
        title = ':office_worker: __Multi Level Wallet system__:office_worker: '
        description = "Explanation of the multi-level wallet system"
        list_of_values = [{
            "name":
            ":one: Custodial Wallet :one: ",
            "value":
            f"Registration for `custodial wallet level` is mandatory for all users who would like to "
            f"use all the functions Crypto Link has to offer. Wallet operates based on MEMO when depositing. "
            f"This allows anyone to receive transaction from sender "
            f"instantly, even doe if recipient has not registered yet into the system. Custodial wallet is  "
            f"is automatically created and all actions connected with it do not require private key "
            f"to be used for signing. In order to fully protect your wallet, please activate 2FA for Discord "
            f"account. "
        }, {
            "name":
            ":two: Non-Custodial wallet support :two: ",
            "value":
            "`Noncustodial wallet` which utilizes XDR envelopes to make XDR envelopes to be signed either through"
            " [Stellar Laboratory](https://laboratory.stellar.org/#?network=public) or any other application"
            " allowing to import XDR or than straight through "
            "Discord. the only details which are stored into Crypto Link system are unique user id and "
            "user public address so XDR can be successfully built and that others can efficiently transfer "
            "tokens to you from Custodial to Non Custodial wallet"
            f"```Access it with: {self.command_string}three```"
        }]

        await custom_messages.embed_builder(ctx=ctx,
                                            title=title,
                                            description=description,
                                            data=list_of_values,
                                            destination=1,
                                            c=Colour.blue())
Beispiel #12
0
    async def account(self, ctx):
        title = ':office_worker: __Obtain information on personal account of level 1__:office_worker: '
        description = "Below are presented all currencies available for P2P transactions"
        list_of_values = [{
            "name": ":credit_card: Get balance information :credit_card: ",
            "value": f"```{self.command_string}me```"
        }, {
            "name": ":moneybag: Access wallet commands :moneybag: ",
            "value": f"```{self.command_string}wallet```"
        }, {
            "name":
            " :woman_technologist: Get full account balance report :woman_technologist:  ",
            "value": f"```{self.command_string}wallet balance```"
        }, {
            "name": ":bar_chart: Wallet Statistics :bar_chart:",
            "value": f"```{self.command_string}wallet stats```"
        }, {
            "name":
            ":inbox_tray: Get instructions on how to deposit :inbox_tray:",
            "value": f"```{self.command_string}wallet deposit```"
        }, {
            "name": ":outbox_tray: Withdrawal instructions :outbox_tray: ",
            "value": f"```{self.command_string}withdraw```"
        }]

        await custom_messages.embed_builder(ctx=ctx,
                                            title=title,
                                            description=description,
                                            data=list_of_values,
                                            destination=1,
                                            c=Colour.blue())
Beispiel #13
0
def generate_summary_embed(game_state):
    civilian_title = "Civilians"
    undercover_title = "Undercovers"
    mr_white_title = "Mr. White"

    if "civilian_word" in game_state.data:
        civilian_title += " | {word}".format(
            word=game_state.data["civilian_word"])
    if "undercover_word" in game_state.data:
        undercover_title += " | {word}".format(
            word=game_state.data["undercover_word"])

    embed = Embed(
        title=generate_message(MessageKey.SUMMARY_TITLE.name),
        colour=Colour.blue(),
    )
    if game_state.data["civilians"]:
        embed.add_field(
            name=civilian_title,
            value=game_state.data["civilians"],
            inline=False,
        )
    if game_state.data["undercovers"]:
        embed.add_field(
            name=undercover_title,
            value=game_state.data["undercovers"],
            inline=False,
        )
    if game_state.data["mr_whites"]:
        embed.add_field(
            name=mr_white_title,
            value=game_state.data["mr_whites"],
            inline=False,
        )
    return embed
Beispiel #14
0
    async def currencies(self, ctx):
        """
        Returns representation of all available currencies available to be utilized int transactions
        :return: Discord Embed
        """

        available = discord.Embed(
            title=':coin: Integrated coins and tokens :coin: ',
            description=
            'Below is a list of all available currencies for making peer 2 peer'
            ' transactions or to be used with merchant system',
            colour=Colour.blue())
        await ctx.author.send(embed=available)

        coins = self.helper.read_json_file(file_name='integratedCoins.json')
        for coin in coins:
            available.add_field(name=f'====================================',
                                value='\u200b')
            available.add_field(
                name=
                f"{coins[coin]['emoji']} {coins[coin]['name']} {coins[coin]['emoji']}",
                value=f'`Symbol:` ***{coins[coin]["ticker"]}***\n'
                f'`Issuer:` ***{coins[coin]["assetIssuer"]}***\n'
                f'`Decimals:` ***{coins[coin]["decimal"]}***\n'
                f'`Min. Withdrawal:` ***{coins[coin]["minimumWithdrawal"] / 10000000}***\n'
                f'`Expert Link:` ***{coins[coin]["expert"]}***\n'
                f'`Homepage:` ***{coins[coin]["homepage"]}***',
                inline=False)
        await ctx.author.send(embed=available)
Beispiel #15
0
 async def help(self, ctx):
     if ctx.invoked_subcommand is None:
         title = ':sos: __Available Help Commands__ :sos: '
         description = f"Available sub commands for `{self.command_string}help`"
         list_of_values = [
             {
                 "name": " :mega: About the Crypto Link :mega:",
                 "value": f"```{self.command_string}about```"
             },
             {
                 "name":
                 ":rocket: How to get started :rocket:",
                 "value":
                 f"```{self.command_string}get_started```\n"
                 f"`Aliases: start`"
             },
             {
                 "name":
                 " :moneybag: Wallet level system information :moneybag: ",
                 "value": f"```{self.command_string}help levels```"
             },
             {
                 "name":
                 ":coin: Available Currencies :coin:",
                 "value":
                 f"```{self.command_string}help currencies```\n"
                 f"`Aliases: tokens, coins`"
             },
             {
                 "name":
                 ":office_worker: Accessing personal account :office_worker:",
                 "value":
                 f"```{self.command_string}help account```\n"
                 f"`Aliases: acc, user, profile, wallet`"
             },
             {
                 "name":
                 ":money_with_wings: P2P transaction execution :money_with_wings:",
                 "value":
                 f"```{self.command_string}help transactions```\n"
                 f"`Aliases: tx, pay`"
             },
             {
                 "name": ":crown: Guild Owner Commands :crown:",
                 "value": f"```{self.command_string}help owner```"
             },
             {
                 "name":
                 ":sunrise:  Query Stellar Horizon :sunrise: ",
                 "value":
                 f"```{self.command_string}help horizon```\n"
                 f"`Aliases: hor, network, explorer`"
             },
         ]
         await custom_messages.embed_builder(ctx=ctx,
                                             title=title,
                                             description=description,
                                             data=list_of_values,
                                             destination=1,
                                             c=Colour.blue())
Beispiel #16
0
 async def ping(self, ctx):
     """Pong!"""
     await ctx.send(embed=Embed(
         colour=Colour.blue(),
         description=
         f":ping_pong: Pong! `{self.bot.latency*1000:.2f}ms` :ping_pong:",
     ))
Beispiel #17
0
    async def search_command(self, ctx: Context, *,
                             query: OffTopicName) -> None:
        """Search for an off-topic name."""
        query = OffTopicName.translate_name(query, from_unicode=False).lower()

        # Map normalized names to returned names for search purposes
        result = {
            OffTopicName.translate_name(name, from_unicode=False).lower(): name
            for name in await self.bot.api_client.get(
                'bot/off-topic-channel-names')
        }

        # Search normalized keys
        in_matches = {name for name in result.keys() if query in name}
        close_matches = difflib.get_close_matches(query,
                                                  result.keys(),
                                                  n=10,
                                                  cutoff=0.70)

        # Send Results
        lines = sorted(f"• {result[name]}"
                       for name in in_matches.union(close_matches))
        embed = Embed(title="Query results", colour=Colour.blue())

        if lines:
            await LinePaginator.paginate(lines,
                                         ctx,
                                         embed,
                                         max_size=400,
                                         empty=False)
        else:
            embed.description = "Nothing found."
            await ctx.send(embed=embed)
    async def google_search(self, ctx, query: str, limit: int = 5):
        """ Finds search results from Google search 
        Usage: !google <query>
        
        Optionally, you can ask for more than 5 results by providing limit
        Usage: !google <query> <limit>

        Note: Please use quotes(") if you are asking with multiple words. 
        I am dumb to understand without quotes :(

        Examples: 
            !google hello
            !google hello 10
            !google "hello world" 3
        """

        await ctx.send(
            f'{ctx.author.mention} Hold on! Fetching search results for you... :clock:'
        )
        async with ctx.channel.typing():
            results = search(query, stop=limit)
            numbered_results = [
                f'{index+1}. {url}' for index, url in enumerate(results)
            ]
            embed = Embed(title=f'Search results for `{query}`',
                          description='\n'.join(numbered_results)
                          or 'Nothing found :frowning2:',
                          colour=Colour.blue())
            search_store.push_search_query(guild_id=ctx.guild.id,
                                           user_id=ctx.author.id,
                                           query=query)
            await ctx.send(embed=embed)
Beispiel #19
0
    async def poll(self, ctx, title, *args):
        count = 0
        values = []
        numbers = [
            "1️⃣", "2️⃣", "3️⃣", "4️⃣", "5️⃣", "6️⃣", "7️⃣", "8️⃣", "9️⃣", "🔟"
        ]

        for number, choice in zip(numbers, args):
            string = f"{number} {choice}"
            values.append(string)
            count += 1

        embed = Embed(colour=Colour.blue(),
                      title=title,
                      description="\n".join(values))
        embed.set_footer(text=f"By {ctx.author.name}")

        if count > 1:
            message = await ctx.send(embed=embed)
            count_ = 0
            for reaction in numbers:
                count_ += 1
                if count_ <= count:
                    await message.add_reaction(reaction)
        else:
            message = await ctx.send("Must provide atleast 2 choices for poll!"
                                     )
Beispiel #20
0
    async def owner(self, ctx):
        if ctx.invoked_subcommand is None:
            title = ':crown: __Available Commands for guild owners__ :crown: '
            description = "All available commands for you to familiarize yourself with payment and merchant " \
                          "services available as owner of the community."

            list_of_values = [{
                "name": f":scales:  Register Guild into System :scales: ",
                "value": f"`{self.command_string}owner register`"
            }, {
                "name":
                f":bank: Guild wallet commands :bank:",
                "value":
                f"`{self.command_string}help owner corporate`"
            }, {
                "name":
                f":convenience_store: About Merchant and Setup :convenience_store:",
                "value":
                f"`{self.command_string}help owner merchant`"
            }, {
                "name":
                f":satellite_orbital: About Uplink and Setup :satellite_orbital:  ",
                "value":
                f"`{self.command_string}help owner uplink`"
            }]

            await custom_messages.embed_builder(ctx=ctx,
                                                title=title,
                                                description=description,
                                                data=list_of_values,
                                                destination=1,
                                                c=Colour.blue())
Beispiel #21
0
    async def eight_ball(self, ctx, *, question=None):
        """Returns an 8ball response to a user's question."""

        responses = [
            "It is certain",
            "Yes, definitely",
            "Without a doubt",
            "That's for sure",
            "Most likely",
            "Umm, try again",
            "Didnt quite get that",
            "Concentrate and try again",
            "Not likely at all",
            "My reply is no",
            "Obviously not",
            "No...",
            "My sources say no",
        ]

        if question:
            await ctx.send(f"Question: {question}\nAnswer: {choice(responses)}"
                           )

        # Send help if question == None
        else:
            embed = Embed(
                title="8ball",
                colour=Colour.blue(),
                description="Usage: `.8ball will this command work?`",
            )
            await ctx.send(embed=embed)
Beispiel #22
0
    async def help_command(self, command_name=None):
        """Sends a formatted embed in order to help users understand the commands of the bot.
        This command relies on command.brief and command.description in order to provide users
        with an adequate explanation of commands that are registered with the bot.

        :param command_name: The command that will be formatted."""
        try:
            _command = self.bot.get_command(command_name)
        except AttributeError:
            _command = None

        help_embed = Embed(colour=Colour.blue())
        if not command_name or not _command:
            # Command not found or none

            description = (f'**{bot_cmd.name}**: {bot_cmd.brief}'
                           for bot_cmd in self.bot.commands.values()
                           if not bot_cmd.hidden)
            help_embed.title = 'Commands'
            help_embed.description = '\n'.join(description)
            help_embed.set_footer(text='Use ;help {command_name}')
            return await self.bot.say(embed=help_embed)

        help_embed.title = f'**{_command.name}**'
        if not _command.description and not _command.brief:
            help_embed.description = 'This command has no description. Please try this command.'
        else:
            help_embed.description = _command.description if _command.description else _command.brief

        # Adds the Aliases field if the command has aliases
        if _command.aliases:
            help_embed.add_field(name='Aliases',
                                 value=', '.join(_command.aliases))

        return await self.bot.say(embed=help_embed)
Beispiel #23
0
def makeEmbed(titleTxt: str = "",
              desc: str = "",
              col: Colour = Colour.blue(),
              footerTxt: str = "",
              footerIcon: str = "",
              img: str = "",
              thumb: str = "",
              authorName: str = "",
              icon: str = "") -> Embed:
    """Factory function building a simple discord embed from the provided arguments.

    :param str titleTxt: The title of the embed (Default "")
    :param str desc: The description of the embed; appears at the top below the title (Default "")
    :param discord.Colour col: The colour of the side strip of the embed (Default discord.Colour.blue())
    :param str footerTxt: Secondary description appearing at the bottom of the embed (Default "")
    :param str footerIcon: small Image appearing to the left of the footer text (Default "")
    :param str img: Large icon appearing as the content of the embed, left aligned like a field (Default "")
    :param str thumb: larger image appearing to the right of the title (Default "")
    :param str authorName: Secondary title for the embed (Default "")
    :param str icon: smaller image to the left of authorName. AuthorName is required for this to be displayed. (Default "")
    :return: a new discord embed as described in the given parameters
    :rtype: discord.Embed
    """
    embed = Embed(title=titleTxt, description=desc, colour=col)
    if footerTxt != "":
        embed.set_footer(text=footerTxt, icon_url=footerIcon)
    embed.set_image(url=img)
    if thumb != "":
        embed.set_thumbnail(url=thumb)
    if icon != "":
        embed.set_author(name=authorName, icon_url=icon)
    return embed
Beispiel #24
0
 async def ping(self, ctx: Context) -> Message:
     """Responds with websocket latency"""
     embed = Embed(
         title="wew!",
         description=f"Pong!",
         colour=Colour.blue(),
     )
     return await ctx.send(embed=embed)
Beispiel #25
0
    async def reload(self, ctx, *cogs):
        """Reload cogs on the bot\n
        If param `cogs` is empty, all cogs will be reloaded 👍"""
        await ctx.trigger_typing()
        e = Embed(colour=Colour.blue(), timestamp=dt.utcnow())
        e.set_footer(
            text="Cogs in bold have already been reloaded",
            icon_url=self.bot.user.avatar_url,
        )

        if cogs != tuple():
            # Cleanup
            cogs = tuple([f"cogs.{cog}" for cog in cogs])
        else:
            # Reload whole bot
            cogs = tuple(self.bot.extensions)

        e = Embed(
            colour=Colour.blue(),
            description="Reloading cogs `" + "`, `".join(cogs) + "`",
        )
        msg, start_time = await ctx.send(embed=e), time()
        scogs, fcogs = [], []  # list and list of tuple (cog, error)
        for cog in cogs:
            try:
                self.bot.reload_extension(cog)
            except Exception as err:
                fcogs.append((cog, err))
            else:
                scogs.append(cog)

        if scogs:
            e.add_field(name="Successful cogs ✅",
                        value="`" + "`, `".join(scogs) + "`")
        if fcogs:
            e.add_field(
                name="Failed cogs ❌",
                value="\n".join([f"`{i[0]}` **-** {str(i[1])}"
                                 for i in fcogs]),
                inline=False,
            )

        e.set_author(name="Cog reload complete",
                     icon_url=self.bot.user.avatar_url)
        e.description = f"Finished reloading `{len(cogs)}` cogs in `{round((time()-start_time)*1000)}`ms ⚙"
        await msg.edit(embed=e)
Beispiel #26
0
 async def ping_cmd(self, ctx: Context) -> None:
     """Ping the Andesite node"""
     async with ctx.typing():
         delay = await self.andesite_client.ping(ctx.guild.id)
         await ctx.send(embed=Embed(
             title="Pong",
             description=f"After {round(1000 * delay)} milliseconds",
             colour=Colour.blue()))
Beispiel #27
0
    async def play(self,ctx,*, query : str):

        try:
            player = self.bot.music.player_manager.get(ctx.guild.id)

            if not play_rx.match(ctx.message.content):
                if not url_rx.match(query):
                    query = f'ytsearch:{query}'

                    # await ctx.channel.purge(limit=1)

                    results = await player.node.get_tracks(query)
                    tracks = results['tracks'][0:5]
                    i = 0 
                    query_result = ''
                    for track in tracks:
                        i+=1
                        query_result = query_result + f'{i}) {track["info"]["title"]} [{lavalink.format_time(track["info"]["length"])}] - {track["info"]["uri"]}\n'
                    embed = Embed(title="Список треков.",colour=Colour.blue())
                    embed.description = query_result
                    
                    if not query_result: 
                        await ctx.send("чел ты написал хуйню\nя гервовнулся")
                        return

                    await ctx.send(embed=embed)
                    
                    response = await self.bot.wait_for('message', check = lambda m : m.author.id == ctx.author.id) 
                    

                    if response_rx.search(response.content):
                        track = tracks[int(response_rx.findall(response.content)[0]) - 1]
                        await ctx.channel.purge(limit=1)
                    else:
                        await ctx.channel.purge(limit=2)
                        return
                    player.add(requester = ctx.author.id, track = track)

                else:
                    results = await player.node.get_tracks(query)
                    track = results['tracks'][0]
                    player.add(requester = ctx.author.id, track = track)

            

                await ctx.channel.purge(limit=1)

                if player.is_playing:
                    await ctx.send(f'Композиция {track["info"]["title"]} [{lavalink.format_time(track["info"]["length"])}] добавлена в очередь по просьбе {ctx.author.name}!')

                else: 
                    await ctx.send(f'Играет композиция {track["info"]["title"]} [{lavalink.format_time(track["info"]["length"])}] по просьбе {ctx.author.name}')
                    # await player.play(start_time=time)
                    await player.play()
                

        except Exception as error:
            await ctx.send(error)
Beispiel #28
0
    async def help(self, ctx):
        """
        Displays descriptions of all available commands for Blabber.

        paramters:
            ctx [Context]: context object representing command invocation
        """
        embed = Embed(
            title=":blue_book: **List of Commands**",
            colour=Colour.blue())
        prefix = self.prefixes[ctx.guild]

        # Generate information for voice.py commands
        embed.add_field(
            name="**Connect:**",
            value=(f"`{prefix}connect`, `{prefix}c`\n"
                    "Summon Blabber to your voice channel"),
            inline=False)
        embed.add_field(
            name="**Disconnect:**",
            value=(f"`{prefix}disconnect`, `{prefix}dc`\n"
                    "Dismiss Blabber from voice channel"),
            inline=False)
        embed.add_field(
            name="**Say:**",
            value=(f"`{prefix}say [Message]`, `{prefix}s [Message]`\n"
                    "Recite a message to your voice channel"),
            inline=False)

        # Generate information for info.py commands
        embed.add_field(
            name="**List:**",
            value=(f"`{prefix}list`, `{prefix}l`\n"
                    "Display supported TTS narrator voices"),
            inline=False)

        # Generate information for profiles.py commands
        embed.add_field(
            name="**Voice:**",
            value=(f"`{prefix}voice`, `{prefix}v`\n"
                    "Display and change your TTS narrator voice"),
            inline=False)

        # Generate information for settings.py commands
        embed.add_field(
            name="**Settings:**",
            value=(f"`{prefix}settings`, `{prefix}set`\n"
                    "Display and change server settings for Blabber"),
            inline=False)

        # Generate information for roles.py commands
        embed.add_field(
            name="**Give Blabby:**",
            value=(f"`{prefix}giveblabby [Member]`, `{prefix}gb [Member]`\n"
                    "Assigns `Blabby` role to a server member"),
            inline=False)

        await ctx.send(embed=embed)
Beispiel #29
0
def embed_pokemon(poke):
    species = poke.species
    descriptions = []
    for entry in species.flavor_text_entries:
        if entry.language.name == 'en':
            descriptions.append(entry.flavor_text)
    types = sorted(list(poke.types), key=lambda x: x.slot)
    types = '/'.join(x.type.name.capitalize() for x in types)

    ability = random.choice(poke.abilities)
    known_moves = poke.moves
    random.shuffle(known_moves)
    known_moves = known_moves[:4]
    known_moves = [pb.NamedAPIResource('move', m.move.name) for m in known_moves]
    known_moves_str = []
    for move in known_moves:
        for name in move.names:
            if name.language.name == 'en':
                known_moves_str.append(name.name)

    item = random_item()
    itemname = ""
    for name in item.names:
        if name.language.name == 'en':
            itemname = name.name
            break
    
    embed = Embed()
    embed.type = "rich"
    embed.color = Colour.blue()
    embed.title = "You caught: #{} {}".format(species.id, species.name.capitalize())
    embed.description = random.choice(descriptions)
    
    embed.set_image(
        url=poke.sprites.front_default
    )

    embed.add_field(
        name='Type',
        value=types
    )

    embed.add_field(
        name='Ability',
        value=ability.ability.name.capitalize()
    )

    embed.add_field(
        name='Moves',
        value=', '.join(known_moves_str)
    )

    embed.add_field(
        name='Held item',
        value=itemname
    )

    return embed
Beispiel #30
0
def create_delta_embeds(title,
                        yesterday: HypixelStats,
                        today: HypixelStats,
                        image=False) -> list[Embed]:
    all_embeds = []
    categories = [("Overall", (today, yesterday)),
                  ("Solos", (today.solos, yesterday.solos)),
                  ("Doubles", (today.doubles, yesterday.doubles)),
                  ("Trios", (today.trios, yesterday.trios)),
                  ("Fours", (today.fours, yesterday.fours)),
                  ("4v4", (today.two_four, yesterday.two_four))]
    for category in categories:
        subtitle = category[0]
        today, yesterday = category[1]
        embed = Embed(title=title, colour=Colour.blue(), description=subtitle)

        final_kills = today.kills - yesterday.kills
        embed.add_field(name="Final Kills",
                        value=str(final_kills),
                        inline=True)
        final_deaths = today.deaths - yesterday.deaths
        embed.add_field(name="Final Deaths",
                        value=str(final_deaths),
                        inline=True)
        final_fkdr = str(round(final_kills / final_deaths,
                               2)) if final_deaths != 0 else "Infinite"
        embed.add_field(name="FKDR", value=final_fkdr, inline=True)

        beds_broken = today.beds_broken - yesterday.beds_broken
        embed.add_field(name="Beds Broken", value=str(beds_broken))
        beds_lost = today.beds_lost - yesterday.beds_lost
        embed.add_field(name="Beds Lost", value=str(beds_lost))
        bblr = str(round(beds_broken /
                         beds_lost, 2)) if beds_lost != 0 else "Infinite"
        embed.add_field(name="BBLR", value=bblr)

        games_won = today.wins - yesterday.wins
        embed.add_field(name="Games Won", value=str(games_won))
        games_lost = today.losses - yesterday.losses
        embed.add_field(name="Games Lost", value=str(games_lost))
        win_rate = str(round(games_won /
                             games_lost, 2)) if games_lost != 0 else "Infinite"
        embed.add_field(name="Winrate", value=win_rate)
        if image:
            embed.set_thumbnail(url="attachment://head.png")
        if subtitle == "Overall":
            games_played = today.games_played - yesterday.games_played
            level = round(today.level - yesterday.level, 2)
            threat_index = round(today.threat_index - yesterday.threat_index,
                                 2)
            embed.add_field(name="Games Played", value=str(games_played))
            embed.add_field(name="Level Change", value=str(level))
            embed.add_field(name="Threat Index Change",
                            value=str(threat_index))
        all_embeds.append(embed)

    return all_embeds