Skip to content

Instantly share code, notes, and snippets.

@cyrus01337
Created March 29, 2023 04:45
Show Gist options
  • Save cyrus01337/29e23f910f7292449efc5f968f2c6c09 to your computer and use it in GitHub Desktop.
Save cyrus01337/29e23f910f7292449efc5f968f2c6c09 to your computer and use it in GitHub Desktop.
Example of custom Embed sub-class that avoids method calls by passing data as kwargs and hiding calls in the initialiser. This concept can also be thought of as providing sensible defaults to simplify developer input when creating embeds en masse.
# src/utils.py
from __future__ import annotations
from collections import namedtuple
import discord
Author = namedtuple("Author", ["name", "url", "icon_url"])
Footer = namedtuple("Footer", ["text", "icon_url"])
Field = namedtuple(
"Field", ["name", "value", "inline"], defaults=(None, None, True)
)
# or create factory functions instead within your bot class:
# def create_author(author: discord.User | discord.Member | str, *, url: str,
# icon_url: str):
# if isinstance(author, str):
# return dict(author=author, url=url, icon_url=icon_url)
#
# return dict(author=author.name, icon_url=author.avatar.url)
class Embed(discord.Embed):
def __init__(
self,
*,
author: discord.User | discord.Member | Author = None,
desc: str = None,
footer: Footer = None,
thumbnail: str = None,
fields: list[Field] = [],
**kwargs,
):
kwargs.setdefault("description", desc)
super().__init__(**kwargs)
if author:
if isinstance(author, Author):
self.set_author(
name=author.name, url=author.url, icon_url=author.icon_url
)
else:
self.set_author(name=author.name, icon_url=author.avatar.url)
if footer:
self.set_footer(text=footer.text, icon_url=footer.icon_url)
if thumbnail:
self.set_thumbnail(url=thumbnail)
for field in fields:
self.add_field(
name=field.name, value=field.value, inline=field.inline
)
from discord.ext import commands
# my preference
from src import utils
from src.utils import Field, Footer
class Example(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def info(self, ctx):
# depending on preference, listing method calls may look better
embed = utils.Embed(
title="Information",
author=ctx.author,
footer=Footer("Some funky footer text goes here", icon_url=ctx.author.avatar.url),
thumbnail=ctx.guild.icon.url,
fields=[
Field("Field #1", "inline"),
Field("Field #2", "inline"),
Field("Field #3", "inline"),
Field("Field #4", "not inline", inline=False),
Field("Field #5", "not inline", inline=False),
Field("Field #6", "not inline", inline=False),
],
)
await ctx.send(embed=embed)
async def setup(bot):
bot.add_cog(Example(bot))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment