Skip to content

Emoji

attrs class PartialEmoji (SnowflakeObject, DictSerializationMixin)

Represent a basic ("partial") emoji used in discord.

Attr attributes:

Name Type Description
id Optional[Snowflake_Type]

The custom emoji id. Leave empty if you are using standard unicode emoji.

name Optional[str]

The custom emoji name, or standard unicode emoji in string

animated bool

Whether this emoji is animated

Source code in naff/models/discord/emoji.py
@define(kw_only=False)
class PartialEmoji(SnowflakeObject, DictSerializationMixin):
    """Represent a basic ("partial") emoji used in discord."""

    id: Optional["Snowflake_Type"] = field(
        repr=True, default=None, converter=optional(to_snowflake)
    )  # can be None for Standard Emoji
    """The custom emoji id. Leave empty if you are using standard unicode emoji."""
    name: Optional[str] = field(repr=True, default=None)
    """The custom emoji name, or standard unicode emoji in string"""
    animated: bool = field(repr=True, default=False)
    """Whether this emoji is animated"""

    @classmethod
    def from_str(cls, emoji_str: str) -> "PartialEmoji":
        """
        Generate a PartialEmoji from a discord Emoji string representation, or unicode emoji.

        Handles:
            <:emoji_name:emoji_id>
            :emoji_name:emoji_id
            <a:emoji_name:emoji_id>
            a:emoji_name:emoji_id
            👋

        Args:
            emoji_str: The string representation an emoji

        Returns:
            A PartialEmoji object

        Raises:
            ValueError if the string cannot be parsed

        """
        parsed = emoji_regex.findall(emoji_str)
        if parsed:
            parsed = tuple(filter(None, parsed[0]))
            if len(parsed) == 3:
                return cls(name=parsed[1], id=parsed[2], animated=True)
            else:
                return cls(name=parsed[0], id=parsed[1])
        else:
            return cls(name=emoji_str)

    def __str__(self) -> str:
        s = self.req_format
        if self.id:
            s = f"<{'a:' if self.animated else ':'}{s}>"
        return s

    def __eq__(self, other) -> bool:
        if not isinstance(other, PartialEmoji):
            return False
        if self.id:
            return self.id == other.id
        return self.name == other.name

    @property
    def req_format(self) -> str:
        """Format used for web request."""
        if self.id:
            return f"{self.name}:{self.id}"
        else:
            return self.name

classmethod method from_str(emoji_str)

Generate a PartialEmoji from a discord Emoji string representation, or unicode emoji.

Handles

<:emoji_name:emoji_id> :emoji_name:emoji_id a:emoji_name:emoji_id 👋

Parameters:

Name Type Description Default
emoji_str str

The string representation an emoji

required

Returns:

Type Description
PartialEmoji

A PartialEmoji object

Source code in naff/models/discord/emoji.py
@classmethod
def from_str(cls, emoji_str: str) -> "PartialEmoji":
    """
    Generate a PartialEmoji from a discord Emoji string representation, or unicode emoji.

    Handles:
        <:emoji_name:emoji_id>
        :emoji_name:emoji_id
        <a:emoji_name:emoji_id>
        a:emoji_name:emoji_id
        👋

    Args:
        emoji_str: The string representation an emoji

    Returns:
        A PartialEmoji object

    Raises:
        ValueError if the string cannot be parsed

    """
    parsed = emoji_regex.findall(emoji_str)
    if parsed:
        parsed = tuple(filter(None, parsed[0]))
        if len(parsed) == 3:
            return cls(name=parsed[1], id=parsed[2], animated=True)
        else:
            return cls(name=parsed[0], id=parsed[1])
    else:
        return cls(name=emoji_str)

inherited property readonly created_at: models.Timestamp

Returns a timestamp representing the date-time this discord object was created.

:Returns:

inherited method update_from_dict(self, data)

Updates object attribute(s) with new json data received from discord api.

Parameters:

Name Type Description Default
data Dict[str, Any]

The json data received from discord api.

required

Returns:

Type Description
~T

The updated object class instance.

Source code in naff/models/discord/emoji.py
def update_from_dict(self: Type[const.T], data: Dict[str, Any]) -> const.T:
    """
    Updates object attribute(s) with new json data received from discord api.

    Args:
        data: The json data received from discord api.

    Returns:
        The updated object class instance.

    """
    data = self._process_dict(data)
    for key, value in self._filter_kwargs(data, self._get_keys()).items():
        # todo improve
        setattr(self, key, value)

    return self

property readonly req_format: str

Format used for web request.

inherited method to_dict(self)

Exports object into dictionary representation, ready to be sent to discord api.

Returns:

Type Description
Dict[str, Any]

The exported dictionary.

Source code in naff/models/discord/emoji.py
def to_dict(self) -> Dict[str, Any]:
    """
    Exports object into dictionary representation, ready to be sent to discord api.

    Returns:
        The exported dictionary.

    """
    self._check_object()
    return serializer.to_dict(self)

attrs class CustomEmoji (PartialEmoji, ClientObject)

Represent a custom emoji in a guild with all its properties.

Attr attributes:

Name Type Description
require_colons bool

Whether this emoji must be wrapped in colons

managed bool

Whether this emoji is managed

available bool

Whether this emoji can be used, may be false due to loss of Server Boosts.

Source code in naff/models/discord/emoji.py
@define()
class CustomEmoji(PartialEmoji, ClientObject):
    """Represent a custom emoji in a guild with all its properties."""

    _client: "Client" = field(metadata=no_export_meta)

    require_colons: bool = field(default=False)
    """Whether this emoji must be wrapped in colons"""
    managed: bool = field(default=False)
    """Whether this emoji is managed"""
    available: bool = field(default=False)
    """Whether this emoji can be used, may be false due to loss of Server Boosts."""

    _creator_id: Optional["Snowflake_Type"] = field(default=None, converter=optional(to_snowflake))
    _role_ids: List["Snowflake_Type"] = field(factory=list, converter=optional(list_converter(to_snowflake)))
    _guild_id: "Snowflake_Type" = field(default=None, converter=to_snowflake)

    @classmethod
    def _process_dict(cls, data: Dict[str, Any], client: "Client") -> Dict[str, Any]:
        creator_dict = data.pop("user", None)
        data["creator_id"] = client.cache.place_user_data(creator_dict).id if creator_dict else None

        if "roles" in data:
            data["role_ids"] = data.pop("roles")

        return data

    @classmethod
    def from_dict(cls, data: Dict[str, Any], client: "Client", guild_id: int) -> "CustomEmoji":
        data = cls._process_dict(data, client)
        return cls(client=client, guild_id=guild_id, **cls._filter_kwargs(data, cls._get_init_keys()))

    @property
    def guild(self) -> "Guild":
        """The guild this emoji belongs to."""
        return self._client.cache.get_guild(self._guild_id)

    @property
    def creator(self) -> Optional[Union["Member", "User"]]:
        """The member that created this emoji."""
        return self._client.cache.get_member(self._creator_id, self._guild_id) or self._client.cache.get_user(
            self._creator_id
        )

    @property
    def roles(self) -> List["Role"]:
        """The roles allowed to use this emoji."""
        return [self._client.cache.get_role(role_id) for role_id in self._role_ids]

    @property
    def is_usable(self) -> bool:
        """Determines if this emoji is usable by the current user."""
        if not self.available:
            return False

        guild = self.guild
        return any(e_role_id in guild.me._role_ids for e_role_id in self._role_ids)

    async def edit(
        self,
        name: Optional[str] = None,
        roles: Optional[List[Union["Snowflake_Type", "Role"]]] = None,
        reason: Optional[str] = None,
    ) -> "CustomEmoji":
        """
        Modify the custom emoji information.

        Args:
            name: The name of the emoji.
            roles: The roles allowed to use this emoji.
            reason: Attach a reason to this action, used for audit logs.

        Returns:
            The newly modified custom emoji.

        """
        data_payload = dict_filter_none(
            {
                "name": name,
                "roles": roles,
            }
        )

        updated_data = await self._client.http.modify_guild_emoji(data_payload, self._guild_id, self.id, reason=reason)
        self.update_from_dict(updated_data)
        return self

    async def delete(self, reason: Optional[str] = None) -> None:
        """
        Deletes the custom emoji from the guild.

        Args:
            reason: Attach a reason to this action, used for audit logs.

        """
        if not self._guild_id:
            raise ValueError("Cannot delete emoji, no guild id set.")

        await self._client.http.delete_guild_emoji(self._guild_id, self.id, reason=reason)

inherited method update_from_dict(self, data)

Updates object attribute(s) with new json data received from discord api.

Parameters:

Name Type Description Default
data

The json data received from discord api.

required

Returns:

Type Description
~T

The updated object class instance.

Source code in naff/models/discord/emoji.py
def update_from_dict(self, data) -> T:
    data = self._process_dict(data, self._client)
    for key, value in self._filter_kwargs(data, self._get_keys()).items():
        # todo improve
        setattr(self, key, value)

    return self

inherited property readonly created_at: models.Timestamp

Returns a timestamp representing the date-time this discord object was created.

:Returns:

inherited property readonly req_format: str

Format used for web request.

inherited method to_dict(self)

Exports object into dictionary representation, ready to be sent to discord api.

Returns:

Type Description
Dict[str, Any]

The exported dictionary.

Source code in naff/models/discord/emoji.py
def to_dict(self) -> Dict[str, Any]:
    """
    Exports object into dictionary representation, ready to be sent to discord api.

    Returns:
        The exported dictionary.

    """
    self._check_object()
    return serializer.to_dict(self)

classmethod method from_dict(data, client, guild_id)

Process and converts dictionary data received from discord api to object class instance.

Parameters:

Name Type Description Default
data Dict[str, Any]

The json data received from discord api.

required

Returns:

Type Description
CustomEmoji

The object class instance.

Source code in naff/models/discord/emoji.py
@classmethod
def from_dict(cls, data: Dict[str, Any], client: "Client", guild_id: int) -> "CustomEmoji":
    data = cls._process_dict(data, client)
    return cls(client=client, guild_id=guild_id, **cls._filter_kwargs(data, cls._get_init_keys()))

property readonly guild: Guild

The guild this emoji belongs to.

property readonly creator: Union[Member, User]

The member that created this emoji.

property readonly roles: List[Role]

The roles allowed to use this emoji.

property readonly is_usable: bool

Determines if this emoji is usable by the current user.

async method edit(self, name, roles, reason)

Modify the custom emoji information.

Parameters:

Name Type Description Default
name Optional[str]

The name of the emoji.

None
roles Optional[List[Union[Snowflake_Type, Role]]]

The roles allowed to use this emoji.

None
reason Optional[str]

Attach a reason to this action, used for audit logs.

None

Returns:

Type Description
CustomEmoji

The newly modified custom emoji.

Source code in naff/models/discord/emoji.py
async def edit(
    self,
    name: Optional[str] = None,
    roles: Optional[List[Union["Snowflake_Type", "Role"]]] = None,
    reason: Optional[str] = None,
) -> "CustomEmoji":
    """
    Modify the custom emoji information.

    Args:
        name: The name of the emoji.
        roles: The roles allowed to use this emoji.
        reason: Attach a reason to this action, used for audit logs.

    Returns:
        The newly modified custom emoji.

    """
    data_payload = dict_filter_none(
        {
            "name": name,
            "roles": roles,
        }
    )

    updated_data = await self._client.http.modify_guild_emoji(data_payload, self._guild_id, self.id, reason=reason)
    self.update_from_dict(updated_data)
    return self

async method delete(self, reason)

Deletes the custom emoji from the guild.

Parameters:

Name Type Description Default
reason Optional[str]

Attach a reason to this action, used for audit logs.

None
Source code in naff/models/discord/emoji.py
async def delete(self, reason: Optional[str] = None) -> None:
    """
    Deletes the custom emoji from the guild.

    Args:
        reason: Attach a reason to this action, used for audit logs.

    """
    if not self._guild_id:
        raise ValueError("Cannot delete emoji, no guild id set.")

    await self._client.http.delete_guild_emoji(self._guild_id, self.id, reason=reason)

function process_emoji_req_format(emoji)

Processes the emoji parameter into the str format required by the API.

Parameters:

Name Type Description Default
emoji Union[naff.models.discord.emoji.PartialEmoji, dict, str]

The emoji to process.

required

Returns:

Type Description
Optional[str]

formatted string for discord

Source code in naff/models/discord/emoji.py
def process_emoji_req_format(emoji: Optional[Union[PartialEmoji, dict, str]]) -> Optional[str]:
    """
    Processes the emoji parameter into the str format required by the API.

    Args:
        emoji: The emoji to process.

    Returns:
        formatted string for discord

    """
    if not emoji:
        return emoji

    if isinstance(emoji, str):
        emoji = PartialEmoji.from_str(emoji)

    if isinstance(emoji, dict):
        emoji = PartialEmoji.from_dict(emoji)

    if isinstance(emoji, PartialEmoji):
        return emoji.req_format

    raise ValueError(f"Invalid emoji: {emoji}")

function process_emoji(emoji)

Processes the emoji parameter into the dictionary format required by the API.

Parameters:

Name Type Description Default
emoji Union[naff.models.discord.emoji.PartialEmoji, dict, str]

The emoji to process.

required

Returns:

Type Description
Optional[dict]

formatted dictionary for discord

Source code in naff/models/discord/emoji.py
def process_emoji(emoji: Optional[Union[PartialEmoji, dict, str]]) -> Optional[dict]:
    """
    Processes the emoji parameter into the dictionary format required by the API.

    Args:
        emoji: The emoji to process.

    Returns:
        formatted dictionary for discord

    """
    if not emoji:
        return emoji

    if isinstance(emoji, dict):
        return emoji

    if isinstance(emoji, str):
        emoji = PartialEmoji.from_str(emoji)

    if isinstance(emoji, PartialEmoji):
        return emoji.to_dict()

    raise ValueError(f"Invalid emoji: {emoji}")