Utility Functions#

discord.utils.find(predicate, seq)[source]#

A helper to return the first element found in the sequence that meets the predicate. For example:

member = discord.utils.find(lambda m: m.name == 'Mighty', channel.guild.members)

would find the first Member whose name is ‘Mighty’ and return it. If an entry is not found, then None is returned.

This is different from filter() due to the fact it stops the moment it finds a valid entry.

Parameters:
  • predicate (Callable[[T], Any]) – A function that returns a boolean-like result.

  • seq (collections.abc.Iterable) – The iterable to search through.

Return type:

T | None

discord.utils.get(iterable, **attrs)[source]#

A helper that returns the first element in the iterable that meets all the traits passed in attrs. This is an alternative for find().

When multiple attributes are specified, they are checked using logical AND, not logical OR. Meaning they have to meet every attribute passed in and not one of them.

To have a nested attribute search (i.e. search by x.y) then pass in x__y as the keyword argument.

If nothing is found that matches the attributes passed, then None is returned.

Examples

Basic usage:

member = discord.utils.get(message.guild.members, name='Foo')

Multiple attribute matching:

channel = discord.utils.get(guild.voice_channels, name='Foo', bitrate=64000)

Nested attribute matching:

channel = discord.utils.get(client.get_all_channels(), guild__name='Cool', name='general')
Parameters:
  • iterable (Iterable[T]) – An iterable to search through.

  • **attrs (Any) – Keyword arguments that denote attributes to search with.

Return type:

T | None

await discord.utils.get_or_fetch(obj, attr, id, *, default=...)[source]#

This function is a coroutine.

Attempts to get an attribute from the object in cache. If it fails, it will attempt to fetch it. If the fetch also fails, an error will be raised.

Parameters:
  • obj (Any) – The object to use the get or fetch methods in

  • attr (str) – The attribute to get or fetch. Note the object must have both a get_ and fetch_ method for this attribute.

  • id (int) – The ID of the object

  • default (Any) – The default value to return if the object is not found, instead of raising an error.

Returns:

The object found or the default value.

Return type:

Any

Raises:
  • AttributeError – The object is missing a get_ or fetch_ method

  • NotFound – Invalid ID for the object

  • HTTPException – An error occurred fetching the object

  • Forbidden – You do not have permission to fetch the object

Examples

Getting a guild from a guild ID:

guild = await utils.get_or_fetch(client, 'guild', guild_id)

Getting a channel from the guild. If the channel is not found, return None:

channel = await utils.get_or_fetch(guild, 'channel', channel_id, default=None)
discord.utils.oauth_url(client_id, *, permissions=..., guild=..., redirect_uri=..., scopes=..., disable_guild_select=False)[source]#

A helper function that returns the OAuth2 URL for inviting the bot into guilds.

Parameters:
  • client_id (Union[int, str]) – The client ID for your bot.

  • permissions (Permissions) – The permissions you’re requesting. If not given then you won’t be requesting any permissions.

  • guild (Snowflake) – The guild to pre-select in the authorization screen, if available.

  • redirect_uri (str) – An optional valid redirect URI.

  • scopes (Iterable[str]) –

    An optional valid list of scopes. Defaults to ('bot',).

    New in version 1.7.

  • disable_guild_select (bool) –

    Whether to disallow the user from changing the guild dropdown.

    New in version 2.0.

Returns:

The OAuth2 URL for inviting the bot into guilds.

Return type:

str

discord.utils.remove_markdown(text, *, ignore_links=True)[source]#

A helper function that removes markdown characters.

New in version 1.7.

Note

This function is not markdown aware and may remove meaning from the original text. For example, if the input contains 10 * 5 then it will be converted into 10  5.

Parameters:
  • text (str) – The text to remove markdown from.

  • ignore_links (bool) – Whether to leave links alone when removing markdown. For example, if a URL in the text contains characters such as _ then it will be left alone. Defaults to True.

Returns:

The text with the markdown special characters removed.

Return type:

str

discord.utils.escape_markdown(text, *, as_needed=False, ignore_links=True)[source]#

A helper function that escapes Discord’s markdown.

Parameters:
  • text (str) – The text to escape markdown from.

  • as_needed (bool) – Whether to escape the markdown characters as needed. This means that it does not escape extraneous characters if it’s not necessary, e.g. **hello** is escaped into \*\*hello** instead of \*\*hello\*\*. Note however that this can open you up to some clever syntax abuse. Defaults to False.

  • ignore_links (bool) – Whether to leave links alone when escaping markdown. For example, if a URL in the text contains characters such as _ then it will be left alone. This option is not supported with as_needed. Defaults to True.

Returns:

The text with the markdown special characters escaped with a slash.

Return type:

str

discord.utils.escape_mentions(text)[source]#

A helper function that escapes everyone, here, role, and user mentions.

Note

This does not include channel mentions.

Note

For more granular control over what mentions should be escaped within messages, refer to the AllowedMentions class.

Parameters:

text (str) – The text to escape mentions from.

Returns:

The text with the mentions removed.

Return type:

str

discord.utils.raw_mentions(text)[source]#

Returns a list of user IDs matching <@user_id> in the string.

New in version 2.2.

Parameters:

text (str) – The string to get user mentions from.

Returns:

A list of user IDs found in the string.

Return type:

List[int]

discord.utils.raw_channel_mentions(text)[source]#

Returns a list of channel IDs matching <@#channel_id> in the string.

New in version 2.2.

Parameters:

text (str) – The string to get channel mentions from.

Returns:

A list of channel IDs found in the string.

Return type:

List[int]

discord.utils.raw_role_mentions(text)[source]#

Returns a list of role IDs matching <@&role_id> in the string.

New in version 2.2.

Parameters:

text (str) – The string to get role mentions from.

Returns:

A list of role IDs found in the string.

Return type:

List[int]

discord.utils.resolve_invite(invite)[source]#

Resolves an invite from a Invite, URL or code.

Parameters:

invite (Union[Invite, str]) – The invite.

Returns:

The invite code.

Return type:

str

discord.utils.resolve_template(code)[source]#

Resolves a template code from a Template, URL or code.

New in version 1.4.

Parameters:

code (Union[Template, str]) – The code.

Returns:

The template code.

Return type:

str

await discord.utils.sleep_until(when, result=None)[source]#

This function is a coroutine.

Sleep until a specified time.

If the time supplied is in the past this function will yield instantly.

New in version 1.3.

Parameters:
  • when (datetime.datetime) – The timestamp in which to sleep until. If the datetime is naive then it is assumed to be local time.

  • result (Any) – If provided is returned to the caller when the coroutine completes.

Return type:

T | None

discord.utils.utcnow()[source]#

A helper function to return an aware UTC datetime representing the current time.

This should be preferred to datetime.datetime.utcnow() since it is an aware datetime, compared to the naive datetime in the standard library.

New in version 2.0.

Returns:

The current aware datetime in UTC.

Return type:

datetime.datetime

discord.utils.snowflake_time(id)[source]#

Converts a Discord snowflake ID to a UTC-aware datetime object.

Parameters:

id (int) – The snowflake ID.

Returns:

An aware datetime in UTC representing the creation time of the snowflake.

Return type:

datetime.datetime

discord.utils.parse_time(timestamp)[source]#

A helper function to convert an ISO 8601 timestamp to a datetime object.

Parameters:

timestamp (Optional[str]) – The timestamp to convert.

Returns:

The converted datetime object.

Return type:

Optional[datetime.datetime]

discord.utils.format_dt(dt, /, style=None)[source]#

A helper function to format a datetime.datetime for presentation within Discord.

This allows for a locale-independent way of presenting data using Discord specific Markdown.

Style

Example Output

Description

t

22:57

Short Time

T

22:57:58

Long Time

d

17/05/2016

Short Date

D

17 May 2016

Long Date

f (default)

17 May 2016 22:57

Short Date Time

F

Tuesday, 17 May 2016 22:57

Long Date Time

R

5 years ago

Relative Time

Note that the exact output depends on the user’s locale setting in the client. The example output presented is using the en-GB locale.

New in version 2.0.

Parameters:
  • dt (datetime.datetime) – The datetime to format.

  • style (str) – The style to format the datetime with.

Returns:

The formatted string.

Return type:

str

discord.utils.time_snowflake(dt, high=False)[source]#

Returns a numeric snowflake pretending to be created at the given date.

When using as the lower end of a range, use time_snowflake(high=False) - 1 to be inclusive, high=True to be exclusive.

When using as the higher end of a range, use time_snowflake(high=True) + 1 to be inclusive, high=False to be exclusive

Parameters:
  • dt (datetime.datetime) – A datetime object to convert to a snowflake. If naive, the timezone is assumed to be local time.

  • high (bool) – Whether to set the lower 22 bit to high or low.

Returns:

The snowflake representing the time given.

Return type:

int

discord.utils.generate_snowflake(dt=None)[source]#

Returns a numeric snowflake pretending to be created at the given date but more accurate and random than time_snowflake(). If dt is not passed, it makes one from the current time using utcnow.

Parameters:

dt (datetime.datetime) – A datetime object to convert to a snowflake. If naive, the timezone is assumed to be local time.

Returns:

The snowflake representing the time given.

Return type:

int

discord.utils.basic_autocomplete(values)[source]#

A helper function to make a basic autocomplete for slash commands. This is a pretty standard autocomplete and will return any options that start with the value from the user, case-insensitive. If the values parameter is callable, it will be called with the AutocompleteContext.

This is meant to be passed into the discord.Option.autocomplete attribute.

Parameters:

values (Union[Union[Iterable[OptionChoice], Iterable[str], Iterable[int], Iterable[float]], Callable[[AutocompleteContext], Union[Union[Iterable[str], Iterable[int], Iterable[float]], Awaitable[Union[Iterable[str], Iterable[int], Iterable[float]]]]], Awaitable[Union[Iterable[str], Iterable[int], Iterable[float]]]]) – Possible values for the option. Accepts an iterable of str, a callable (sync or async) that takes a single argument of AutocompleteContext, or a coroutine. Must resolve to an iterable of str.

Returns:

A wrapped callback for the autocomplete.

Return type:

Callable[[AutocompleteContext], Awaitable[Union[Iterable[OptionChoice], Iterable[str], Iterable[int], Iterable[float]]]]

Note

Autocomplete cannot be used for options that have specified choices.

Example

Option(str, "color", autocomplete=basic_autocomplete(("red", "green", "blue")))

# or

async def autocomplete(ctx):
    return "foo", "bar", "baz", ctx.interaction.user.name

Option(str, "name", autocomplete=basic_autocomplete(autocomplete))

New in version 2.0.

discord.utils.as_chunks(iterator, max_size)[source]#

A helper function that collects an iterator into chunks of a given size.

New in version 2.0.

Warning

The last chunk collected may not be as large as max_size.

Parameters:
Returns:

A new iterator which yields chunks of a given size.

Return type:

Union[collections.abc.Iterator, collections.abc.AsyncIterator]

discord.utils.filter_params(params, **kwargs)[source]#

A helper function to filter out and replace certain keyword parameters

Parameters:
  • params (Dict[str, Any]) – The initial parameters to filter.

  • **kwargs (Dict[str, Optional[str]]) – Key to value pairs where the key’s contents would be moved to the value, or if the value is None, remove key’s contents (see code example).

Example

>>> params = {"param1": 12, "param2": 13}
>>> filter_params(params, param1="param3", param2=None)
{'param3': 12}
# values of 'param1' is moved to 'param3'
# and values of 'param2' are completely removed.
discord.utils.warn_deprecated(name, instead=None, since=None, removed=None, reference=None)[source]#

Warn about a deprecated function, with the ability to specify details about the deprecation. Emits a DeprecationWarning.

Parameters:
  • name (str) – The name of the deprecated function.

  • instead (Optional[str]) – A recommended alternative to the function.

  • since (Optional[str]) – The version in which the function was deprecated. This should be in the format major.minor(.patch), where the patch version is optional.

  • removed (Optional[str]) – The version in which the function is planned to be removed. This should be in the format major.minor(.patch), where the patch version is optional.

  • reference (Optional[str]) – A reference that explains the deprecation, typically a URL to a page such as a changelog entry or a GitHub issue/PR.

Return type:

None

discord.utils.deprecated(instead=None, since=None, removed=None, reference=None, *, use_qualname=True)[source]#

A decorator implementation of warn_deprecated(). This will automatically call warn_deprecated() when the decorated function is called.

Parameters:
  • instead (Optional[str]) – A recommended alternative to the function.

  • since (Optional[str]) – The version in which the function was deprecated. This should be in the format major.minor(.patch), where the patch version is optional.

  • removed (Optional[str]) – The version in which the function is planned to be removed. This should be in the format major.minor(.patch), where the patch version is optional.

  • reference (Optional[str]) – A reference that explains the deprecation, typically a URL to a page such as a changelog entry or a GitHub issue/PR.

  • use_qualname (bool) – Whether to use the qualified name of the function in the deprecation warning. If False, the short name of the function will be used instead. For example, __qualname__ will display as Client.login while __name__ will display as login. Defaults to True.

Return type:

Callable[[Callable[[P], T]], Callable[[P], T]]