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, thenNone
is returned.This is different from
filter()
due to the fact it stops the moment it finds a valid entry.
- await discord.utils.get_or_fetch(obj, attr, id, *, default=Undefined.MISSING)[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 aget_
andfetch_
method for this attribute.id (
int
) – The ID of the objectdefault (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_
orfetch_
methodNotFound – 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=Undefined.MISSING, guild=Undefined.MISSING, redirect_uri=Undefined.MISSING, scopes=Undefined.MISSING, disable_guild_select=False)[source]¶
A helper function that returns the OAuth2 URL for inviting the bot into guilds.
- Parameters:
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',)
.Added in version 1.7.
disable_guild_select (
bool
) –Whether to disallow the user from changing the guild dropdown.
Added in version 2.0.
- Returns:
The OAuth2 URL for inviting the bot into guilds.
- Return type:
- discord.utils.remove_markdown(text, *, ignore_links=True)[source]¶
A helper function that removes markdown characters.
Added 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 into10 5
.- Parameters:
- Returns:
The text with the markdown special characters removed.
- Return type:
- 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 toFalse
.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 withas_needed
. Defaults toTrue
.
- Returns:
The text with the markdown special characters escaped with a slash.
- Return type:
- 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.
- discord.utils.raw_mentions(text)[source]¶
Returns a list of user IDs matching
<@user_id>
in the string.Added in version 2.2.
- discord.utils.raw_channel_mentions(text)[source]¶
Returns a list of channel IDs matching
<@#channel_id>
in the string.Added in version 2.2.
- discord.utils.raw_role_mentions(text)[source]¶
Returns a list of role IDs matching
<@&role_id>
in the string.Added in version 2.2.
- 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.Added in version 2.0.
- Returns:
The current aware datetime in UTC.
- Return type:
- 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:
- 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.Added in version 2.0.
- Parameters:
dt (Union[
datetime.datetime
,datetime.time
]) – The datetime to format.style (:class:`str`R) – The style to format the datetime with.
- Returns:
The formatted string.
- Return type:
- discord.utils.generate_snowflake(dt=None, *, mode='boundary', high=False)[source]¶
Returns a numeric snowflake pretending to be created at the given date.
This function can generate both realistic snowflakes (for general use) and boundary snowflakes (for range queries).
- Parameters:
dt (
datetime.datetime
) – A datetime object to convert to a snowflake. If naive, the timezone is assumed to be local time. If None, uses current UTC time.mode (
str
) – The type of snowflake to generate: - “realistic”: Creates a snowflake with random-like lower bits - “boundary”: Creates a snowflake for range queries (default)high (
bool
) – Only used when mode=”boundary”. Whether to set the lower 22 bits to high (True) or low (False). Default is False.
- Returns:
The snowflake representing the time given.
- Return type:
Examples
# Generate realistic snowflake snowflake = generate_snowflake(dt)
# Generate boundary snowflakes lower_bound = generate_snowflake(dt, mode=”boundary”, high=False) upper_bound = generate_snowflake(dt, mode=”boundary”, high=True)
# For inclusive ranges: # Lower: generate_snowflake(dt, mode=”boundary”, high=False) - 1 # Upper: generate_snowflake(dt, mode=”boundary”, high=True) + 1
- discord.utils.basic_autocomplete(values, *, filter=None)[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 ofstr
, a callable (sync or async) that takes a single argument ofAutocompleteContext
, or a coroutine. Must resolve to an iterable ofstr
.filter (Optional[Callable[[
AutocompleteContext
, Any], Union[bool
, Awaitable[bool
]]]]) –An optional callable (sync or async) used to filter the autocomplete options. It accepts two arguments: the
AutocompleteContext
and an item fromvalues
iteration treated as callback parameters. IfNone
is provided, a default filter is used that includes items whose string representation starts with the user’s input value, case-insensitive.Added in version 2.7.
- Returns:
A wrapped callback for the autocomplete.
- Return type:
Callable[[
AutocompleteContext
], Awaitable[Union[Iterable[OptionChoice
], Iterable[str
], Iterable[int
], Iterable[float
]]]]
Examples
Basic usage:
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))
With filter parameter:
Option( str, "color", autocomplete=basic_autocomplete(("red", "green", "blue"), filter=lambda c, i: str(c.value or "") in i), )
Added in version 2.0.
Note
Autocomplete cannot be used for options that have specified choices.