Пример #1
0
    async def wikipedia_search_command(self, ctx: commands.Context, *, search: str) -> None:
        """Return list of results containing your search query from wikipedia."""
        titles = await self.search_wikipedia(search)

        def check(message: Message) -> bool:
            return message.author.id == ctx.author.id and message.channel == ctx.channel

        if not titles:
            await ctx.send("Sorry, we could not find a wikipedia article using that search term")
            return

        async with ctx.typing():
            log.info("Finished appending titles to titles_no_underscore list")

            s_desc = "\n".join(self.formatted_wiki_url(index, title) for index, title in enumerate(titles, start=1))
            embed = Embed(colour=Color.blue(), title=f"Wikipedia results for `{search}`", description=s_desc)
            embed.timestamp = datetime.datetime.utcnow()
            await ctx.send(embed=embed)
        embed = Embed(colour=Color.green(), description="Enter number to choose")
        msg = await ctx.send(embed=embed)
        titles_len = len(titles)  # getting length of list

        for retry_count in range(1, Wikipedia.total_chance + 1):
            retries_left = Wikipedia.total_chance - retry_count
            if retry_count < Wikipedia.total_chance:
                error_msg = f"You have `{retries_left}/{Wikipedia.total_chance}` chances left"
            else:
                error_msg = 'Please try again by using `.wiki` command'
            try:
                message = await ctx.bot.wait_for('message', timeout=60.0, check=check)
                response_from_user = await self.bot.get_context(message)

                if response_from_user.command:
                    return

                response = int(message.content)
                if response < 0:
                    await ctx.send(f"Sorry, but you can't give negative index, {error_msg}")
                elif response == 0:
                    await ctx.send(f"Sorry, please give an integer between `1` to `{titles_len}`, {error_msg}")
                else:
                    await ctx.send(WIKIPEDIA_URL.format(title=titles[response - 1].replace(" ", "_")))
                    break

            except asyncio.TimeoutError:
                embed = Embed(colour=Color.red(), description=f"Time's up {ctx.author.mention}")
                await msg.edit(embed=embed)
                break

            except ValueError:
                await ctx.send(f"Sorry, but you cannot do that, I will only accept an positive integer, {error_msg}")

            except IndexError:
                await ctx.send(f"Sorry, please give an integer between `1` to `{titles_len}`, {error_msg}")

            except Exception as e:
                log.info(f"Caught exception {e}, breaking out of retry loop")
                break
Пример #2
0
def colour(rolls):
    """Return Discord embed colouring for given rolls."""

    if len(rolls) > 1:
        return Color.blue()
    elif rolls[0][1] > 0:
        return Color.green()
    else:
        return Color.red()
Пример #3
0
def get_embed_color(query):
    if spotify_rx.match(query):
        return Color.green()
    if url_rx.match(query):
        for service in embed_colors:
            if service in query:
                return embed_colors[service]
        return Color.blurple()
    return Color.red()
 async def support(self, ctx, *, message: StrRange(0, 2000)):
     """Sends a message to the bot's owner. Do not abuse."""
     owner = ctx.bot.get_user(ctx.bot.owner_id)
     embed = Embed(description=message)
     embed.set_author(name=ctx.author, icon_url=ctx.author.avatar_url)
     await owner.send(embed=embed)
     await ctx.send(embed=Embed(
         description=
         ":white_check_mark: Message has been sent. Thank you for your help!",
         color=Color.green()))
Пример #5
0
async def send_success_or_fail(ctx, status):
    if isinstance(status, list):
        condition = all(str(s).startswith('2') for s in status)
    else:
        condition = str(status).startswith('2')
    if condition:
        return await ctx.send(embed=Embed(title='Success', color=Color.green())
                              )
    else:
        return await ctx.send(embed=Embed(title='Failed', color=Color.red()))
Пример #6
0
    async def list_category(self, ctx):
        embeds = []

        for categories in divide(list(self.bot.categoryDB.find()), 10):
            embed = Embed(title='카테고리 목록', color=Color.green())

            for category in categories:
                embed.add_field(name=category['name'],
                                value=f'`{category["description"]}`')

            embeds.append(embed)

        if embeds:
            msg = await ctx.send(embed=embeds[0])
            await Paginator(self.bot, msg, embeds=embeds).start()
        else:
            await ctx.send(embed=Embed(
                title='카테고리 목록', description='카테고리가 없습니다', color=Color.green())
                           )
Пример #7
0
    async def del_category(self, ctx, name: str):
        if not self.bot.categoryDB.getOne({'name': name}):
            await ctx.send(
                embed=Embed(title='그런 이름을 가진 카테고리가 없습니다', color=Color.red()))
            return

        category = self.bot.categoryDB.getOne({'name': name})
        if category['authorID'] != str(ctx.author.id):
            await ctx.send(
                embed=Embed(title='님이 만드신 카테고리만 삭제 가능합니다', color=Color.red()))
            return

        msg = await ctx.send(
            embed=Embed(title='카테고리 삭제',
                        description=f'정말 카테고리 `{name}`를 삭제하시겠습니까?',
                        color=Color.orange()))

        await msg.add_reaction('⭕')
        await msg.add_reaction('❌')

        try:
            reaction, _ = await self.bot.wait_for(
                'reaction_add',
                check=(lambda r, u:
                       (str(r.emoji) in
                        ('⭕', '❌')) and (r.message.channel == ctx.channel) and
                       (u == ctx.author)),
                timeout=30)
        except TimeoutError:
            await msg.edit(
                embed=Embed(title='카테고리 삭제를 취소했습니다', color=Color.green()))
            return

        if str(reaction) == '❌':
            await msg.edit(
                embed=Embed(title='카테고리 삭제를 취소했습니다', color=Color.green()))
            return

        self.bot.categoryDB.delete_one({
            'authorID': str(ctx.author.id),
            'name': name
        })
        await msg.edit(embed=Embed(title='카테고리를 삭제했습니다', color=Color.green()))
Пример #8
0
    async def delegate_last_block_check(self):

        # Obtain settings and values from database as dict
        block_data = self.bot.setting.get_setting(setting_name='new_block')
        if block_data["status"] == 1:

            last_block_found = self.dpops_wrapper.delegate_api.get_last_block_found(
            )[0]
            if not last_block_found.get("error"):
                last_checked_block = int(
                    block_data["value"]
                )  # Get last check height as INT from database
                last_produced_block = int(last_block_found["block_height"])

                if last_produced_block > last_checked_block:
                    print("we have new block")
                    block_channel = self.bot.get_channel(
                        id=int(block_data["channel"]))
                    new_block = Embed(
                        title=f':bricks: New block',
                        description=
                        f'Height @ ***{int(last_block_found["block_height"]):,}***',
                        colour=Color.green())
                    new_block.add_field(
                        name=f":date: Time",
                        value=
                        f"```{datetime.fromtimestamp(int(last_block_found['block_date_and_time']))}```"
                    )
                    new_block.add_field(
                        name=f":moneybag: Block Value",
                        value=
                        f"```{float(last_block_found['block_reward']) / (10 ** 6):,} XCASH```",
                        inline=False)

                    await block_channel.send(embed=new_block)
                    if self.bot.setting.update_settings_by_dict(
                            setting_name="new_block",
                            value={
                                "value": int(last_block_found["block_height"])
                            }):
                        print("Last block marked successfully to db")
                    else:
                        print(
                            "there has been an issue when marking latest block in database"
                        )
                else:
                    print(
                        f"No new blocks have been found by delegate @ f{datetime.utcnow()}"
                    )
            else:
                print(
                    f'Could not get block status check DELEGATE: {last_block_found["error"]}'
                )
        else:
            print("Service for delegate block notifcations turned off")
Пример #9
0
    async def rand_artifacts(self):
        """Randomly summon artifacts"""
        servers = self.bot.guilds
        numservers = len(servers)
        interval_range = economy['interval_range']
        interval = random.randint(
            *interval_range) / numservers  # How often to summon a artifact
        while True:
            # Wait
            await asyncio.sleep(interval)
            interval = random.randint(*interval_range) / numservers

            selserver = random.choice(servers)  # Randomly choose a server

            artifact = random.choices(
                [x for x, y in economy['rand_artifacts']],
                weights=[y for x, y in economy['rand_artifacts']],
                k=1,
            )[0]  # Randomly choose a artifact using weights

            embed = Embed(
                title=f"A {artifact} appeared!",
                description="React with :white_check_mark: to claim!",
                color=Color.green())

            msg = await selserver.text_channels[0].send(
                embed=embed)  # Send the artifact embed | Needs improvement
            await msg.add_reaction('✅')  # Add checkmark reaction

            def check(reaction, user):
                return user.id != self.bot.user.id and reaction.emoji == '✅' and reaction.message.id == msg.id

            try:
                reaction, user = await self.bot.wait_for(
                    'reaction_add', check=check,
                    timeout=15)  # Wait for a reaction
            except asyncio.TimeoutError:
                await msg.delete(
                )  # Delete artifact message if it isn't reacted to
                continue

            await msg.delete()  # Delete message

            if str(user.id
                   ) not in economy:  # If user doesn't have economy set up
                economy[str(user.id)] = economy['default_economy']

            inv = economy[str(user.id)]['inventory']  # User's inventory
            if artifact in dict(inv).keys(
            ):  # Add artifact counter if it it already in inventory
                economy[str(user.id)]['inventory'][inv.index(artifact)][1] += 1
            else:  # Create slot of not in inventory
                economy[str(user.id)]['inventory'].append([artifact, 1])

            await economy.save()  # Save economy
Пример #10
0
def status_embed(ctx, member: Member) -> Embed:
    """
    Construct status embed for certain member.
    Status will have info such as member device, online status, activity, roles etc.
    :param ctx: context variable to get the member
    :param member: member to get data from
    :return: discord.Embed
    """

    color_dict = {
        Status.online: Color.green(),
        Status.offline: 0x000000,
        Status.idle: Color.orange(),
        Status.dnd: Color.red()
    }

    embed = Embed(title=str(member), color=color_dict[member.status])
    embed.description = get_badges(member)
    embed.set_thumbnail(url=member.avatar_url)

    bot = constants.tick_no
    nick = member.nick
    verified = constants.tick_no
    join_pos = get_join_pos(ctx, member)
    activities = ""

    if member.bot:
        bot = constants.tick_yes

    if has_verified_role(ctx, member):
        verified = constants.tick_yes

    if not nick:
        nick = constants.tick_no

    for activity in member.activities:

        clean_activity = format_activity(activity)
        activities += f"{clean_activity}\n"

    embed.add_field(
        name=f"{constants.pin_emoji} General info",
        value=f"**Nick** : {nick}\n**Bot** : {bot}\n"
        f"**Verified** : {verified}\n**Join position** : {join_pos}")
    embed.add_field(name=f"{constants.user_emoji} Status",
                    value=get_device_status(member),
                    inline=False)
    embed.add_field(name="📆 Dates",
                    value=f"**Join date** : {format_date(member.joined_at)}\n "
                    f"**Creation Date** : {format_date(member.created_at)}",
                    inline=False)

    if not activities == "":
        embed.add_field(name='Activities', value=activities, inline=False)
    return embed
Пример #11
0
    async def edit_post(self, ctx, *, id: str):
        if not self.bot.postDB.getByID(id):
            await ctx.send(embed=Embed(title='그런 아이디를 가진 글이 없습니다', color=Color.red()))
            return

        post = self.bot.postDB.getByID(id)
        if post['authorID'] != str(ctx.author.id):
            await ctx.send(embed=Embed(title='님이 만드신 글만 수정 가능합니다', color=Color.red()))
            return

        await ctx.send(embed=Embed(title='글 수정', description='글의 내용을 수정하세요? (10분이 지나면 자동으로 취소됩니다)', color=Color.orange()))

        try:
            msg = await self.bot.wait_for('message', check=(lambda m: (m.channel == ctx.channel) and (m.author == ctx.author)), timeout=600)
        except AsyncTimeoutError:
            await msg.edit(embed=Embed(title='글 수정을 취소했습니다', color=Color.green()))
            return

        content = msg.content
        if msg.attachments:
            if splitext(msg.attachments[0].filename)[1][1:] in ['png', 'jpg', 'jpeg', 'gif']:
                content += f'\n![Image]({msg.attachments[0].url})'

        msg = await ctx.send(embed=Embed(title='글 수정', description='정말 글을 수정하겠습니까?', color=Color.orange()))

        await msg.add_reaction('⭕')
        await msg.add_reaction('❌')

        try:
            reaction, _ = await self.bot.wait_for('reaction_add', check=(lambda r, u: (str(r.emoji) in ('⭕', '❌')) and (r.message == msg) and (u == ctx.author)), timeout=30)
        except AsyncTimeoutError:
            await msg.edit(embed=Embed(title='글 수정을 취소했습니다', color=Color.green()))
            return

        if str(reaction) == '❌':
            await msg.edit(embed=Embed(title='글 수정을 취소했습니다', color=Color.green()))
            return

        self.bot.postDB.updateByID(id, {
            'content': content
        })
        await msg.edit(embed=Embed(title='글 내용을 수정했습니다', color=Color.green()))
Пример #12
0
 async def premium(self, ctx: CommandContext):
     await ctx.send(
         embed=Embed(
             color=Color.green(),
             description="Hey, cool that you think about to go premium! If you go premium you would support the "
                         "developer and the moderators. Also you would help us to cover our costs ;) But what "
                         "would you get?\n__**What will you get?**__\n• change footer text\n• change embed "
                         "color\n• you can sign up to an beta from the bot to test new features\n• faster "
                         "support\n• exclusive textchannels\n__**Where to buy?**__\nYou could buy it on Patreon ["
                         "here](https://www.patreon.com/TheBotDev), but other then normally with patreon this is "
                         "an **one time payment** so you dont need to pay monthly for staying premium!"))
Пример #13
0
 async def battle(self, ctx, p2: Member):
     p1 = ctx.author
     game = Embed(color=Color.green())
     beast = list(animals.keys())
     p1 = [p1, choice(beast)]
     hp = randrange(100, 300)
     b1 = [300, stats[p1[1]]]
     game.set_author(name=p1[1].title(), icon_url=animals[p1[1]])
     game.description = f"{p1[0].display_name} goes to battle with a {p1[1].title()}!"
     s = "**HP**: 300/300\n"
     for i in b1[1]:
         s += f"**{i.upper()}**: {b1[1][i]}\n"
     game.add_field(name="Stats", value=s)
     await ctx.send(embed=game)
     await sleep(2.5)
     p2 = [p2, choice(beast)]
     b2 = [300, stats[p2[1]]]
     game.set_author(name=p2[1].title(), icon_url=animals[p2[1]])
     game.description = f"{p2[0].display_name} goes to battle with a {p2[1].title()}!"
     s = "**HP**: 300/300\n"
     for i in b2[1]:
         s += f"**{i.upper()}**: {b2[1][i]}\n"
     game.set_field_at(index=0, name="Stats", value=s)
     await ctx.send(embed=game)
     await sleep(3)
     battle = Embed(color=Color.red())
     battle.description = "**Battle Start**!"
     msg = await ctx.send(embed=battle)
     await sleep(2)
     while b1[0] > 0 and b2[0] > 0:
         b1a = b1[1]['str'] * 10 - b2[1]['agi'] * 2.5 - b2[1][
             'def'] * 2.5 + randrange(10, 30)
         b2a = b2[1]['str'] * 10 - b1[1]['agi'] * 2.5 - b1[1][
             'def'] * 2.5 + randrange(10, 30)
         b1[0] -= b2a
         b2[0] -= b1a
         battle.set_author(name=p1[1].title(), icon_url=animals[p1[1]])
         log = f"{p1[0].display_name}'s {p1[1]} deals **{b1a}** damage!\n"
         log += f"HP **{b1[0]}**/**300**\n\n\n"
         log += f"{p2[0].display_name}'s {p2[1]} deals **{b2a}** damage!\n"
         log += f"HP **{b2[0]}**/**300**\n"
         battle.description = log
         battle.set_footer(text=p2[1].title(), icon_url=animals[p2[1]])
         await msg.edit(embed=battle)
         await sleep(3)
     result = Embed(color=Color.gold())
     await sleep(2)
     if b1[0] < 0 and b2[0] < 0:
         result.title = f"{ctx.author.display_name} and {p2.display_name}'s tied"
     else:
         win = p1 if b1[0] > b2[0] else p2
         result.title = f"🎉 {win[0].display_name} 🎉 won the battle! "
     result.set_thumbnail(url=animals[win[1]])
     await ctx.send(embed=result)
Пример #14
0
    async def _suggestion_helper(self, ctx, message_id: int, reason: str,
                                 status: constants.SuggestionStatus):
        """
        Helper for suggestion approve/deny.
        :param ctx: context where approve/deny command was called.
        :param message_id: suggestion message id
        :param reason: reason for approving/denying
        :param status: either constants.SuggestionStatus.approved or constants.SuggestionStatus.denied
        :return:
        """
        msg: Message = await self.user_suggestions_channel.fetch_message(
            message_id)
        if msg is None:
            return await ctx.send(
                embed=failure("Suggestion message not found."),
                delete_after=10)
        elif not msg.embeds or not msg.embeds[0].fields:
            return await ctx.send(
                embed=failure("Message is not in correct format."),
                delete_after=10)

        api_data = await self.bot.api_client.get_suggestion(message_id)

        msg_embed = msg.embeds[0]
        if status == constants.SuggestionStatus.denied:
            field_title = "Reason"
            state = "denied"
            msg_embed.colour = Color.red()
        else:
            field_title = "Comment"
            state = "approved"
            msg_embed.colour = Color.green()

        dm_embed_msg = (
            f"Your suggestion[[link]]({msg.jump_url}) was **{state}**:\n"
            f"```\"{api_data['brief'][:200]}\"```\n"
            f"\nReason:\n{reason}")
        dm_embed = thumbnail(dm_embed_msg,
                             member=ctx.me,
                             title=f"Suggestion {state}.")

        msg_embed.set_field_at(0, name="Status", value=status.value)

        if len(msg_embed.fields) == 1:
            msg_embed.add_field(name=field_title, value=reason, inline=True)
        else:
            msg_embed.set_field_at(1,
                                   name=field_title,
                                   value=reason,
                                   inline=True)

        await self.bot.api_client.edit_suggestion(message_id, status, reason)
        await msg.edit(embed=msg_embed)
        await self._dm_member(api_data["author_id"], dm_embed)
Пример #15
0
def info(message: str, member: Union[Member, User], title: str = "Info") -> Embed:
    """
    Constructs success embed with custom title and description.
    Color depends on passed member top role color.
    :param message: embed description
    :param member: member object to get the color of it's top role from
    :param title: title of embed, defaults to "Info"
    :return: Embed object
    """
    return Embed(title=title, description=message, 
        color=get_top_role_color(member, fallback_color=Color.green()))
Пример #16
0
        def get_gradient_color(percentage):

            percentage = 50 + int(percentage) / 2
            return gradient(
                Color.red(),
                Color.magenta(),
                Color.lighter_grey(),
                Color.teal(),
                Color.green(),
                percentage=percentage,
            )
Пример #17
0
    async def send_cog_help(self, cog):
        commands = cog.get_commands()

        embed = Embed(color=Color.green())
        embed.set_author(name=f'{cog.qualified_name} category')
        embed.add_field(name='Usage', value=cog.description, inline=False)
        embed.add_field(name='Commands',
                        value=', '.join([command.name for command in commands])
                        if commands else '*No commands to show*',
                        inline=True)
        await self.get_destination().send(embed=embed)
Пример #18
0
    async def _resolve_help_settings(self, result, option, message):
        if result.reaction == "✅":
            self.logging_settings[option] = True
        else:
            self.logging_settings[option] = False

        emb = Embed()
        emb.colour = Color.green()
        emb.title = "{0} set to {1.reaction.emoji}".format(option, result)
        await self.bot.edit_message(message, embed=emb)
        await self.bot.clear_reactions(message)
Пример #19
0
def ping_em(p: int) -> Embed:
    if p > 600:
        color = Color.red()
    elif p > 200:
        color = Color.orange()
    else:
        color = Color.green()

    return Embed(title=':ping_pong: Pong',
                 description=f'Ping wynosi **{p}** ms.',
                 color=color)
Пример #20
0
    def embed(self) -> Embed:
        embed = Embed(color=Color.green(), description=self.description)
        embed.set_author(name=f'{self.version} - Changelog',
                         icon_url=self.bot.user.avatar_url,
                         url='https://modmail.tk/changelog')

        for name, value in self.fields.items():
            embed.add_field(name=name, value=value)
        embed.set_footer(text=f'Current version: v{self.bot.version}')
        embed.set_thumbnail(url=self.bot.user.avatar_url)
        return embed
Пример #21
0
    async def follow(self, ctx, user: Member):
        if not len(
                list(
                    self.bot.userCollection.find(
                        {'discordID': str(ctx.author.id)}))):
            await ctx.send(embed=Embed(title='가입이 안되있습니다', color=Color.red()))
            return

        if not user:
            await ctx.send(embed=Embed(title='유저를 맨션해주세요', color=Color.red()))
            return

        if not self.bot.userCollection.find_one({'discordID': str(user.id)}):
            await ctx.send(
                embed=Embed(title='가입이 되지 않은 유저입니다', color=Color.red()))
            return

        if user == ctx.author:
            await ctx.send(
                embed=Embed(title='나 자신은 영원한 인생의 친구입니다(라고 쓰라고 디켑님이 시킴)',
                            color=Color.green()))
            return

        user_db = self.bot.userCollection.find_one(
            {'discordID': str(ctx.author.id)})
        if str(user.id) in user_db["following"]:
            user_db['following'].remove(str(user.id))
            self.bot.userCollection.update(
                {'discordID': str(ctx.author.id)},
                {'$set': {
                    'following': user_db["following"]
                }})
            await ctx.send(
                embed=Embed(title='팔로우 취소를 했습니다', color=Color.green()))
        else:
            self.bot.userCollection.update(
                {'discordID': str(ctx.author.id)},
                {'$set': {
                    'following': user_db["following"] + [str(user.id)]
                }})
            await ctx.send(embed=Embed(title='팔로우를 했습니다', color=Color.green()))
Пример #22
0
    async def send_bot_help(self, mapping):
        embed = Embed(color=Color.green()).set_author(
            name='List of categories and commands')

        for cog, commands in mapping.items():
            if cog is not None and commands:
                embed.add_field(name=cog.qualified_name,
                                value=', '.join(command.qualified_name
                                                for command in commands),
                                inline=False)

        await self.get_destination().send(embed=embed)
Пример #23
0
 async def on_guild_role_create(self, role):
     channel = get(role.guild.text_channels, name="action_log")
     async for entry in channel.guild.audit_logs(limit=1):
         role_creator = entry.user
     e = Embed(
         description=
         f"**New role created by {role_creator.mention}**\nName:{role.name}",
         color=Color.green(),
         timestamp=datetime.utcnow())
     e.set_footer(text=f"ID: {role.id}")
     e.set_author(name=channel.guild.name, icon_url=channel.guild.icon_url)
     await channel.send(embed=e)
Пример #24
0
    async def info_category(self, ctx, name: str):
        if not self.bot.categoryDB.find({'name': name}):
            await ctx.send(
                embed=Embed(title='그런 이름을 가진 카테고리가 없습니다', color=Color.red()))
            return

        category = self.bot.categoryDB.getOne({'name': name})
        await ctx.send(embed=Embed(
            title=f'{name} 카테고리 정보',
            description=
            f'**설명:** `{category["description"]}`\n**글 수:** `{len(list(self.bot.postDB.find({"category": name})))}`',
            color=Color.green()))
Пример #25
0
def success(message: str, member: Union[Member, User] = None) -> Embed:
    """
    Constructs success embed with fixed title 'Success' and color depending
    on passed member top role color.
    If member is not passed or if it's a User (DMs) green color will be used.
    :param message: embed description
    :param member: member object to get the color of it's top role from,
                   usually our bot member object from the specific guild.
    :return: Embed object
    """
    return simple_embed(f"😁︱{message}", "",
                        get_top_role_color(member, fallback_color=Color.green()))
Пример #26
0
    async def work(self, ctx):
        """Work to make some money, with a chance of promotion"""
        if str(ctx.author.id) not in economy:
            economy[str(ctx.author.id)] = economy['default_economy']

        stats = economy[str(ctx.author.id)]

        economy[str(ctx.author.id)]['coins'] += stats['salary']

        embed = Embed(title="You went to work and made some 💸",
                      description=f"You made {stats['salary']} coins today",
                      color=Color.green())

        embed.add_field(name="Current salary",
                        value=f"{stats['salary']} coins")
        embed.add_field(name="Total coins", value=stats['coins'])

        await ctx.send(embed=embed)

        if random.choice([False] * 11 + [True]):
            economy[str(ctx.author.id)]['salary'] += random.randint(50, 120)
            salary = economy[str(ctx.author.id)]['salary']

            embed = Embed(title="You got promoted!",
                          description=f"Your new salary is {salary}!",
                          color=Color.green())

            await ctx.send(embed=embed)

        elif random.choice([False] * 24 + [True]):
            economy[str(ctx.author.id)]['salary'] -= random.randint(40, 150)
            salary = economy[str(ctx.author.id)]['salary']

            embed = Embed(title="You were demoted.",
                          description=f"Your new salary is {salary}.",
                          color=Color.red())

            await ctx.send(embed=embed)

        await economy.save()
Пример #27
0
 async def setgender(self, ctx: Context, *, gender):
     mes: Message
     if len(gender) > 255 or len(gender) < 2:
         mes = await ctx.send(embed=Embed(
             description="Please enter a valid  gender", color=Color.red()))
     else:
         ProfileModel.update(gender=gender).where(
             ProfileModel.uid == ctx.author.id).execute()
         mes = await ctx.send(
             embed=Embed(description=f"Set your gender to `{gender}`",
                         color=Color.green()))
     await sleep(10)
     await mes.delete()
Пример #28
0
def previous_feedback_submission_message(
        prev_feedback_metadata: MessageResponseContext) -> Embed:
    """ Embedded response for .last"""
    embed = discord.Embed(title="Previous Feedback Submission",
                          description="By: " + prev_feedback_metadata.author,
                          color=Color.green())
    embed.add_field(name="Original Message",
                    value=prev_feedback_metadata.content[0:997] + "...",
                    inline=False)
    embed.add_field(name="Link to Message",
                    value=prev_feedback_metadata.jump_url,
                    inline=False)
    return embed
Пример #29
0
    async def wordOfDay(self, ctx):
        """
        A user defined async function that returns the word
        of the day as an Embed object.
        """

        message = getWordOfTheDay()

        embed = Embed(title=message['word'], color=Color.green())

        embed.add_field(name="Meaning", value=message['meaning'], inline=False)

        await ctx.send(embed=embed)
Пример #30
0
def authored(message: str, *, author: Union[Member, User]) -> Embed:
    """
    Construct embed and sets its author to passed param author.
    Embed color is based on passed author top role color.
    :param author: to whom the embed will be authored.
    :param message: message to display in embed.
    :return: discord.Embed
    """
    embed = Embed(description=message,
                  color=get_top_role_color(author,
                                           fallback_color=Color.green()))
    embed.set_author(name=author.name, icon_url=author.avatar_url)
    return embed