Overview
Pycord provides a variety of utility functions in the discord.utils module to help with common operations.
Search & Filter Functions
find
find(predicate: Callable[[T], Any], seq: Iterable[T]) -> T | None
A helper to return the first element found in the sequence that meets the predicate.
This is different from filter() due to the fact it stops the moment it finds a valid entry.
A function that returns a boolean-like result.
The iterable to search through.
Returns: The first matching element, or None if not found.
Example:
import discord
member = discord.utils.find(lambda m: m.name == 'Mighty', channel.guild.members)
if member:
print(f"Found {member}")
get
get(iterable: Iterable[T], **attrs: Any) -> T | None
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.
To have a nested attribute search (i.e. search by x.y) then pass in x__y as the keyword argument.
An iterable to search through.
Keyword arguments that denote attributes to search with.
Returns: The first matching element, or None if not found.
Examples:
import discord
# 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')
# Get a role by ID
role = discord.utils.get(guild.roles, id=123456789)
get_or_fetch
await get_or_fetch(
obj: Guild | Client,
object_type: Type[T],
object_id: int,
default: Any = MISSING
) -> T | None
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.
The object to operate on.
Type of object to fetch or get (e.g., discord.Member, discord.Role, discord.TextChannel).
The value to return instead of raising if fetching fails.
Returns: The object if found, or default if provided when not found.
Raises:
TypeError - Required parameters are missing or invalid types are provided.
InvalidArgument - 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.
Example:
import discord
# Try to get member from cache, fetch if not cached
member = await discord.utils.get_or_fetch(guild, discord.Member, 123456789)
# With default value
member = await discord.utils.get_or_fetch(
guild,
discord.Member,
123456789,
default=None
)
# Get channel
channel = await discord.utils.get_or_fetch(guild, discord.TextChannel, 987654321)
# Get user from client
user = await discord.utils.get_or_fetch(client, discord.User, 123456789)
Time & Snowflake Functions
snowflake_time
snowflake_time(id: int) -> datetime.datetime
Converts a Discord snowflake ID to a UTC-aware datetime object.
Returns: An aware datetime in UTC representing the creation time of the snowflake.
Example:
import discord
creation_time = discord.utils.snowflake_time(message.id)
print(f"Message created at: {creation_time}")
time_snowflake
time_snowflake(dt: datetime.datetime, high: bool = False) -> int
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.
dt
datetime.datetime
required
A datetime object to convert to a snowflake. If naive, the timezone is assumed to be local time.
Whether to set the lower 22 bits to high or low.
Returns: The snowflake representing the time given.
Example:
import discord
from datetime import datetime, timedelta
# Get messages from the last 24 hours
after = datetime.utcnow() - timedelta(days=1)
after_snowflake = discord.utils.time_snowflake(after)
async for message in channel.history(after=discord.Object(after_snowflake)):
print(message.content)
generate_snowflake
generate_snowflake(dt: datetime.datetime | None = None) -> int
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().
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.
Example:
import discord
# Generate a snowflake for the current time
snowflake = discord.utils.generate_snowflake()
# Generate a snowflake for a specific time
from datetime import datetime
dt = datetime(2023, 1, 1)
snowflake = discord.utils.generate_snowflake(dt)
format_dt(dt: datetime.datetime | datetime.time, /, style: str | None = None) -> str
A helper function to format a datetime for presentation within Discord.
This allows for a locale-independent way of presenting data using Discord specific Markdown.
dt
datetime.datetime | datetime.time
required
The datetime to format.
The style to format the datetime with.Styles:
t - Short Time (22:57)
T - Long Time (22:57:58)
d - Short Date (17/05/2016)
D - Long Date (17 May 2016)
f - Short Date Time (17 May 2016 22:57) - default
F - Long Date Time (Tuesday, 17 May 2016 22:57)
R - Relative Time (5 years ago)
Returns: The formatted string.
Example:
import discord
from datetime import datetime
dt = datetime.now()
# Default format
await channel.send(f"Created {discord.utils.format_dt(dt)}")
# Relative time
await channel.send(f"Created {discord.utils.format_dt(dt, style='R')}")
# Short date
await channel.send(f"Created {discord.utils.format_dt(dt, style='d')}")
utcnow
utcnow() -> datetime.datetime
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.
Returns: The current aware datetime in UTC.
Example:
import discord
now = discord.utils.utcnow()
print(f"Current time: {now}")
sleep_until
await sleep_until(when: datetime.datetime, result: Any = None) -> Any
Sleep until a specified time.
If the time supplied is in the past this function will yield instantly.
when
datetime.datetime
required
The timestamp in which to sleep until. If the datetime is naive then it is assumed to be local time.
If provided is returned to the caller when the coroutine completes.
Example:
import discord
from datetime import datetime, timedelta
# Sleep until tomorrow
tomorrow = datetime.now() + timedelta(days=1)
await discord.utils.sleep_until(tomorrow)
print("It's tomorrow!")
OAuth & URL Functions
oauth_url
oauth_url(
client_id: int | str,
*,
permissions: Permissions = MISSING,
guild: Snowflake = MISSING,
redirect_uri: str = MISSING,
scopes: Iterable[str] = MISSING,
disable_guild_select: bool = False
) -> str
A helper function that returns the OAuth2 URL for inviting the bot into guilds.
The client ID for your bot.
The permissions you’re requesting. If not given then you won’t be requesting any permissions.
The guild to pre-select in the authorization screen, if available.
An optional valid redirect URI.
An optional valid list of scopes. Defaults to ('bot',).
Whether to disallow the user from changing the guild dropdown.
Returns: The OAuth2 URL for inviting the bot into guilds.
Example:
import discord
# Basic invite URL
url = discord.utils.oauth_url(client_id=123456789)
# With permissions
perms = discord.Permissions(send_messages=True, read_messages=True)
url = discord.utils.oauth_url(client_id=123456789, permissions=perms)
# With application commands scope
url = discord.utils.oauth_url(
client_id=123456789,
scopes=['bot', 'applications.commands']
)
print(url)
resolve_invite
resolve_invite(invite: Invite | str) -> str
Resolves an invite from an Invite object, URL or code.
Returns: The invite code.
Example:
import discord
# From URL
code = discord.utils.resolve_invite('https://discord.gg/abc123')
print(code) # 'abc123'
# From code
code = discord.utils.resolve_invite('abc123')
print(code) # 'abc123'
# From Invite object
invite = await client.fetch_invite('abc123')
code = discord.utils.resolve_invite(invite)
print(code) # 'abc123'
resolve_template
resolve_template(code: Template | str) -> str
Resolves a template code from a Template object, URL or code.
Returns: The template code.
Example:
import discord
# From URL
code = discord.utils.resolve_template('https://discord.new/abc123')
print(code) # 'abc123'
# From code
code = discord.utils.resolve_template('abc123')
print(code) # 'abc123'
Text Processing Functions
escape_markdown
escape_markdown(
text: str,
*,
as_needed: bool = False,
ignore_links: bool = True
) -> str
A helper function that escapes Discord’s markdown.
The text to escape markdown from.
Whether to escape the markdown characters as needed. This means that it does not escape extraneous characters if it’s not necessary.
Whether to leave links alone when escaping markdown. This option is not supported with as_needed.
Returns: The text with the markdown special characters escaped with a slash.
Example:
import discord
user_input = "**bold text**"
safe_text = discord.utils.escape_markdown(user_input)
await channel.send(safe_text) # Shows: \*\*bold text\*\*
escape_mentions
escape_mentions(text: str) -> str
A helper function that escapes everyone, here, role, and user mentions.
Note: This does not include channel mentions.
The text to escape mentions from.
Returns: The text with the mentions removed.
Example:
import discord
user_input = "Hey @everyone!"
safe_text = discord.utils.escape_mentions(user_input)
await channel.send(safe_text) # Shows: Hey @everyone!
remove_markdown
remove_markdown(text: str, *, ignore_links: bool = True) -> str
A helper function that removes markdown characters.
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.
The text to remove markdown from.
Whether to leave links alone when removing markdown.
Returns: The text with the markdown special characters removed.
Example:
import discord
formatted_text = "**bold** and *italic*"
plain_text = discord.utils.remove_markdown(formatted_text)
print(plain_text) # "bold and italic"
raw_mentions
raw_mentions(text: str) -> list[int]
Returns a list of user IDs matching <@user_id> in the string.
The string to get user mentions from.
Returns: A list of user IDs found in the string.
Example:
import discord
text = "Hello <@123456789> and <@987654321>!"
user_ids = discord.utils.raw_mentions(text)
print(user_ids) # [123456789, 987654321]
raw_channel_mentions
raw_channel_mentions(text: str) -> list[int]
Returns a list of channel IDs matching <#channel_id> in the string.
The string to get channel mentions from.
Returns: A list of channel IDs found in the string.
Example:
import discord
text = "Check out <#123456789> and <#987654321>!"
channel_ids = discord.utils.raw_channel_mentions(text)
print(channel_ids) # [123456789, 987654321]
raw_role_mentions
raw_role_mentions(text: str) -> list[int]
Returns a list of role IDs matching <@&role_id> in the string.
The string to get role mentions from.
Returns: A list of role IDs found in the string.
Example:
import discord
text = "Mention <@&123456789> and <@&987654321>!"
role_ids = discord.utils.raw_role_mentions(text)
print(role_ids) # [123456789, 987654321]
Iterator Functions
as_chunks
as_chunks(
iterator: Iterator[T] | AsyncIterator[T],
max_size: int
) -> Iterator[list[T]] | AsyncIterator[list[T]]
A helper function that collects an iterator into chunks of a given size.
The last chunk collected may not be as large as max_size.
iterator
Iterator | AsyncIterator
required
The iterator to chunk, can be sync or async.
Returns: A new iterator which yields chunks of a given size.
Example:
import discord
# Chunk a list of members
members = guild.members
for chunk in discord.utils.as_chunks(iter(members), max_size=10):
print(f"Processing {len(chunk)} members")
# Process chunk
# Async example
async for chunk in discord.utils.as_chunks(channel.history(limit=100), max_size=10):
print(f"Got {len(chunk)} messages")
Autocomplete Function
basic_autocomplete
basic_autocomplete(
values: Values,
*,
filter: Callable | None = None
) -> AutocompleteFunc
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.
This is meant to be passed into the discord.Option.autocomplete attribute.
values
Iterable | Callable | Coroutine
required
Possible values for the option. Accepts an iterable of strings, a callable (sync or async) that takes a single argument of AutocompleteContext, or a coroutine.
An optional callable (sync or async) used to filter the autocomplete options. It accepts two arguments: the AutocompleteContext and an item from values iteration.
Returns: A wrapped callback for the autocomplete.
Example:
import discord
from discord import Option
# Basic usage
@bot.slash_command()
async def color(
ctx,
color: Option(
str,
"Pick a color",
autocomplete=discord.utils.basic_autocomplete(["red", "green", "blue"])
)
):
await ctx.respond(f"You picked {color}")
# With dynamic values
async def get_colors(ctx):
# Return colors based on user or guild
return ["red", "green", "blue", ctx.interaction.user.name]
@bot.slash_command()
async def dynamic_color(
ctx,
color: Option(
str,
"Pick a color",
autocomplete=discord.utils.basic_autocomplete(get_colors)
)
):
await ctx.respond(f"You picked {color}")
# With custom filter
@bot.slash_command()
async def filtered_color(
ctx,
color: Option(
str,
"Pick a color",
autocomplete=discord.utils.basic_autocomplete(
["red", "green", "blue"],
filter=lambda c, i: str(c.value or "") in i
)
)
):
await ctx.respond(f"You picked {color}")
Other Utility Functions
parse_time
parse_time(timestamp: str | None) -> datetime.datetime | None
A helper function to convert an ISO 8601 timestamp to a datetime object.
The timestamp to convert.
Returns: The converted datetime object, or None if timestamp is None.
Example:
import discord
timestamp_str = "2023-01-01T12:00:00+00:00"
dt = discord.utils.parse_time(timestamp_str)
print(dt) # 2023-01-01 12:00:00+00:00
users_to_csv
users_to_csv(users: Iterable[Snowflake]) -> io.BytesIO
Converts an iterable of users to a CSV file-like object for usage in GuildChannel.create_invite() and Invite.edit_target_users().
users
Iterable[Snowflake]
required
An iterable of users to convert.
Returns: A file-like object containing the CSV data.
Example:
import discord
users = [member1, member2, member3]
csv_data = discord.utils.users_to_csv(users)
# Use this CSV data with invite creation
Constants
MISSING
A sentinel value used throughout Pycord to indicate that a parameter was not provided.
import discord
if some_value is discord.utils.MISSING:
print("Value was not provided")