Utility Functions¶
- discord.utils.find(predicate, seq)[ソース]¶
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
Memberwhose name is 'Mighty' and return it. If an entry is not found, thenNoneis returned.This is different from
filter()due to the fact it stops the moment it finds a valid entry.
- discord.utils.get(iterable, **attrs)[ソース]¶
A helper that returns the first element in the iterable that meets all the traits passed in
attrs. This is an alternative forfind().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 inx__yas the keyword argument.If nothing is found that matches the attributes passed, then
Noneis returned.サンプル
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')
- await discord.utils.get_or_fetch(obj, object_type=..., object_id=..., default=..., attr=..., id=...)[ソース]¶
Shortcut method to get data from an object either by returning the cached version, or if it does not exist, attempting to fetch it from the API.
- パラメータ:
object_type (
type[TypeVar(_FETCHABLE, bound= VoiceChannel | TextChannel | ForumChannel | StageChannel | CategoryChannel | Thread | Member | User | Guild | Role | GuildEmoji | AppEmoji)]) -- Type of object to fetch or get.default (
TypeVar(_D)) -- The value to return instead of raising if fetching fails.attr (
str)id (
int)
- 戻り値:
The object if found, or default if provided when not found. Returns
Noneonly if object_id isNoneand no default is given.- 戻り値の型:
TypeVar(_FETCHABLE, bound= VoiceChannel | TextChannel | ForumChannel | StageChannel | CategoryChannel | Thread | Member | User | Guild | Role | GuildEmoji | AppEmoji) |TypeVar(_D) |None- 例外:
TypeError -- Raised when required parameters are missing or invalid types are provided.
InvalidArgument -- Raised when an unsupported or incompatible object type is used.
NotFound -- Invalid ID for the object.
HTTPException -- An error occurred fetching the object.
Forbidden -- You do not have permission to fetch the object.
InvalidData -- Raised when the object resolves to a different guild.
- discord.utils.oauth_url(client_id, *, permissions=..., guild=..., redirect_uri=..., scopes=..., disable_guild_select=False)[ソース]¶
A helper function that returns the OAuth2 URL for inviting the bot into guilds.
- パラメータ:
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.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.
- 戻り値:
The OAuth2 URL for inviting the bot into guilds.
- 戻り値の型:
- discord.utils.remove_markdown(text, *, ignore_links=True)[ソース]¶
A helper function that removes markdown characters.
Added in version 1.7.
注釈
This function is not markdown aware and may remove meaning from the original text. For example, if the input contains
10 * 5then it will be converted into10 5.- パラメータ:
- 戻り値:
The text with the markdown special characters removed.
- 戻り値の型:
- discord.utils.escape_markdown(text, *, as_needed=False, ignore_links=True)[ソース]¶
A helper function that escapes Discord's markdown.
- パラメータ:
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.
- 戻り値:
The text with the markdown special characters escaped with a slash.
- 戻り値の型:
- discord.utils.escape_mentions(text)[ソース]¶
A helper function that escapes everyone, here, role, and user mentions.
注釈
This does not include channel mentions.
注釈
For more granular control over what mentions should be escaped within messages, refer to the
AllowedMentionsclass.
- discord.utils.raw_mentions(text)[ソース]¶
Returns a list of user IDs matching
<@user_id>in the string.Added in version 2.2.
- discord.utils.raw_channel_mentions(text)[ソース]¶
Returns a list of channel IDs matching
<@#channel_id>in the string.Added in version 2.2.
- discord.utils.raw_role_mentions(text)[ソース]¶
Returns a list of role IDs matching
<@&role_id>in the string.Added in version 2.2.
- discord.utils.resolve_template(code)[ソース]¶
Resolves a template code from a
Template, URL or code.Added in version 1.4.
- await discord.utils.sleep_until(when, result=None)[ソース]¶
This function is a coroutine.
Sleep until a specified time.
If the time supplied is in the past this function will yield instantly.
Added in version 1.3.
- discord.utils.utcnow()[ソース]¶
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.
- 戻り値:
The current aware datetime in UTC.
- 戻り値の型:
- discord.utils.snowflake_time(id)[ソース]¶
Converts a Discord snowflake ID to a UTC-aware datetime object.
- discord.utils.parse_time(timestamp)[ソース]¶
A helper function to convert an ISO 8601 timestamp to a datetime object.
- discord.utils.format_dt(dt, /, style=None)[ソース]¶
A helper function to format a
datetime.datetimefor 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-GBlocale.Added in version 2.0.
- discord.utils.time_snowflake(dt, high=False)[ソース]¶
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) - 1to be inclusive,high=Trueto be exclusive.When using as the higher end of a range, use
time_snowflake(high=True) + 1to be inclusive,high=Falseto be exclusive
- discord.utils.generate_snowflake(dt=None)[ソース]¶
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.
- discord.utils.basic_autocomplete(values, *, filter=None)[ソース]¶
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
valuesparameter is callable, it will be called with the AutocompleteContext.This is meant to be passed into the
discord.Option.autocompleteattribute.- パラメータ:
values (
Iterable[Any] |Iterable[str] |Iterable[int] |Iterable[float] |Callable[[Any],Iterable[Any] |Iterable[str] |Iterable[int] |Iterable[float] |Awaitable[Iterable[Any] |Iterable[str] |Iterable[int] |Iterable[float]]] |Awaitable[Iterable[Any] |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 (
Callable[[Any,Any],bool|Awaitable[bool]] |None) --An optional callable (sync or async) used to filter the autocomplete options. It accepts two arguments: the
AutocompleteContextand an item fromvaluesiteration treated as callback parameters. IfNoneis 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.
- 戻り値:
A wrapped callback for the autocomplete.
- 戻り値の型:
Callable[[Any],Awaitable[Iterable[Any] |Iterable[str] |Iterable[int] |Iterable[float]]]
サンプル
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.
注釈
Autocomplete cannot be used for options that have specified choices.
- discord.utils.as_chunks(iterator, max_size)[ソース]¶
A helper function that collects an iterator into chunks of a given size.
Added in version 2.0.
警告
The last chunk collected may not be as large as
max_size.
- discord.utils.filter_params(params, **kwargs)[ソース]¶
A helper function to filter out and replace certain keyword parameters
- パラメータ:
サンプル
>>> 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, stacklevel=3)[ソース]¶
Warn about a deprecated function, with the ability to specify details about the deprecation. Emits a DeprecationWarning.
- パラメータ:
name (
str) -- The name of the deprecated function.instead (
str|None) -- A recommended alternative to the function.since (
str|None) -- The version in which the function was deprecated. This should be in the formatmajor.minor(.patch), where the patch version is optional.removed (
str|None) -- The version in which the function is planned to be removed. This should be in the formatmajor.minor(.patch), where the patch version is optional.reference (
str|None) -- A reference that explains the deprecation, typically a URL to a page such as a changelog entry or a GitHub issue/PR.stacklevel (
int) -- The stacklevel kwarg passed towarnings.warn(). Defaults to 3.
- 戻り値の型:
- discord.utils.deprecated(instead=None, since=None, removed=None, reference=None, stacklevel=3, *, use_qualname=True)[ソース]¶
A decorator implementation of
warn_deprecated(). This will automatically callwarn_deprecated()when the decorated function is called.バージョン 2.8 で非推奨: Deprecated in favor of
warnings.deprecated().- パラメータ:
instead (
str|None) -- A recommended alternative to the function.since (
str|None) -- The version in which the function was deprecated. This should be in the formatmajor.minor(.patch), where the patch version is optional.removed (
str|None) -- The version in which the function is planned to be removed. This should be in the formatmajor.minor(.patch), where the patch version is optional.reference (
str|None) -- A reference that explains the deprecation, typically a URL to a page such as a changelog entry or a GitHub issue/PR.stacklevel (
int) -- The stacklevel kwarg passed towarnings.warn(). Defaults to 3.use_qualname (
bool) -- Whether to use the qualified name of the function in the deprecation warning. IfFalse, the short name of the function will be used instead. For example, __qualname__ will display asClient.loginwhile __name__ will display aslogin. Defaults toTrue.
- 戻り値の型:
Callable[[Callable[[ParamSpec(P, bound=None)],TypeVar(T)]],Callable[[ParamSpec(P, bound=None)],TypeVar(T)]]
- discord.utils.users_to_csv(users)[ソース]¶
Converts an iterable of users to a CSV file-like object for usage in
create_invite()andedit_target_users().