Python discord.Embed() Examples

The following are 30 code examples of discord.Embed(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module discord , or try the search function .
Example #1
Source File: maths.py    From cyberdisc-bot with MIT License 35 votes vote down vote up
def challenge(self, ctx: Context, number: int = 1):
        """Show the provided challenge number."""
        challenge = await get_challenge(number)
        description = challenge["challenge"]
        if len(description) > 2048:
            description = description[:2045] + "..."
        embed = Embed(
            title=challenge["title"],
            colour=Colour(0xE5E242),
            url=f"https://www.kingsmathsschool.com/weekly-maths-challenge/{challenge['slug']}",
            description=description,
        )

        embed.set_image(url=challenge["image"])
        embed.set_thumbnail(
            url="https://pbs.twimg.com/profile_images/502115424121528320/hTQzj_-R.png"
        )
        embed.set_author(name="King's Maths School")
        embed.set_footer(
            text=f"Challenge Released: {challenge['published']} | Category: {challenge['category']}"
        )
        return await ctx.send(embed=embed) 
Example #2
Source File: off_topic_names.py    From bot with MIT License 11 votes vote down vote up
def search_command(self, ctx: Context, *, query: OffTopicName) -> None:
        """Search for an off-topic name."""
        result = await self.bot.api_client.get('bot/off-topic-channel-names')
        in_matches = {name for name in result if query in name}
        close_matches = difflib.get_close_matches(query, result, n=10, cutoff=0.70)
        lines = sorted(f"• {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) 
Example #3
Source File: utils.py    From bot with MIT License 10 votes vote down vote up
def notify_pardon(
    user: UserObject,
    title: str,
    content: str,
    icon_url: str = Icons.user_verified
) -> bool:
    """DM a user about their pardoned infraction and return True if the DM is successful."""
    log.trace(f"Sending {user} a DM about their pardoned infraction.")

    embed = discord.Embed(
        description=content,
        colour=Colours.soft_green
    )

    embed.set_author(name=title, icon_url=icon_url)

    return await send_private_embed(user, embed) 
Example #4
Source File: discordclient.py    From SpaceXLaunchBot with MIT License 9 votes vote down vote up
def send_all_subscribed(
        self, to_send: Union[str, discord.Embed], send_mentions: bool = False
    ) -> None:
        """Send a message to all subscribed channels.

        Args:
            to_send: A String or discord.Embed object.
            send_mentions: If True, get mentions from db and send as well.

        """
        channel_ids = self.ds.get_subbed_channels()
        guild_opts = self.ds.get_all_guilds_options()
        invalid_ids = set()

        for channel_id in channel_ids:
            channel = self.get_channel(channel_id)

            if channel is None:
                invalid_ids.add(channel_id)
                continue

            await self._send_s(channel, to_send)

            if send_mentions:
                if (opts := guild_opts.get(channel.guild.id)) is not None:
                    if (mentions := opts.get("mentions")) is not None:
                        await self._send_s(channel, mentions)

        # Remove any channels from db that are picked up as invalid 
Example #5
Source File: watchchannel.py    From bot with MIT License 7 votes vote down vote up
def list_watched_users(self, ctx: Context, update_cache: bool = True) -> None:
        """
        Gives an overview of the watched user list for this channel.

        The optional kwarg `update_cache` specifies whether the cache should
        be refreshed by polling the API.
        """
        if update_cache:
            if not await self.fetch_user_cache():
                await ctx.send(f":x: Failed to update {self.__class__.__name__} user cache, serving from cache")
                update_cache = False

        lines = []
        for user_id, user_data in self.watched_users.items():
            inserted_at = user_data['inserted_at']
            time_delta = self._get_time_delta(inserted_at)
            lines.append(f"• <@{user_id}> (added {time_delta})")

        lines = lines or ("There's nothing here yet.",)
        embed = Embed(
            title=f"{self.__class__.__name__} watched users ({'updated' if update_cache else 'cached'})",
            color=Color.blue()
        )
        await LinePaginator.paginate(lines, ctx, embed, empty=False) 
Example #6
Source File: test_embeds.py    From SpaceXLaunchBot with MIT License 6 votes vote down vote up
def test_embed_is_valid():
    assert embeds.embed_is_valid(Embed()) is True
    assert embeds.embed_is_valid(Embed(title="a" * 256)) is True
    assert embeds.embed_is_valid(Embed(description="a" * 2048)) is True
    assert (
        embeds.embed_is_valid(embeds.EmbedWithFields(fields=[["a", "a"]] * 25)) is True
    ) 
Example #7
Source File: dice.py    From avrae with GNU General Public License v3.0 5 votes vote down vote up
def monster_check(self, ctx, monster_name, check, *args):
        """Rolls a check for a monster.
        __Valid Arguments__
        *adv/dis*
        *-b [conditional bonus]*
        -phrase [flavor text]
        -title [title] *note: [name] and [cname] will be replaced automatically*
        -thumb [thumbnail URL]
        -dc [dc]
        -rr [iterations]
        str/dex/con/int/wis/cha (different skill base; e.g. Strength (Intimidation))
        -h (hides name and image of monster)

        An italicized argument means the argument supports ephemeral arguments - e.g. `-b1` applies a bonus to one check.
        """

        monster: Monster = await select_monster_full(ctx, monster_name)

        skill_key = await search_and_select(ctx, SKILL_NAMES, check, lambda s: s)

        embed = discord.Embed()
        embed.colour = random.randint(0, 0xffffff)

        args = await helpers.parse_snippets(args, ctx)
        args = argparse(args)

        if not args.last('h', type_=bool):
            embed.set_thumbnail(url=monster.get_image_url())

        checkutils.run_check(skill_key, monster, args, embed)

        if monster.homebrew:
            embeds.add_homebrew_footer(embed)

        await ctx.send(embed=embed)
        await try_delete(ctx.message) 
Example #8
Source File: alias.py    From bot with MIT License 5 votes vote down vote up
def aliases_command(self, ctx: Context) -> None:
        """Show configured aliases on the bot."""
        embed = Embed(
            title='Configured aliases',
            colour=Colour.blue()
        )
        await LinePaginator.paginate(
            (
                f"• `{ctx.prefix}{value.name}` "
                f"=> `{ctx.prefix}{name[:-len('_alias')].replace('_', ' ')}`"
                for name, value in inspect.getmembers(self)
                if isinstance(value, Command) and name.endswith('_alias')
            ),
            ctx, embed, empty=False, max_lines=20
        ) 
Example #9
Source File: dice.py    From avrae with GNU General Public License v3.0 5 votes vote down vote up
def monster_save(self, ctx, monster_name, save_stat, *args):
        """Rolls a save for a monster.
        __Valid Arguments__
        adv/dis
        -b [conditional bonus]
        -phrase [flavor text]
        -title [title] *note: [name] and [cname] will be replaced automatically*
        -thumb [thumbnail URL]
        -dc [dc]
        -rr [iterations]
        -h (hides name and image of monster)"""

        monster: Monster = await select_monster_full(ctx, monster_name)

        embed = discord.Embed()
        embed.colour = random.randint(0, 0xffffff)

        args = await helpers.parse_snippets(args, ctx)
        args = argparse(args)

        if not args.last('h', type_=bool):
            embed.set_thumbnail(url=monster.get_image_url())

        checkutils.run_save(save_stat, monster, args, embed)

        if monster.homebrew:
            embeds.add_homebrew_footer(embed)

        await ctx.send(embed=embed)
        await try_delete(ctx.message) 
Example #10
Source File: sheetManager.py    From avrae with GNU General Public License v3.0 5 votes vote down vote up
def portrait(self, ctx):
        """Shows or edits the image of your currently active character."""
        char: Character = await Character.from_ctx(ctx)

        if not char.image:
            return await ctx.send("No image available.")

        embed = discord.Embed()
        embed.title = char.name
        embed.colour = char.get_color()
        embed.set_image(url=char.image)

        await ctx.send(embed=embed)
        await try_delete(ctx.message) 
Example #11
Source File: homebrew.py    From avrae with GNU General Public License v3.0 5 votes vote down vote up
def bestiary_server_list(self, ctx):
        """Shows what bestiaries are currently active on the server."""
        desc = []
        async for best in Bestiary.server_bestiaries(ctx):
            sharer = await best.get_server_sharer(ctx)
            desc.append(f"{best.name} (<@{sharer}>)")
        await ctx.send(embed=discord.Embed(title="Active Server Bestiaries", description="\n".join(desc))) 
Example #12
Source File: defcon.py    From bot with MIT License 5 votes vote down vote up
def status_command(self, ctx: Context) -> None:
        """Check the current status of DEFCON mode."""
        embed = Embed(
            colour=Colour.blurple(), title="DEFCON Status",
            description=f"**Enabled:** {self.enabled}\n"
                        f"**Days:** {self.days.days}"
        )

        await ctx.send(embed=embed) 
Example #13
Source File: bot.py    From bot with MIT License 5 votes vote down vote up
def embed_command(self, ctx: Context, *, text: str) -> None:
        """Send the input within an embed to the current channel."""
        embed = Embed(description=text)
        await ctx.send(embed=embed) 
Example #14
Source File: bot.py    From bot with MIT License 5 votes vote down vote up
def about_command(self, ctx: Context) -> None:
        """Get information about the bot."""
        embed = Embed(
            description="A utility bot designed just for the Python server! Try `!help` for more info.",
            url="https://github.com/python-discord/bot"
        )

        embed.add_field(name="Total Users", value=str(len(self.bot.get_guild(Guild.id).members)))
        embed.set_author(
            name="Python Bot",
            url="https://github.com/python-discord/bot",
            icon_url=URLs.bot_avatar
        )

        await ctx.send(embed=embed) 
Example #15
Source File: off_topic_names.py    From bot with MIT License 5 votes vote down vote up
def list_command(self, ctx: Context) -> None:
        """
        Lists all currently known off-topic channel names in a paginator.

        Restricted to Moderator and above to not spoil the surprise.
        """
        result = await self.bot.api_client.get('bot/off-topic-channel-names')
        lines = sorted(f"• {name}" for name in result)
        embed = Embed(
            title=f"Known off-topic names (`{len(result)}` total)",
            colour=Colour.blue()
        )
        if result:
            await LinePaginator.paginate(lines, ctx, embed, max_size=400, empty=False)
        else:
            embed.description = "Hmmm, seems like there's nothing here yet."
            await ctx.send(embed=embed) 
Example #16
Source File: homebrew.py    From avrae with GNU General Public License v3.0 5 votes vote down vote up
def tome_server_list(self, ctx):
        """Shows what tomes are currently active on the server."""
        desc = ""
        async for tome in Tome.server_active(ctx, meta_only=True):
            desc += f"{tome['name']} (<@{tome['owner']}>)\n"
        await ctx.send(embed=discord.Embed(title="Active Server Tomes", description=desc)) 
Example #17
Source File: duck_pond.py    From bot with MIT License 5 votes vote down vote up
def send_webhook(
        self,
        content: Optional[str] = None,
        username: Optional[str] = None,
        avatar_url: Optional[str] = None,
        embed: Optional[Embed] = None,
    ) -> None:
        """Send a webhook to the duck_pond channel."""
        try:
            await self.webhook.send(
                content=content,
                username=sub_clyde(username),
                avatar_url=avatar_url,
                embed=embed
            )
        except discord.HTTPException:
            log.exception("Failed to send a message to the Duck Pool webhook") 
Example #18
Source File: duck_pond.py    From bot with MIT License 5 votes vote down vote up
def relay_message(self, message: Message) -> None:
        """Relays the message's content and attachments to the duck pond channel."""
        clean_content = message.clean_content

        if clean_content:
            await self.send_webhook(
                content=message.clean_content,
                username=message.author.display_name,
                avatar_url=message.author.avatar_url
            )

        if message.attachments:
            try:
                await send_attachments(message, self.webhook)
            except (errors.Forbidden, errors.NotFound):
                e = Embed(
                    description=":x: **This message contained an attachment, but it could not be retrieved**",
                    color=Color.red()
                )
                await self.send_webhook(
                    embed=e,
                    username=message.author.display_name,
                    avatar_url=message.author.avatar_url
                )
            except discord.HTTPException:
                log.exception("Failed to send an attachment to the webhook")

        await message.add_reaction("✅") 
Example #19
Source File: watchchannel.py    From bot with MIT License 5 votes vote down vote up
def send_header(self, msg: Message) -> None:
        """Sends a header embed with information about the relayed messages to the watch channel."""
        user_id = msg.author.id

        guild = self.bot.get_guild(GuildConfig.id)
        actor = guild.get_member(self.watched_users[user_id]['actor'])
        actor = actor.display_name if actor else self.watched_users[user_id]['actor']

        inserted_at = self.watched_users[user_id]['inserted_at']
        time_delta = self._get_time_delta(inserted_at)

        reason = self.watched_users[user_id]['reason']

        if isinstance(msg.channel, DMChannel):
            # If a watched user DMs the bot there won't be a channel name or jump URL
            # This could technically include a GroupChannel but bot's can't be in those
            message_jump = "via DM"
        else:
            message_jump = f"in [#{msg.channel.name}]({msg.jump_url})"

        footer = f"Added {time_delta} by {actor} | Reason: {reason}"
        embed = Embed(description=f"{msg.author.mention} {message_jump}")
        embed.set_footer(text=textwrap.shorten(footer, width=128, placeholder="..."))

        await self.webhook_send(embed=embed, username=msg.author.display_name, avatar_url=msg.author.avatar_url) 
Example #20
Source File: charGen_test.py    From avrae with GNU General Public License v3.0 5 votes vote down vote up
def test_randname(avrae, dhttp):
    dhttp.clear()

    avrae.message("!randname")
    await dhttp.receive_message(r"Your random name: \w+")

    avrae.message("!name elf family")
    await dhttp.receive_message(embed=discord.Embed(title="Family Elf Name", description=r"\w+")) 
Example #21
Source File: site.py    From bot with MIT License 5 votes vote down vote up
def site_main(self, ctx: Context) -> None:
        """Info about the website itself."""
        url = f"{URLs.site_schema}{URLs.site}/"

        embed = Embed(title="Python Discord website")
        embed.set_footer(text=url)
        embed.colour = Colour.blurple()
        embed.description = (
            f"[Our official website]({url}) is an open-source community project "
            "created with Python and Django. It contains information about the server "
            "itself, lets you sign up for upcoming events, has its own wiki, contains "
            "a list of valuable learning resources, and much more."
        )

        await ctx.send(embed=embed) 
Example #22
Source File: site.py    From bot with MIT License 5 votes vote down vote up
def site_resources(self, ctx: Context) -> None:
        """Info about the site's Resources page."""
        learning_url = f"{PAGES_URL}/resources"

        embed = Embed(title="Resources")
        embed.set_footer(text=f"{learning_url}")
        embed.colour = Colour.blurple()
        embed.description = (
            f"The [Resources page]({learning_url}) on our website contains a "
            "list of hand-selected learning resources that we regularly recommend "
            f"to both beginners and experts."
        )

        await ctx.send(embed=embed) 
Example #23
Source File: site.py    From bot with MIT License 5 votes vote down vote up
def site_tools(self, ctx: Context) -> None:
        """Info about the site's Tools page."""
        tools_url = f"{PAGES_URL}/resources/tools"

        embed = Embed(title="Tools")
        embed.set_footer(text=f"{tools_url}")
        embed.colour = Colour.blurple()
        embed.description = (
            f"The [Tools page]({tools_url}) on our website contains a "
            f"couple of the most popular tools for programming in Python."
        )

        await ctx.send(embed=embed) 
Example #24
Source File: site.py    From bot with MIT License 5 votes vote down vote up
def site_help(self, ctx: Context) -> None:
        """Info about the site's Getting Help page."""
        url = f"{PAGES_URL}/resources/guides/asking-good-questions"

        embed = Embed(title="Asking Good Questions")
        embed.set_footer(text=url)
        embed.colour = Colour.blurple()
        embed.description = (
            "Asking the right question about something that's new to you can sometimes be tricky. "
            f"To help with this, we've created a [guide to asking good questions]({url}) on our website. "
            "It contains everything you need to get the very best help from our community."
        )

        await ctx.send(embed=embed) 
Example #25
Source File: site.py    From bot with MIT License 5 votes vote down vote up
def site_rules(self, ctx: Context, *rules: int) -> None:
        """Provides a link to all rules or, if specified, displays specific rule(s)."""
        rules_embed = Embed(title='Rules', color=Colour.blurple())
        rules_embed.url = f"{PAGES_URL}/rules"

        if not rules:
            # Rules were not submitted. Return the default description.
            rules_embed.description = (
                "The rules and guidelines that apply to this community can be found on"
                f" our [rules page]({PAGES_URL}/rules). We expect"
                " all members of the community to have read and understood these."
            )

            await ctx.send(embed=rules_embed)
            return

        full_rules = await self.bot.api_client.get('rules', params={'link_format': 'md'})
        invalid_indices = tuple(
            pick
            for pick in rules
            if pick < 1 or pick > len(full_rules)
        )

        if invalid_indices:
            indices = ', '.join(map(str, invalid_indices))
            await ctx.send(f":x: Invalid rule indices: {indices}")
            return

        for rule in rules:
            self.bot.stats.incr(f"rule_uses.{rule}")

        final_rules = tuple(f"**{pick}.** {full_rules[pick - 1]}" for pick in rules)

        await LinePaginator.paginate(final_rules, ctx, rules_embed, max_lines=3) 
Example #26
Source File: decorators.py    From bot with MIT License 5 votes vote down vote up
def locked() -> Callable:
    """
    Allows the user to only run one instance of the decorated command at a time.

    Subsequent calls to the command from the same author are ignored until the command has completed invocation.

    This decorator must go before (below) the `command` decorator.
    """
    def wrap(func: Callable) -> Callable:
        func.__locks = WeakValueDictionary()

        @wraps(func)
        async def inner(self: Cog, ctx: Context, *args, **kwargs) -> None:
            lock = func.__locks.setdefault(ctx.author.id, Lock())
            if lock.locked():
                embed = Embed()
                embed.colour = Colour.red()

                log.debug("User tried to invoke a locked command.")
                embed.description = (
                    "You're already using this command. Please wait until it is done before you use it again."
                )
                embed.title = random.choice(ERROR_REPLIES)
                await ctx.send(embed=embed)
                return

            async with func.__locks.setdefault(ctx.author.id, Lock()):
                await func(self, ctx, *args, **kwargs)
        return inner
    return wrap 
Example #27
Source File: utils.py    From bot with MIT License 5 votes vote down vote up
def notify_infraction(
    user: UserObject,
    infr_type: str,
    expires_at: t.Optional[str] = None,
    reason: t.Optional[str] = None,
    icon_url: str = Icons.token_removed
) -> bool:
    """DM a user about their new infraction and return True if the DM is successful."""
    log.trace(f"Sending {user} a DM about their {infr_type} infraction.")

    text = textwrap.dedent(f"""
        **Type:** {infr_type.capitalize()}
        **Expires:** {expires_at or "N/A"}
        **Reason:** {reason or "No reason provided."}
    """)

    embed = discord.Embed(
        description=textwrap.shorten(text, width=2048, placeholder="..."),
        colour=Colours.soft_red
    )

    embed.set_author(name="Infraction information", icon_url=icon_url, url=RULES_URL)
    embed.title = f"Please review our rules over at {RULES_URL}"
    embed.url = RULES_URL

    if infr_type in APPEALABLE_INFRACTIONS:
        embed.set_footer(
            text="To appeal this infraction, send an e-mail to appeals@pythondiscord.com"
        )

    return await send_private_embed(user, embed) 
Example #28
Source File: utils.py    From bot with MIT License 5 votes vote down vote up
def send_private_embed(user: UserObject, embed: discord.Embed) -> bool:
    """
    A helper method for sending an embed to a user's DMs.

    Returns a boolean indicator of DM success.
    """
    try:
        await user.send(embed=embed)
        return True
    except (discord.HTTPException, discord.Forbidden, discord.NotFound):
        log.debug(
            f"Infraction-related information could not be sent to user {user} ({user.id}). "
            "The user either could not be retrieved or probably disabled their DMs."
        )
        return False 
Example #29
Source File: management.py    From bot with MIT License 5 votes vote down vote up
def search_reason(self, ctx: Context, reason: str) -> None:
        """Search for infractions by their reason. Use Re2 for matching."""
        infraction_list = await self.bot.api_client.get(
            'bot/infractions',
            params={'search': reason}
        )
        embed = discord.Embed(
            title=f"Infractions matching `{reason}` ({len(infraction_list)} total)",
            colour=discord.Colour.orange()
        )
        await self.send_infraction_list(ctx, embed, infraction_list)

    # endregion
    # region: Utility functions 
Example #30
Source File: management.py    From bot with MIT License 5 votes vote down vote up
def send_infraction_list(
        self,
        ctx: Context,
        embed: discord.Embed,
        infractions: t.Iterable[utils.Infraction]
    ) -> None:
        """Send a paginated embed of infractions for the specified user."""
        if not infractions:
            await ctx.send(":warning: No infractions could be found for that query.")
            return

        lines = tuple(
            self.infraction_to_string(infraction)
            for infraction in infractions
        )

        await LinePaginator.paginate(
            lines,
            ctx=ctx,
            embed=embed,
            empty=True,
            max_lines=3,
            max_size=1000
        )