Event Reference¶
This section outlines the different types of events in Pycord. Events are class-based objects that inherit from
Event and are dispatched by the Discord gateway when certain actions occur.
See also
For information about the Gears system and modular event handling, see Gears.
Listening to Events¶
There are two main ways to listen to events in Pycord:
Using
Client.listen()decorator - This allows you to register typed event listeners directly on the client.Using Gears - A modular event handling system that allows you to organize event listeners into reusable components.
Using the listen() Decorator¶
The modern way to register event listeners is by using the listen() decorator with typed event classes:
import discord
from discord.events import MessageCreate, Ready
client = discord.Client(intents=discord.Intents.default())
@client.listen()
async def on_message(event: MessageCreate) -> None:
if event.author == client.user:
return
if event.content.startswith('$hello'):
await event.channel.send('Hello World!')
@client.listen(once=True)
async def on_ready(event: Ready) -> None:
print("Client is ready!")
client.run("TOKEN")
Note that:
Event listeners use type annotations to specify which event they handle
Event objects may inherit from domain models (e.g.,
MessageCreateinherits fromMessage)The
once=Trueparameter creates a one-time listener that is automatically removed after being called onceAll event listeners must be coroutines (
async deffunctions)
Using Gears¶
For more organized code, especially in larger bots, you can use the Gears system:
from discord.gears import Gear
from discord.events import Ready, MessageCreate
class MyGear(Gear):
@Gear.listen()
async def on_ready(self, event: Ready) -> None:
print("Bot is ready!")
@Gear.listen()
async def on_message(self, event: MessageCreate) -> None:
print(f"Message: {event.content}")
bot = discord.Bot()
bot.attach_gear(MyGear())
bot.run("TOKEN")
See Gears for more information on using Gears.
Warning
All event listeners must be coroutine. If they aren’t, then you might get unexpected
errors. In order to turn a function into a coroutine they must be async def functions.
Event Classes¶
All events inherit from the base Event class. Events are typed objects that
contain data related to the specific Discord gateway event that occurred.
Some event classes inherit from domain models, meaning they have all the attributes and methods of that model. For example:
MessageCreateinherits fromMessageGuildMemberJoininherits fromMember
Events that don’t inherit from a domain model will have specific attributes for accessing event data.
Many events also include a raw attribute that contains the raw event payload data from Discord, which can be
useful for accessing data that may not be in the cache.
Available Events¶
Below is a comprehensive list of all events available in Pycord, organized by category.
Audit Logs¶
- class discord.events.GuildAuditLogEntryCreate[source]¶
Called when an audit log entry is created.
The bot must have
view_audit_logto receive this, andIntents.moderationmust be enabled.This event inherits from
AuditLogEntry.- raw¶
The raw event payload data.
- Type:
RawAuditLogEntryEvent
- property after: AuditLogDiff¶
The target’s subsequent state.
- property before: AuditLogDiff¶
The target’s prior state.
- property category: AuditLogActionCategory¶
The category of the action, if applicable.
- await changes()¶
The list of changes this entry has.
- Return type:
AuditLogChanges
AutoMod¶
- class discord.events.AutoModRuleCreate[source]¶
Called when an auto moderation rule is created.
The bot must have
manage_guildto receive this, andIntents.auto_moderation_configurationmust be enabled.- rule¶
The newly created rule.
- Type:
AutoModRule
- class discord.events.AutoModRuleUpdate[source]¶
Called when an auto moderation rule is updated.
The bot must have
manage_guildto receive this, andIntents.auto_moderation_configurationmust be enabled.- rule¶
The updated rule.
- Type:
AutoModRule
Channels¶
- class discord.events.ChannelCreate[source]¶
Called when a guild channel is created.
This requires
Intents.guildsto be enabled.This event inherits from the actual channel type that was created (e.g.,
TextChannel,VoiceChannel,ForumChannel, etc.). You can access all channel attributes directly on the event object.Note
While this class shows
GuildChannelin the signature, at runtime the event will be an instance of the specific channel type that was created.- property category: CategoryChannel | None¶
The category this channel belongs to.
If there is no category then this is
None.
- property changed_roles: list[Role]¶
Returns a list of roles that have been overridden from their default values in the
rolesattribute.
- await clone(*, name=None, reason=None)¶
This function is a coroutine.
Clones this channel. This creates a channel with the same properties as this channel.
You must have the
manage_channelspermission to do this.Added in version 1.1.
- Parameters:
- Returns:
The channel that was created.
- Return type:
- Raises:
Forbidden – You do not have the proper permissions to create this channel.
HTTPException – Creating the channel failed.
- await create_invite(*, reason=None, max_age=0, max_uses=0, temporary=False, unique=True, target_event=None, target_type=None, target_user=None, target_application_id=None)¶
This function is a coroutine.
Creates an instant invite from a text or voice channel.
You must have the
create_instant_invitepermission to do this.- Parameters:
max_age (
int) – How long the invite should last in seconds. If it’s 0 then the invite doesn’t expire. Defaults to0.max_uses (
int) – How many uses the invite could be used for. If it’s 0 then there are unlimited uses. Defaults to0.temporary (
bool) – Denotes that the invite grants temporary membership (i.e. they get kicked after they disconnect). Defaults toFalse.unique (
bool) – Indicates if a unique invite URL should be created. Defaults to True. If this is set toFalsethen it will return a previously created invite.reason (Optional[
str]) – The reason for creating this invite. Shows up on the audit log.target_type (Optional[
InviteTarget]) –The type of target for the voice channel invite, if any.
Added in version 2.0.
target_user (Optional[
User]) –The user whose stream to display for this invite, required if target_type is TargetType.stream. The user must be streaming in the channel.
Added in version 2.0.
target_application_id (Optional[
int]) –The id of the embedded application for the invite, required if target_type is TargetType.embedded_application.
Added in version 2.0.
target_event (Optional[
ScheduledEvent]) –The scheduled event object to link to the event. Shortcut to
Invite.set_scheduled_event()See
Invite.set_scheduled_event()for more info on event invite linking.Added in version 2.0.
- Returns:
The invite that was created.
- Return type:
- Raises:
HTTPException – Invite creation failed.
NotFound – The channel that was passed is a category or an invalid channel.
- await delete(*, reason=None)¶
This function is a coroutine.
Deletes the channel.
You must have
manage_channelspermission to use this.- Parameters:
reason (Optional[
str]) – The reason for deleting this channel. Shows up on the audit log.- Raises:
Forbidden – You do not have proper permissions to delete the channel.
NotFound – The channel was not found or was already deleted.
HTTPException – Deleting the channel failed.
- Return type:
- await get_overwrites()¶
Returns all of the channel’s overwrites.
This is returned as a dictionary where the key contains the target which can be either a
Roleor aMemberand the value is the overwrite as aPermissionOverwrite.- Returns:
The channel’s permission overwrites.
- Return type:
Dict[Union[
Role,Member,Object],PermissionOverwrite]
- await invites()¶
This function is a coroutine.
Returns a list of all active instant invites from this channel.
You must have
manage_channelsto get this information.- Returns:
The list of invites that are currently active.
- Return type:
List[
Invite]- Raises:
Forbidden – You do not have proper permissions to get the information.
HTTPException – An error occurred while fetching the information.
- property jump_url: str¶
Returns a URL that allows the client to jump to the channel.
Added in version 2.0.
- property members: Collection[Member]¶
Returns all members that can view this channel.
This is calculated based on the channel’s permission overwrites and the members’ roles.
- Returns:
All members who have permission to view this channel.
- Return type:
Collection[
Member]
- overwrites_for(obj)¶
Returns the channel-specific overwrites for a member or a role.
- await permissions_are_synced()¶
Whether the permissions for this channel are synced with the category it belongs to.
If there is no category then this is
False. :rtype:boolAdded in version 3.0.
- permissions_for(obj, /)¶
Handles permission resolution for the
MemberorRole.This function takes into consideration the following cases:
Guild owner
Guild roles
Channel overrides
Member overrides
If a
Roleis passed, then it checks the permissions someone with that role would have, which is essentially:The default role permissions
The permissions of the role used as a parameter
The default role permission overwrites
The permission overwrites of the role used as a parameter
Changed in version 2.0: The object passed in can now be a role object.
- await set_permissions(target, *, overwrite=Undefined.MISSING, reason=None, **permissions)¶
This function is a coroutine.
Sets the channel specific permission overwrites for a target in the channel.
The
targetparameter should either be aMemberor aRolethat belongs to guild.The
overwriteparameter, if given, must either beNoneorPermissionOverwrite. For convenience, you can pass in keyword arguments denotingPermissionsattributes. If this is done, then you cannot mix the keyword arguments with theoverwriteparameter.If the
overwriteparameter isNone, then the permission overwrites are deleted.You must have the
manage_rolespermission to use this.Note
This method replaces the old overwrites with the ones given.
Examples
Setting allow and deny:
await message.channel.set_permissions(message.author, read_messages=True, send_messages=False)
Deleting overwrites
await channel.set_permissions(member, overwrite=None)
Using
PermissionOverwriteoverwrite = discord.PermissionOverwrite() overwrite.send_messages = False overwrite.read_messages = True await channel.set_permissions(member, overwrite=overwrite)
- Parameters:
target (Union[
Member,Role]) – The member or role to overwrite permissions for.overwrite (Optional[
PermissionOverwrite]) – The permissions to allow and deny to the target, orNoneto delete the overwrite.**permissions (
bool) – A keyword argument list of permissions to set for ease of use. Cannot be mixed withoverwrite.reason (Optional[
str]) – The reason for doing this action. Shows up on the audit log.
- Raises:
Forbidden – You do not have permissions to edit channel specific permissions.
HTTPException – Editing channel specific permissions failed.
NotFound – The role or member being edited is not part of the guild.
InvalidArgument – The overwrite parameter invalid or the target type was not
RoleorMember.
- Return type:
- property type: ChannelType¶
The channel’s Discord channel type.
- class discord.events.ChannelDelete[source]¶
Called when a guild channel is deleted.
This requires
Intents.guildsto be enabled.This event inherits from the actual channel type that was deleted (e.g.,
TextChannel,VoiceChannel,ForumChannel, etc.). You can access all channel attributes directly on the event object.Note
While this class shows
GuildChannelin the signature, at runtime the event will be an instance of the specific channel type that was deleted.- property category: CategoryChannel | None¶
The category this channel belongs to.
If there is no category then this is
None.
- property changed_roles: list[Role]¶
Returns a list of roles that have been overridden from their default values in the
rolesattribute.
- await clone(*, name=None, reason=None)¶
This function is a coroutine.
Clones this channel. This creates a channel with the same properties as this channel.
You must have the
manage_channelspermission to do this.Added in version 1.1.
- Parameters:
- Returns:
The channel that was created.
- Return type:
- Raises:
Forbidden – You do not have the proper permissions to create this channel.
HTTPException – Creating the channel failed.
- await create_invite(*, reason=None, max_age=0, max_uses=0, temporary=False, unique=True, target_event=None, target_type=None, target_user=None, target_application_id=None)¶
This function is a coroutine.
Creates an instant invite from a text or voice channel.
You must have the
create_instant_invitepermission to do this.- Parameters:
max_age (
int) – How long the invite should last in seconds. If it’s 0 then the invite doesn’t expire. Defaults to0.max_uses (
int) – How many uses the invite could be used for. If it’s 0 then there are unlimited uses. Defaults to0.temporary (
bool) – Denotes that the invite grants temporary membership (i.e. they get kicked after they disconnect). Defaults toFalse.unique (
bool) – Indicates if a unique invite URL should be created. Defaults to True. If this is set toFalsethen it will return a previously created invite.reason (Optional[
str]) – The reason for creating this invite. Shows up on the audit log.target_type (Optional[
InviteTarget]) –The type of target for the voice channel invite, if any.
Added in version 2.0.
target_user (Optional[
User]) –The user whose stream to display for this invite, required if target_type is TargetType.stream. The user must be streaming in the channel.
Added in version 2.0.
target_application_id (Optional[
int]) –The id of the embedded application for the invite, required if target_type is TargetType.embedded_application.
Added in version 2.0.
target_event (Optional[
ScheduledEvent]) –The scheduled event object to link to the event. Shortcut to
Invite.set_scheduled_event()See
Invite.set_scheduled_event()for more info on event invite linking.Added in version 2.0.
- Returns:
The invite that was created.
- Return type:
- Raises:
HTTPException – Invite creation failed.
NotFound – The channel that was passed is a category or an invalid channel.
- await delete(*, reason=None)¶
This function is a coroutine.
Deletes the channel.
You must have
manage_channelspermission to use this.- Parameters:
reason (Optional[
str]) – The reason for deleting this channel. Shows up on the audit log.- Raises:
Forbidden – You do not have proper permissions to delete the channel.
NotFound – The channel was not found or was already deleted.
HTTPException – Deleting the channel failed.
- Return type:
- await get_overwrites()¶
Returns all of the channel’s overwrites.
This is returned as a dictionary where the key contains the target which can be either a
Roleor aMemberand the value is the overwrite as aPermissionOverwrite.- Returns:
The channel’s permission overwrites.
- Return type:
Dict[Union[
Role,Member,Object],PermissionOverwrite]
- await invites()¶
This function is a coroutine.
Returns a list of all active instant invites from this channel.
You must have
manage_channelsto get this information.- Returns:
The list of invites that are currently active.
- Return type:
List[
Invite]- Raises:
Forbidden – You do not have proper permissions to get the information.
HTTPException – An error occurred while fetching the information.
- property jump_url: str¶
Returns a URL that allows the client to jump to the channel.
Added in version 2.0.
- property members: Collection[Member]¶
Returns all members that can view this channel.
This is calculated based on the channel’s permission overwrites and the members’ roles.
- Returns:
All members who have permission to view this channel.
- Return type:
Collection[
Member]
- overwrites_for(obj)¶
Returns the channel-specific overwrites for a member or a role.
- await permissions_are_synced()¶
Whether the permissions for this channel are synced with the category it belongs to.
If there is no category then this is
False. :rtype:boolAdded in version 3.0.
- permissions_for(obj, /)¶
Handles permission resolution for the
MemberorRole.This function takes into consideration the following cases:
Guild owner
Guild roles
Channel overrides
Member overrides
If a
Roleis passed, then it checks the permissions someone with that role would have, which is essentially:The default role permissions
The permissions of the role used as a parameter
The default role permission overwrites
The permission overwrites of the role used as a parameter
Changed in version 2.0: The object passed in can now be a role object.
- await set_permissions(target, *, overwrite=Undefined.MISSING, reason=None, **permissions)¶
This function is a coroutine.
Sets the channel specific permission overwrites for a target in the channel.
The
targetparameter should either be aMemberor aRolethat belongs to guild.The
overwriteparameter, if given, must either beNoneorPermissionOverwrite. For convenience, you can pass in keyword arguments denotingPermissionsattributes. If this is done, then you cannot mix the keyword arguments with theoverwriteparameter.If the
overwriteparameter isNone, then the permission overwrites are deleted.You must have the
manage_rolespermission to use this.Note
This method replaces the old overwrites with the ones given.
Examples
Setting allow and deny:
await message.channel.set_permissions(message.author, read_messages=True, send_messages=False)
Deleting overwrites
await channel.set_permissions(member, overwrite=None)
Using
PermissionOverwriteoverwrite = discord.PermissionOverwrite() overwrite.send_messages = False overwrite.read_messages = True await channel.set_permissions(member, overwrite=overwrite)
- Parameters:
target (Union[
Member,Role]) – The member or role to overwrite permissions for.overwrite (Optional[
PermissionOverwrite]) – The permissions to allow and deny to the target, orNoneto delete the overwrite.**permissions (
bool) – A keyword argument list of permissions to set for ease of use. Cannot be mixed withoverwrite.reason (Optional[
str]) – The reason for doing this action. Shows up on the audit log.
- Raises:
Forbidden – You do not have permissions to edit channel specific permissions.
HTTPException – Editing channel specific permissions failed.
NotFound – The role or member being edited is not part of the guild.
InvalidArgument – The overwrite parameter invalid or the target type was not
RoleorMember.
- Return type:
- property type: ChannelType¶
The channel’s Discord channel type.
- class discord.events.ChannelUpdate[source]¶
Internal event that dispatches to either
PrivateChannelUpdateorGuildChannelUpdate.This event is not directly received by user code. It automatically routes to the appropriate specific channel update event based on the channel type.
- property category: CategoryChannel | None¶
The category this channel belongs to.
If there is no category then this is
None.
- property changed_roles: list[Role]¶
Returns a list of roles that have been overridden from their default values in the
rolesattribute.
- await clone(*, name=None, reason=None)¶
This function is a coroutine.
Clones this channel. This creates a channel with the same properties as this channel.
You must have the
manage_channelspermission to do this.Added in version 1.1.
- Parameters:
- Returns:
The channel that was created.
- Return type:
- Raises:
Forbidden – You do not have the proper permissions to create this channel.
HTTPException – Creating the channel failed.
- await create_invite(*, reason=None, max_age=0, max_uses=0, temporary=False, unique=True, target_event=None, target_type=None, target_user=None, target_application_id=None)¶
This function is a coroutine.
Creates an instant invite from a text or voice channel.
You must have the
create_instant_invitepermission to do this.- Parameters:
max_age (
int) – How long the invite should last in seconds. If it’s 0 then the invite doesn’t expire. Defaults to0.max_uses (
int) – How many uses the invite could be used for. If it’s 0 then there are unlimited uses. Defaults to0.temporary (
bool) – Denotes that the invite grants temporary membership (i.e. they get kicked after they disconnect). Defaults toFalse.unique (
bool) – Indicates if a unique invite URL should be created. Defaults to True. If this is set toFalsethen it will return a previously created invite.reason (Optional[
str]) – The reason for creating this invite. Shows up on the audit log.target_type (Optional[
InviteTarget]) –The type of target for the voice channel invite, if any.
Added in version 2.0.
target_user (Optional[
User]) –The user whose stream to display for this invite, required if target_type is TargetType.stream. The user must be streaming in the channel.
Added in version 2.0.
target_application_id (Optional[
int]) –The id of the embedded application for the invite, required if target_type is TargetType.embedded_application.
Added in version 2.0.
target_event (Optional[
ScheduledEvent]) –The scheduled event object to link to the event. Shortcut to
Invite.set_scheduled_event()See
Invite.set_scheduled_event()for more info on event invite linking.Added in version 2.0.
- Returns:
The invite that was created.
- Return type:
- Raises:
HTTPException – Invite creation failed.
NotFound – The channel that was passed is a category or an invalid channel.
- await delete(*, reason=None)¶
This function is a coroutine.
Deletes the channel.
You must have
manage_channelspermission to use this.- Parameters:
reason (Optional[
str]) – The reason for deleting this channel. Shows up on the audit log.- Raises:
Forbidden – You do not have proper permissions to delete the channel.
NotFound – The channel was not found or was already deleted.
HTTPException – Deleting the channel failed.
- Return type:
- await get_overwrites()¶
Returns all of the channel’s overwrites.
This is returned as a dictionary where the key contains the target which can be either a
Roleor aMemberand the value is the overwrite as aPermissionOverwrite.- Returns:
The channel’s permission overwrites.
- Return type:
Dict[Union[
Role,Member,Object],PermissionOverwrite]
- await invites()¶
This function is a coroutine.
Returns a list of all active instant invites from this channel.
You must have
manage_channelsto get this information.- Returns:
The list of invites that are currently active.
- Return type:
List[
Invite]- Raises:
Forbidden – You do not have proper permissions to get the information.
HTTPException – An error occurred while fetching the information.
- property jump_url: str¶
Returns a URL that allows the client to jump to the channel.
Added in version 2.0.
- property members: Collection[Member]¶
Returns all members that can view this channel.
This is calculated based on the channel’s permission overwrites and the members’ roles.
- Returns:
All members who have permission to view this channel.
- Return type:
Collection[
Member]
- overwrites_for(obj)¶
Returns the channel-specific overwrites for a member or a role.
- await permissions_are_synced()¶
Whether the permissions for this channel are synced with the category it belongs to.
If there is no category then this is
False. :rtype:boolAdded in version 3.0.
- permissions_for(obj, /)¶
Handles permission resolution for the
MemberorRole.This function takes into consideration the following cases:
Guild owner
Guild roles
Channel overrides
Member overrides
If a
Roleis passed, then it checks the permissions someone with that role would have, which is essentially:The default role permissions
The permissions of the role used as a parameter
The default role permission overwrites
The permission overwrites of the role used as a parameter
Changed in version 2.0: The object passed in can now be a role object.
- await set_permissions(target, *, overwrite=Undefined.MISSING, reason=None, **permissions)¶
This function is a coroutine.
Sets the channel specific permission overwrites for a target in the channel.
The
targetparameter should either be aMemberor aRolethat belongs to guild.The
overwriteparameter, if given, must either beNoneorPermissionOverwrite. For convenience, you can pass in keyword arguments denotingPermissionsattributes. If this is done, then you cannot mix the keyword arguments with theoverwriteparameter.If the
overwriteparameter isNone, then the permission overwrites are deleted.You must have the
manage_rolespermission to use this.Note
This method replaces the old overwrites with the ones given.
Examples
Setting allow and deny:
await message.channel.set_permissions(message.author, read_messages=True, send_messages=False)
Deleting overwrites
await channel.set_permissions(member, overwrite=None)
Using
PermissionOverwriteoverwrite = discord.PermissionOverwrite() overwrite.send_messages = False overwrite.read_messages = True await channel.set_permissions(member, overwrite=overwrite)
- Parameters:
target (Union[
Member,Role]) – The member or role to overwrite permissions for.overwrite (Optional[
PermissionOverwrite]) – The permissions to allow and deny to the target, orNoneto delete the overwrite.**permissions (
bool) – A keyword argument list of permissions to set for ease of use. Cannot be mixed withoverwrite.reason (Optional[
str]) – The reason for doing this action. Shows up on the audit log.
- Raises:
Forbidden – You do not have permissions to edit channel specific permissions.
HTTPException – Editing channel specific permissions failed.
NotFound – The role or member being edited is not part of the guild.
InvalidArgument – The overwrite parameter invalid or the target type was not
RoleorMember.
- Return type:
- property type: ChannelType¶
The channel’s Discord channel type.
- class discord.events.GuildChannelUpdate[source]¶
Called whenever a guild channel is updated (e.g., changed name, topic, permissions).
This requires
Intents.guildsto be enabled.This event inherits from the actual channel type that was updated (e.g.,
TextChannel,VoiceChannel,ForumChannel, etc.).Note
While this class shows
GuildChannelin the signature, at runtime the event will be an instance of the specific channel type that was updated.- old¶
The channel’s old info before the update, or None if not in cache. This will be the same type as the event itself.
- Type:
TextChannel|VoiceChannel|CategoryChannel|StageChannel|ForumChannel| None
- class discord.events.PrivateChannelUpdate[source]¶
Called whenever a private group DM is updated (e.g., changed name or topic).
This requires
Intents.messagesto be enabled.This event inherits from
GroupChannel.- old¶
The channel’s old info before the update, or None if not in cache.
- Type:
GroupChannel| None
- class discord.events.ChannelPinsUpdate[source]¶
Called whenever a message is pinned or unpinned from a channel.
- channel¶
The channel that had its pins updated. Can be any messageable channel type.
- Type:
abc.PrivateChannel|TextChannel|VoiceChannel|StageChannel|ForumChannel|Thread
- last_pin¶
The latest message that was pinned as an aware datetime in UTC, or None if no pins exist.
- Type:
datetime.datetime| None
Connection & Gateway¶
- class discord.events.Ready[source]¶
Called when the client is done preparing the data received from Discord.
Usually after login is successful and the client’s guilds and cache are filled up.
Warning
This event is not guaranteed to be the first event called. Likewise, this event is not guaranteed to only be called once. This library implements reconnection logic and thus will end up calling this event whenever a RESUME request fails.
- user¶
An instance representing the connected application user.
- Type:
ClientUser
- application_flags¶
An instance representing the application flags.
- Type:
ApplicationFlags
- guilds¶
A list of guilds received in this event. Note it may have incomplete data as
GUILD_CREATEfills up other parts of guild data.- Type:
list[
Guild]
Entitlements & Monetization¶
- class discord.events.EntitlementCreate[source]¶
Called when a user subscribes to an SKU.
This event inherits from
Entitlement.- await consume()¶
This function is a coroutine.
Consumes this entitlement.
This can only be done on entitlements from an SKU of type
SKUType.consumable.- Raises:
HTTPException – Consuming the entitlement failed.
- Return type:
- await delete()¶
This function is a coroutine.
Deletes a test entitlement.
A test entitlement is an entitlement that was created using
Guild.create_test_entitlement()orUser.create_test_entitlement().- Raises:
HTTPException – Deleting the entitlement failed.
- Return type:
- class discord.events.EntitlementUpdate[source]¶
Called when a user’s subscription to an Entitlement is cancelled.
Note
Before October 1, 2024, this event was called when a user’s subscription was renewed.
Entitlements that no longer follow this behavior will have a type of
EntitlementType.purchase. Those that follow the old behavior will have a type ofEntitlementType.application_subscription.This event inherits from
Entitlement.- await consume()¶
This function is a coroutine.
Consumes this entitlement.
This can only be done on entitlements from an SKU of type
SKUType.consumable.- Raises:
HTTPException – Consuming the entitlement failed.
- Return type:
- await delete()¶
This function is a coroutine.
Deletes a test entitlement.
A test entitlement is an entitlement that was created using
Guild.create_test_entitlement()orUser.create_test_entitlement().- Raises:
HTTPException – Deleting the entitlement failed.
- Return type:
- class discord.events.EntitlementDelete[source]¶
Called when a user’s entitlement is deleted.
Entitlements are usually only deleted when Discord issues a refund for a subscription, or manually removes an entitlement from a user.
Note
This is not called when a user’s subscription is cancelled.
This event inherits from
Entitlement.- await consume()¶
This function is a coroutine.
Consumes this entitlement.
This can only be done on entitlements from an SKU of type
SKUType.consumable.- Raises:
HTTPException – Consuming the entitlement failed.
- Return type:
- await delete()¶
This function is a coroutine.
Deletes a test entitlement.
A test entitlement is an entitlement that was created using
Guild.create_test_entitlement()orUser.create_test_entitlement().- Raises:
HTTPException – Deleting the entitlement failed.
- Return type:
- class discord.events.SubscriptionCreate[source]¶
Called when a subscription is created for the application.
This event inherits from
Subscription.- await get_user()¶
Optional[
User]: The user that owns this subscription.
Guilds¶
- class discord.events.GuildJoin[source]¶
Called when the client joins a new guild or when a guild is created.
This requires
Intents.guildsto be enabled.This event inherits from
Guild.- await active_threads()¶
This function is a coroutine.
Returns a list of active
Threadthat the client can access.This includes both private and public threads.
Added in version 2.0.
- Returns:
The active threads
- Return type:
List[
Thread]- Raises:
HTTPException – The request to get the active threads failed.
- await audit_logs(*, limit=100, before=None, after=None, user=None, action=None)¶
Returns an
AsyncIteratorthat enables receiving the guild’s audit logs.You must have the
view_audit_logpermission to use this.See API documentation for more information about the before and after parameters.
- Parameters:
limit (Optional[
int]) – The number of entries to retrieve. IfNoneretrieve all entries.before (Union[
abc.Snowflake,datetime.datetime]) – Retrieve entries before this date or entry. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.after (Union[
abc.Snowflake,datetime.datetime]) – Retrieve entries after this date or entry. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.user (
abc.Snowflake) – The moderator to filter entries from.action (
AuditLogAction) – The action to filter with.
- Yields:
AuditLogEntry– The audit log entry.- Raises:
Forbidden – You are not allowed to fetch audit logs
HTTPException – An error occurred while fetching the audit logs.
- Return type:
AuditLogIterator
Examples
Getting the first 100 entries:
async for entry in guild.audit_logs(limit=100): print(f"{entry.user} did {entry.action} to {await entry.get_target()}")
Getting entries for a specific action:
async for entry in guild.audit_logs(action=discord.AuditLogAction.ban): print(f"{entry.user} banned {await entry.get_target()}")
Getting entries made by a specific user:
entries = await guild.audit_logs(limit=None, user=guild.me).flatten() await channel.send(f"I made {len(entries)} moderation actions.")
- await ban(user, *, delete_message_seconds=None, reason=None)¶
This function is a coroutine.
Bans a user from the guild.
The user must meet the
abc.Snowflakeabc.You must have the
ban_memberspermission to do this.- Parameters:
user (
abc.Snowflake) – The user to ban from their guild.delete_message_seconds (Optional[
int]) – The number of seconds worth of messages to delete from the user in the guild. The minimum is 0 and the maximum is 604800 (i.e. 7 days). The default is 0.reason (Optional[
str]) – The reason the user got banned.
- Raises:
Forbidden – You do not have the proper permissions to ban.
HTTPException – Banning failed.
- Return type:
- bans(limit=None, before=None, after=None)¶
This function is a coroutine.
Retrieves an
AsyncIteratorthat enables receiving the guild’s bans. In order to use this, you must have theban_memberspermission. Users will always be returned in ascending order sorted by user ID. If both thebeforeandafterparameters are provided, only before is respected.Changed in version 2.5: The
before. andafterparameters were changed. They are now of the typeabc.Snowflakeinstead of SnowflakeTime to comply with the discord api.Changed in version 2.0: The
limit,before. andafterparameters were added. Now returns aBanIteratorinstead of a list ofBanEntryobjects.All parameters are optional.
- Parameters:
limit (Optional[
int]) – The number of bans to retrieve. Defaults to 1000.before (Optional[
abc.Snowflake]) – Retrieve bans before the given user.after (Optional[
abc.Snowflake]) – Retrieve bans after the given user.
- Yields:
BanEntry– The ban entry for the ban.- Raises:
Forbidden – You do not have proper permissions to get the information.
HTTPException – An error occurred while fetching the information.
- Return type:
BanIterator
Examples
Usage
async for ban in guild.bans(limit=150): print(ban.user.name)
Flattening into a list
bans = await guild.bans(limit=150).flatten() # bans is now a list of BanEntry...
- await bulk_ban(*users, delete_message_seconds=None, reason=None)¶
This function is a coroutine.
Bulk ban users from the guild.
The users must meet the
abc.Snowflakeabc.You must have the
ban_memberspermission to do this.Example Usage:
# Ban multiple users successes, failures = await guild.bulk_ban(user1, user2, user3, ..., reason="Raid") # Ban a list of users successes, failures = await guild.bulk_ban(*users)
- Parameters:
*users (
abc.Snowflake) – An argument list of users to ban from the guild, up to 200.delete_message_seconds (Optional[
int]) – The number of seconds worth of messages to delete from the user in the guild. The minimum is 0 and the maximum is 604800 (i.e. 7 days). The default is 0.reason (Optional[
str]) – The reason the users were banned.
- Returns:
Returns two lists: the first contains members that were successfully banned, while the second is members that could not be banned.
- Return type:
Tuple[List[
abc.Snowflake], List[abc.Snowflake]]- Raises:
ValueError – You tried to ban more than 200 users.
Forbidden – You do not have the proper permissions to ban.
HTTPException – No users were banned.
- by_category()¶
Returns every
CategoryChanneland their associated channels.These channels and categories are sorted in the official Discord UI order.
If the channels do not have a category, then the first element of the tuple is
None.- Returns:
The categories and their associated channels.
- Return type:
List[Tuple[Optional[
CategoryChannel], List[abc.GuildChannel]]]
- property categories: list[CategoryChannel]¶
A list of categories that belong to this guild.
This is sorted by the position and are in UI order from top to bottom.
- await change_voice_state(*, channel, self_mute=False, self_deaf=False)¶
This function is a coroutine.
Changes client’s voice state in the guild.
Added in version 1.4.
- await chunk(*, cache=True)¶
This function is a coroutine.
Requests all members that belong to this guild. In order to use this,
Intents.members()must be enabled.This is a websocket operation and can be slow.
Added in version 1.5.
- Parameters:
cache (
bool) – Whether to cache the members as well.- Raises:
ClientException – The members intent is not enabled.
- Return type:
- await create_auto_moderation_rule(*, name, event_type, trigger_type, trigger_metadata, actions, enabled=False, exempt_roles=None, exempt_channels=None, reason=None)¶
Creates an auto moderation rule.
- Parameters:
name (
str) – The name of the auto moderation rule.event_type (
AutoModEventType) – The type of event that triggers the rule.trigger_type (
AutoModTriggerType) – The rule’s trigger type.trigger_metadata (
AutoModTriggerMetadata) – The rule’s trigger metadata.actions (List[
AutoModAction]) – The actions to take when the rule is triggered.enabled (
bool) – Whether the rule is enabled.exempt_roles (List[
abc.Snowflake]) – A list of roles that are exempt from the rule.exempt_channels (List[
abc.Snowflake]) – A list of channels that are exempt from the rule.reason (Optional[
str]) – The reason for creating the rule. Shows up in the audit log.
- Returns:
The new auto moderation rule.
- Return type:
AutoModRule- Raises:
HTTPException – Creating the auto moderation rule failed.
Forbidden – You do not have the Manage Guild permission.
- await create_category(name, *, overwrites=Undefined.MISSING, reason=None, position=Undefined.MISSING)¶
This function is a coroutine.
Same as
create_text_channel()except makes aCategoryChannelinstead.Note
The
categoryparameter is not supported in this function since categories cannot have categories.- Returns:
The channel that was just created.
- Return type:
CategoryChannel- Raises:
Forbidden – You do not have the proper permissions to create this channel.
HTTPException – Creating the channel failed.
InvalidArgument – The permission overwrite information is not in proper form.
- Parameters:
- await create_category_channel(name, *, overwrites=Undefined.MISSING, reason=None, position=Undefined.MISSING)¶
This function is a coroutine.
Same as
create_text_channel()except makes aCategoryChannelinstead.Note
The
categoryparameter is not supported in this function since categories cannot have categories.- Returns:
The channel that was just created.
- Return type:
CategoryChannel- Raises:
Forbidden – You do not have the proper permissions to create this channel.
HTTPException – Creating the channel failed.
InvalidArgument – The permission overwrite information is not in proper form.
- Parameters:
- await create_custom_emoji(*, name, image, roles=Undefined.MISSING, reason=None)¶
This function is a coroutine.
Creates a custom
GuildEmojifor the guild.There is currently a limit of 50 static and animated emojis respectively per guild, unless the guild has the
MORE_EMOJIfeature which extends the limit to 200.You must have the
manage_emojispermission to do this.- Parameters:
name (
str) – The emoji name. Must be at least 2 characters.image (
bytes) – The bytes-like object representing the image data to use. Only JPG, PNG and GIF images are supported.roles (List[
Role]) – AlistofRoles that can use this emoji. Leave empty to make it available to everyone.reason (Optional[
str]) – The reason for creating this emoji. Shows up on the audit log.
- Raises:
Forbidden – You are not allowed to create emojis.
HTTPException – An error occurred creating an emoji.
- Returns:
The created emoji.
- Return type:
GuildEmoji
- await create_forum_channel(name, *, reason=None, category=None, position=Undefined.MISSING, topic=Undefined.MISSING, slowmode_delay=Undefined.MISSING, nsfw=Undefined.MISSING, overwrites=Undefined.MISSING, default_reaction_emoji=Undefined.MISSING, available_tags=Undefined.MISSING, default_sort_order=Undefined.MISSING, default_thread_slowmode_delay=Undefined.MISSING, default_auto_archive_duration=Undefined.MISSING)¶
This function is a coroutine.
Creates a
ForumChannelfor the guild.Note that you need the
manage_channelspermission to create the channel.The
overwritesparameter can be used to create a ‘secret’ channel upon creation. This parameter expects adictof overwrites with the target (either aMemberor aRole) as the key and aPermissionOverwriteas the value.Note
Creating a channel of a specified position will not update the position of other channels to follow suit. A follow-up call to
edit()will be required to update the position of the channel in the channel list.- Parameters:
name (
str) – The channel’s name.overwrites (Dict[Union[
Role,Member,Snowflake],PermissionOverwrite]) – The overwrites to apply to the channel. Useful for creating secret channels.category (Optional[
CategoryChannel]) – The category to place the newly created channel under. The permissions will be automatically synced to category if no overwrites are provided.position (
int) – The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0.topic (
str) – The new channel’s topic.slowmode_delay (
int) – Specifies the slowmode rate limit for user in this channel, in seconds. A value of0disables slowmode. The maximum value possible is21600.nsfw (
bool) – Whether the channel is marked as NSFW.reason (Optional[
str]) – The reason for creating this channel. Shows up on the audit log.default_reaction_emoji (Optional[
GuildEmoji|int|str]) –The default reaction emoji. Can be a unicode emoji or a custom emoji in the forms:
GuildEmoji, snowflake ID, string representation (eg. ‘<a:emoji_name:emoji_id>’).Added in version v2.5.
available_tags (List[
ForumTag]) –The set of tags that can be used in a forum channel.
Added in version 2.7.
default_sort_order (Optional[
SortOrder]) –The default sort order type used to order posts in this channel.
Added in version 2.7.
default_thread_slowmode_delay (Optional[
int]) –The initial slowmode delay to set on newly created threads in this channel.
Added in version 2.7.
default_auto_archive_duration (
int) –The default auto archive duration in minutes for threads created in this channel.
Added in version 2.7.
- Returns:
The channel that was just created.
- Return type:
ForumChannel- Raises:
Forbidden – You do not have the proper permissions to create this channel.
HTTPException – Creating the channel failed.
InvalidArgument – The argument is not in proper form.
Examples
Creating a basic channel:
channel = await guild.create_forum_channel("cool-channel")
Creating a “secret” channel:
overwrites = { guild.default_role: discord.PermissionOverwrite(read_messages=False), guild.me: discord.PermissionOverwrite(read_messages=True), } channel = await guild.create_forum_channel("secret", overwrites=overwrites)
- await create_integration(*, type, id)¶
This function is a coroutine.
Attaches an integration to the guild.
You must have the
manage_guildpermission to do this.Added in version 1.4.
- Parameters:
- Raises:
Forbidden – You do not have permission to create the integration.
HTTPException – The account could not be found.
- Return type:
- await create_role(*, name=Undefined.MISSING, permissions=Undefined.MISSING, color=Undefined.MISSING, colour=Undefined.MISSING, colors=Undefined.MISSING, colours=Undefined.MISSING, holographic=Undefined.MISSING, hoist=Undefined.MISSING, mentionable=Undefined.MISSING, reason=None, icon=Undefined.MISSING, unicode_emoji=Undefined.MISSING)¶
This function is a coroutine.
Creates a
Rolefor the guild.All fields are optional.
You must have the
manage_rolespermission to do this.Changed in version 1.6: Can now pass
inttocolourkeyword-only parameter.- Parameters:
name (
str) – The role name. Defaults to ‘new role’.permissions (
Permissions) – The permissions to have. Defaults to no permissions.colour (Union[
Colour,int]) – The colour for the role. Defaults toColour.default(). This is aliased tocoloras well.hoist (
bool) – Indicates if the role should be shown separately in the member list. Defaults toFalse.mentionable (
bool) – Indicates if the role should be mentionable by others. Defaults toFalse.reason (Optional[
str]) – The reason for creating this role. Shows up on the audit log.icon (Optional[
bytes]) – A bytes-like object representing the icon. Only PNG/JPEG/WebP is supported. If this argument is passed,unicode_emojiis set to None. Only available to guilds that containROLE_ICONSinGuild.features.unicode_emoji (Optional[
str]) – The role’s unicode emoji. If this argument is passed,iconis set to None. Only available to guilds that containROLE_ICONSinGuild.features.color (Colour | int | utils.Undefined)
colors (RoleColours | utils.Undefined)
colours (RoleColours | utils.Undefined)
holographic (bool | utils.Undefined)
- Returns:
The newly created role.
- Return type:
Role- Raises:
Forbidden – You do not have permissions to create the role.
HTTPException – Creating the role failed.
InvalidArgument – An invalid keyword argument was given.
- await create_scheduled_event(*, name, description=Undefined.MISSING, start_time, end_time=Undefined.MISSING, location, privacy_level=ScheduledEventPrivacyLevel.guild_only, reason=None, image=Undefined.MISSING)¶
This function is a coroutine. Creates a scheduled event.
- Parameters:
name (
str) – The name of the scheduled event.description (Optional[
str]) – The description of the scheduled event.start_time (
datetime.datetime) – A datetime object of when the scheduled event is supposed to start.end_time (Optional[
datetime.datetime]) – A datetime object of when the scheduled event is supposed to end.location (
ScheduledEventLocation) – The location of where the event is happening.privacy_level (
ScheduledEventPrivacyLevel) – The privacy level of the event. Currently, the only possible value isScheduledEventPrivacyLevel.guild_only, which is default, so there is no need to change this parameter.reason (Optional[
str]) – The reason to show in the audit log.image (Optional[
bytes]) – The cover image of the scheduled event
- Returns:
The created scheduled event.
- Return type:
Optional[
ScheduledEvent]- Raises:
Forbidden – You do not have the Manage Events permission.
HTTPException – The operation failed.
- await create_sound(name, sound, volume=1.0, emoji=None, reason=None)¶
This function is a coroutine. Creates a
SoundboardSoundin the guild. You must havePermissions.manage_expressionspermission to use this.Added in version 2.7.
- Parameters:
name (
str) – The name of the sound.sound (
bytes) – The bytes-like object representing the sound data. Only MP3 sound files that are less than 5.2 seconds long are supported.volume (
float) – The volume of the sound. Defaults to 1.0.emoji (Optional[Union[
PartialEmoji,GuildEmoji,str]]) – The emoji of the sound.reason (Optional[
str]) – The reason for creating this sound. Shows up on the audit log.
- Returns:
The created sound.
- Return type:
SoundboardSound- Raises:
HTTPException – Creating the sound failed.
Forbidden – You do not have permissions to create sounds.
- await create_stage_channel(name, *, topic, position=Undefined.MISSING, overwrites=Undefined.MISSING, category=None, reason=None, bitrate=Undefined.MISSING, user_limit=Undefined.MISSING, rtc_region=Undefined.MISSING, video_quality_mode=Undefined.MISSING, slowmode_delay=Undefined.MISSING, nsfw=Undefined.MISSING)¶
This function is a coroutine.
This is similar to
create_text_channel()except makes aStageChannelinstead.Added in version 1.7.
- Parameters:
name (
str) – The channel’s name.topic (
str) – The new channel’s topic.overwrites (Dict[Union[
Role,Member,Snowflake],PermissionOverwrite]) – The overwrites to apply to the channel. Useful for creating secret channels.category (Optional[
CategoryChannel]) – The category to place the newly created channel under. The permissions will be automatically synced to category if no overwrites are provided.position (
int) – The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0.reason (Optional[
str]) – The reason for creating this channel. Shows up on the audit log.bitrate (
int) –The channel’s preferred audio bitrate in bits per second.
Added in version 2.7.
user_limit (
int) –The channel’s limit for number of members that can be in a voice channel.
Added in version 2.7.
rtc_region (Optional[
VoiceRegion]) –The region for the voice channel’s voice communication. A value of
Noneindicates automatic voice region detection.Added in version 2.7.
video_quality_mode (
VideoQualityMode) –The camera video quality for the voice channel’s participants.
Added in version 2.7.
slowmode_delay (
int) –Specifies the slowmode rate limit for user in this channel, in seconds. A value of
0disables slowmode. The maximum value possible is21600.Added in version 2.7.
nsfw (
bool) –Whether the channel is marked as NSFW.
Added in version 2.7.
- Returns:
The channel that was just created.
- Return type:
StageChannel- Raises:
Forbidden – You do not have the proper permissions to create this channel.
HTTPException – Creating the channel failed.
InvalidArgument – The permission overwrite information is not in proper form.
- await create_sticker(*, name, description=None, emoji, file, reason=None)¶
This function is a coroutine.
Creates a
Stickerfor the guild.You must have
manage_emojis_and_stickerspermission to do this.Added in version 2.0.
- Parameters:
name (
str) – The sticker name. Must be 2 to 30 characters.description (Optional[
str]) – The sticker’s description. If used, must be 2 to 100 characters.emoji (
str) – The name of a unicode emoji that represents the sticker’s expression.file (
File) – The file of the sticker to upload.reason (
str) – The reason for creating this sticker. Shows up on the audit log.
- Returns:
The created sticker.
- Return type:
GuildSticker- Raises:
Forbidden – You are not allowed to create stickers.
HTTPException – An error occurred creating a sticker.
TypeError – The parameters for the sticker are not correctly formatted.
- await create_template(*, name, description=Undefined.MISSING)¶
This function is a coroutine.
Creates a template for the guild.
You must have the
manage_guildpermission to do this.Added in version 1.7.
- await create_test_entitlement(sku)¶
This function is a coroutine.
Creates a test entitlement for the guild.
- Parameters:
sku (
Snowflake) – The SKU to create a test entitlement for.- Returns:
The created entitlement.
- Return type:
Entitlement
- await create_text_channel(name, *, reason=None, category=None, position=Undefined.MISSING, topic=Undefined.MISSING, slowmode_delay=Undefined.MISSING, nsfw=Undefined.MISSING, overwrites=Undefined.MISSING, default_thread_slowmode_delay=Undefined.MISSING, default_auto_archive_duration=Undefined.MISSING)¶
This function is a coroutine.
Creates a
TextChannelfor the guild.Note that you need the
manage_channelspermission to create the channel.The
overwritesparameter can be used to create a ‘secret’ channel upon creation. This parameter expects adictof overwrites with the target (either aMemberor aRole) as the key and aPermissionOverwriteas the value.Note
Creating a channel of a specified position will not update the position of other channels to follow suit. A follow-up call to
edit()will be required to update the position of the channel in the channel list.- Parameters:
name (
str) – The channel’s name.overwrites (Dict[Union[
Role,Member,Snowflake],PermissionOverwrite]) – The overwrites to apply to the channel. Useful for creating secret channels.category (Optional[
CategoryChannel]) – The category to place the newly created channel under. The permissions will be automatically synced to category if no overwrites are provided.position (
int) – The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0.topic (
str) – The new channel’s topic.slowmode_delay (
int) – Specifies the slowmode rate limit for user in this channel, in seconds. A value of 0 disables slowmode. The maximum value possible is 21600.nsfw (
bool) – Whether the channel is marked as NSFW.reason (Optional[
str]) – The reason for creating this channel. Shows up on the audit log.default_thread_slowmode_delay (Optional[
int]) –The initial slowmode delay to set on newly created threads in this channel.
Added in version 2.7.
default_auto_archive_duration (
int) –The default auto archive duration in minutes for threads created in this channel.
Added in version 2.7.
- Returns:
The channel that was just created.
- Return type:
TextChannel- Raises:
Forbidden – You do not have the proper permissions to create this channel.
HTTPException – Creating the channel failed.
InvalidArgument – The permission overwrite information is not in proper form.
Examples
Creating a basic channel:
channel = await guild.create_text_channel("cool-channel")
Creating a “secret” channel:
overwrites = { guild.default_role: discord.PermissionOverwrite(read_messages=False), guild.me: discord.PermissionOverwrite(read_messages=True), } channel = await guild.create_text_channel("secret", overwrites=overwrites)
- await create_voice_channel(name, *, reason=None, category=None, position=Undefined.MISSING, bitrate=Undefined.MISSING, user_limit=Undefined.MISSING, rtc_region=Undefined.MISSING, video_quality_mode=Undefined.MISSING, overwrites=Undefined.MISSING, slowmode_delay=Undefined.MISSING, nsfw=Undefined.MISSING)¶
This function is a coroutine.
This is similar to
create_text_channel()except makes aVoiceChannelinstead.- Parameters:
name (
str) – The channel’s name.overwrites (Dict[Union[
Role,Member,Snowflake],PermissionOverwrite]) – The overwrites to apply to the channel. Useful for creating secret channels.category (Optional[
CategoryChannel]) – The category to place the newly created channel under. The permissions will be automatically synced to category if no overwrites are provided.position (
int) – The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0.bitrate (
int) – The channel’s preferred audio bitrate in bits per second.user_limit (
int) – The channel’s limit for number of members that can be in a voice channel.rtc_region (Optional[
VoiceRegion]) –The region for the voice channel’s voice communication. A value of
Noneindicates automatic voice region detection.Added in version 1.7.
video_quality_mode (
VideoQualityMode) –The camera video quality for the voice channel’s participants.
Added in version 2.0.
reason (Optional[
str]) – The reason for creating this channel. Shows up on the audit log.slowmode_delay (
int) –Specifies the slowmode rate limit for user in this channel, in seconds. A value of
0disables slowmode. The maximum value possible is21600.Added in version 2.7.
nsfw (
bool) –Whether the channel is marked as NSFW.
Added in version 2.7.
- Returns:
The channel that was just created.
- Return type:
VoiceChannel- Raises:
Forbidden – You do not have the proper permissions to create this channel.
HTTPException – Creating the channel failed.
InvalidArgument – The permission overwrite information is not in proper form.
- await delete()¶
This function is a coroutine.
Deletes the guild. You must be the guild owner to delete the guild.
- Raises:
HTTPException – Deleting the guild failed.
Forbidden – You do not have permissions to delete the guild.
- Return type:
- await delete_auto_moderation_rule(id, *, reason=None)¶
Deletes an auto moderation rule.
- Parameters:
- Raises:
HTTPException – Deleting the auto moderation rule failed.
Forbidden – You do not have the Manage Guild permission.
- Return type:
- await delete_emoji(emoji, *, reason=None)¶
This function is a coroutine.
Deletes the custom
GuildEmojifrom the guild.You must have
manage_emojispermission to do this.- Parameters:
emoji (
abc.Snowflake) – The emoji you are deleting.reason (Optional[
str]) – The reason for deleting this emoji. Shows up on the audit log.
- Raises:
Forbidden – You are not allowed to delete emojis.
HTTPException – An error occurred deleting the emoji.
- Return type:
- await delete_sticker(sticker, *, reason=None)¶
This function is a coroutine.
Deletes the custom
Stickerfrom the guild.You must have
manage_emojis_and_stickerspermission to do this.Added in version 2.0.
- Parameters:
sticker (
abc.Snowflake) – The sticker you are deleting.reason (Optional[
str]) – The reason for deleting this sticker. Shows up on the audit log.
- Raises:
Forbidden – You are not allowed to delete stickers.
HTTPException – An error occurred deleting the sticker.
- Return type:
- await edit(*, reason=Undefined.MISSING, name=Undefined.MISSING, description=Undefined.MISSING, icon=Undefined.MISSING, banner=Undefined.MISSING, splash=Undefined.MISSING, discovery_splash=Undefined.MISSING, community=Undefined.MISSING, afk_channel=Undefined.MISSING, owner=Undefined.MISSING, afk_timeout=Undefined.MISSING, default_notifications=Undefined.MISSING, verification_level=Undefined.MISSING, explicit_content_filter=Undefined.MISSING, system_channel=Undefined.MISSING, system_channel_flags=Undefined.MISSING, preferred_locale=Undefined.MISSING, rules_channel=Undefined.MISSING, public_updates_channel=Undefined.MISSING, premium_progress_bar_enabled=Undefined.MISSING, disable_invites=Undefined.MISSING, discoverable=Undefined.MISSING, disable_raid_alerts=Undefined.MISSING, enable_activity_feed=Undefined.MISSING)¶
This function is a coroutine.
Edits the guild.
You must have the
manage_guildpermission to edit the guild.Changed in version 1.4: The rules_channel and public_updates_channel keyword-only parameters were added.
Changed in version 2.0: The discovery_splash and community keyword-only parameters were added.
Changed in version 2.0: The newly updated guild is returned.
- Parameters:
name (
str) – The new name of the guild.description (Optional[
str]) – The new description of the guild. Could beNonefor no description. This is only available to guilds that containPUBLICinGuild.features.icon (
bytes) – A bytes-like object representing the icon. Only PNG/JPEG is supported. GIF is only available to guilds that containANIMATED_ICONinGuild.features. Could beNoneto denote removal of the icon.banner (
bytes) – A bytes-like object representing the banner. Could beNoneto denote removal of the banner. This is only available to guilds that containBANNERinGuild.features.splash (
bytes) – A bytes-like object representing the invite splash. Only PNG/JPEG supported. Could beNoneto denote removing the splash. This is only available to guilds that containINVITE_SPLASHinGuild.features.discovery_splash (
bytes) – A bytes-like object representing the discovery splash. Only PNG/JPEG supported. Could beNoneto denote removing the splash. This is only available to guilds that containDISCOVERABLEinGuild.features.community (
bool) – Whether the guild should be a Community guild. If set toTrue, bothrules_channelandpublic_updates_channelparameters are required.afk_channel (Optional[
VoiceChannel]) – The new channel that is the AFK channel. Could beNonefor no AFK channel.afk_timeout (
int) – The number of seconds until someone is moved to the AFK channel.owner (
Member) – The new owner of the guild to transfer ownership to. Note that you must be owner of the guild to do this.verification_level (
VerificationLevel) – The new verification level for the guild.default_notifications (
NotificationLevel) – The new default notification level for the guild.explicit_content_filter (
ContentFilter) – The new explicit content filter for the guild.system_channel (Optional[
TextChannel]) – The new channel that is used for the system channel. Could beNonefor no system channel.system_channel_flags (
SystemChannelFlags) – The new system channel settings to use with the new system channel.preferred_locale (
str) – The new preferred locale for the guild. Used as the primary language in the guild. If set, this must be an ISO 639 code, e.g.en-USorjaorzh-CN.rules_channel (Optional[
TextChannel]) – The new channel that is used for rules. This is only available to guilds that containPUBLICinGuild.features. Could beNonefor no rules channel.public_updates_channel (Optional[
TextChannel]) – The new channel that is used for public updates from Discord. This is only available to guilds that containPUBLICinGuild.features. Could beNonefor no public updates channel.premium_progress_bar_enabled (
bool) – Whether the guild should have premium progress bar enabled.disable_invites (
bool) – Whether the guild should have server invites enabled or disabled.discoverable (
bool) – Whether the guild should be discoverable in the discover tab.disable_raid_alerts (
bool) – Whether activity alerts for the guild should be disabled.enable_activity_feed (class:bool) – Whether the guild’s user activity feed should be enabled.
reason (Optional[
str]) – The reason for editing this guild. Shows up on the audit log.
- Raises:
Forbidden – You do not have permissions to edit the guild.
HTTPException – Editing the guild failed.
InvalidArgument – The image format passed in to
iconis invalid. It must be PNG or JPG. This is also raised if you are not the owner of the guild and request an ownership transfer.
- Returns:
The newly updated guild. Note that this has the same limitations as mentioned in
Client.fetch_guild()and may not have full data.- Return type:
Guild
- await edit_onboarding(*, prompts=Undefined.MISSING, default_channels=Undefined.MISSING, enabled=Undefined.MISSING, mode=Undefined.MISSING, reason=Undefined.MISSING)¶
This function is a coroutine.
A shorthand for
Onboarding.editwithout fetching the onboarding flow.You must have the
manage_guildandmanage_rolespermissions in the guild to do this.- Parameters:
prompts (Optional[List[
OnboardingPrompt]]) – The new list of prompts for this flow.default_channels (Optional[List[
Snowflake]]) – The new default channels that users are opted into.enabled (Optional[
bool]) – Whether onboarding should be enabled. Setting this toTruerequires the guild to haveCOMMUNITYinfeaturesand at least 7default_channels.mode (Optional[
OnboardingMode]) – The new onboarding mode.reason (Optional[
str]) – The reason that shows up on Audit log.
- Returns:
The updated onboarding flow.
- Return type:
Onboarding- Raises:
HTTPException – Editing the onboarding flow failed somehow.
Forbidden – You don’t have permissions to edit the onboarding flow.
- await edit_role_positions(positions, *, reason=None)¶
This function is a coroutine.
Bulk edits a list of
Rolein the guild.You must have the
manage_rolespermission to do this.Added in version 1.4.
Example:
positions = { bots_role: 1, # penultimate role tester_role: 2, admin_role: 6, } await guild.edit_role_positions(positions=positions)
- Parameters:
- Returns:
A list of all the roles in the guild.
- Return type:
List[
Role]- Raises:
Forbidden – You do not have permissions to move the roles.
HTTPException – Moving the roles failed.
InvalidArgument – An invalid keyword argument was given.
- await edit_welcome_screen(**options)¶
This function is a coroutine.
A shorthand for
WelcomeScreen.editwithout fetching the welcome screen.You must have the
manage_guildpermission in the guild to do this.The guild must have
COMMUNITYinGuild.features- Parameters:
description (Optional[
str]) – The new description of welcome screen.welcome_channels (Optional[List[
WelcomeScreenChannel]]) – The welcome channels. The order of the channels would be same as the passed list order.enabled (Optional[
bool]) – Whether the welcome screen should be displayed.reason (Optional[
str]) – The reason that shows up on audit log.
- Returns:
The edited welcome screen.
- Return type:
WelcomeScreen- Raises:
HTTPException – Editing the welcome screen failed somehow.
Forbidden – You don’t have permissions to edit the welcome screen.
NotFound – This welcome screen does not exist.
- await edit_widget(*, enabled=Undefined.MISSING, channel=Undefined.MISSING)¶
This function is a coroutine.
Edits the widget of the guild.
You must have the
manage_guildpermission to use thisAdded in version 2.0.
- Parameters:
- Raises:
Forbidden – You do not have permission to edit the widget.
HTTPException – Editing the widget failed.
- Return type:
- entitlements(skus=None, before=None, after=None, limit=100, exclude_ended=False)¶
Returns an
AsyncIteratorthat enables fetching the guild’s entitlements.This is identical to
Client.entitlements()with theguildparameter.Added in version 2.6.
- Parameters:
skus (list[
abc.Snowflake] | None) – Limit the fetched entitlements to entitlements that are for these SKUs.before (
abc.Snowflake|datetime.datetime| None) – Retrieves guilds before this date or object. If a datetime is provided, it is recommended to use a UTC-aware datetime. If the datetime is naive, it is assumed to be local time.after (
abc.Snowflake|datetime.datetime| None) – Retrieve guilds after this date or object. If a datetime is provided, it is recommended to use a UTC-aware datetime. If the datetime is naive, it is assumed to be local time.limit (Optional[
int]) – The number of entitlements to retrieve. IfNone, retrieves every entitlement, which may be slow. Defaults to100.exclude_ended (
bool) – Whether to limit the fetched entitlements to those that have not ended. Defaults toFalse.
- Yields:
Entitlement– The application’s entitlements.- Raises:
HTTPException – Retrieving the entitlements failed.
- Return type:
EntitlementIterator
- await estimate_pruned_members(*, days, roles=Undefined.MISSING)¶
This function is a coroutine.
Similar to
prune_members()except instead of actually pruning members, it returns how many members it would prune from the guild had it been called.- Parameters:
days (
int) – The number of days before counting as inactive.roles (List[
abc.Snowflake]) –A list of
abc.Snowflakethat represent roles to include in the estimate. If a member has a role that is not specified, they’ll be excluded.Added in version 1.7.
- Returns:
The number of members estimated to be pruned.
- Return type:
- Raises:
Forbidden – You do not have permissions to prune members.
HTTPException – An error occurred while fetching the prune members estimate.
InvalidArgument – An integer was not passed for
days.
- await fetch_auto_moderation_rule(id)¶
This function is a coroutine.
Retrieves a
AutoModRulefrom rule ID.- Returns:
The requested auto moderation rule.
- Return type:
AutoModRule- Raises:
HTTPException – Getting the auto moderation rule failed.
Forbidden – You do not have the Manage Guild permission.
- Parameters:
id (
int)
- await fetch_auto_moderation_rules()¶
This function is a coroutine.
Retrieves a list of auto moderation rules for this guild.
- Returns:
The auto moderation rules for this guild.
- Return type:
List[
AutoModRule]- Raises:
HTTPException – Getting the auto moderation rules failed.
Forbidden – You do not have the Manage Guild permission.
- await fetch_ban(user)¶
This function is a coroutine.
Retrieves the
BanEntryfor a user.You must have the
ban_memberspermission to get this information.- Parameters:
user (
abc.Snowflake) – The user to get ban information from.- Returns:
The
BanEntryobject for the specified user.- Return type:
BanEntry- Raises:
Forbidden – You do not have proper permissions to get the information.
NotFound – This user is not banned.
HTTPException – An error occurred while fetching the information.
- await fetch_channel(channel_id, /)¶
This function is a coroutine.
Retrieves a
abc.GuildChannelorThreadwith the specified ID.Note
This method is an API call. For general usage, consider
get_channel_or_thread()instead.Added in version 2.0.
- Returns:
The channel from the ID.
- Return type:
Union[
abc.GuildChannel,Thread]- Raises:
InvalidData – An unknown channel type was received from Discord or the guild the channel belongs to is not the same as the one in this object points to.
HTTPException – Retrieving the channel failed.
NotFound – Invalid Channel ID.
Forbidden – You do not have permission to fetch this channel.
- Parameters:
channel_id (
int)
- await fetch_channels()¶
This function is a coroutine.
Retrieves all
abc.GuildChannelthat the guild has.Note
This method is an API call. For general usage, consider
channelsinstead.Added in version 1.2.
- Returns:
All channels in the guild.
- Return type:
Sequence[
discord.channel.base.GuildChannel]- Raises:
InvalidData – An unknown channel type was received from Discord.
HTTPException – Retrieving the channels failed.
- await fetch_emoji(emoji_id, /)¶
This function is a coroutine.
Retrieves a custom
GuildEmojifrom the guild.Note
This method is an API call. For general usage, consider iterating over
emojisinstead.- Parameters:
emoji_id (
int) – The emoji’s ID.- Returns:
The retrieved emoji.
- Return type:
GuildEmoji- Raises:
NotFound – The emoji requested could not be found.
HTTPException – An error occurred fetching the emoji.
- await fetch_emojis()¶
This function is a coroutine.
Retrieves all custom
GuildEmojis from the guild.Note
This method is an API call. For general usage, consider
emojisinstead.- Raises:
HTTPException – An error occurred fetching the emojis.
- Returns:
The retrieved emojis.
- Return type:
List[
GuildEmoji]
- await fetch_member(member_id, /)¶
This function is a coroutine.
Retrieves a
Memberfrom a guild ID, and a member ID.Note
This method is an API call. If you have
Intents.membersand member cache enabled, considerget_member()instead.- Parameters:
member_id (
int) – The member’s ID to fetch from.- Returns:
The member from the member ID.
- Return type:
Member- Raises:
Forbidden – You do not have access to the guild.
HTTPException – Fetching the member failed.
- fetch_members(*, limit=1000, after=None)¶
Retrieves an
AsyncIteratorthat enables receiving the guild’s members. In order to use this,Intents.members()must be enabled.Note
This method is an API call. For general usage, consider
membersinstead.Added in version 1.3.
All parameters are optional.
- Parameters:
limit (Optional[
int]) – The number of members to retrieve. Defaults to 1000. PassNoneto fetch all members. Note that this is potentially slow.after (Optional[Union[
abc.Snowflake,datetime.datetime]]) – Retrieve members after this date or object. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.
- Yields:
Member– The member with the member data parsed.- Raises:
ClientException – The members intent is not enabled.
HTTPException – Getting the members failed.
- Return type:
MemberIterator
Examples
Usage
async for member in guild.fetch_members(limit=150): print(member.name)
Flattening into a list
members = await guild.fetch_members(limit=150).flatten() # members is now a list of Member...
- await fetch_role(role_id)¶
This function is a coroutine.
Retrieves a
Rolethat the guild has.Note
This method is an API call. For general usage, consider using
get_roleinstead.Added in version 2.7.
- Returns:
The role in the guild with the specified ID.
- Return type:
Role- Raises:
HTTPException – Retrieving the role failed.
- Parameters:
role_id (
int)
- await fetch_roles()¶
This function is a coroutine.
Retrieves all
Rolethat the guild has.Note
This method is an API call. For general usage, consider
rolesinstead.Added in version 1.3.
- Returns:
All roles in the guild.
- Return type:
List[
Role]- Raises:
HTTPException – Retrieving the roles failed.
- await fetch_scheduled_event(event_id, /, *, with_user_count=True)¶
This function is a coroutine.
Retrieves a
ScheduledEventfrom event ID.Note
This method is an API call. If you have
Intents.scheduled_events, considerget_scheduled_event()instead.- Parameters:
- Returns:
The scheduled event from the event ID.
- Return type:
Optional[
ScheduledEvent]- Raises:
HTTPException – Fetching the event failed.
NotFound – Event not found.
- await fetch_scheduled_events(*, with_user_count=True)¶
This function is a coroutine.
Returns a list of
ScheduledEventin the guild.Note
This method is an API call. For general usage, consider
scheduled_eventsinstead.- Parameters:
with_user_count (Optional[
bool]) – If the scheduled event should be fetched with the number of users that are interested in the events. Defaults toTrue.- Returns:
The fetched scheduled events.
- Return type:
List[
ScheduledEvent]- Raises:
ClientException – The scheduled events intent is not enabled.
HTTPException – Getting the scheduled events failed.
- await fetch_sound(sound_id)¶
This function is a coroutine. Fetches a soundboard sound in the guild.
Added in version 2.7.
- Parameters:
sound_id (
int) – The ID of the sound.- Returns:
The sound.
- Return type:
SoundboardSound
- await fetch_sounds()¶
This function is a coroutine. Fetches all the soundboard sounds in the guild.
Added in version 2.7.
- Returns:
The sounds in the guild.
- Return type:
List[
SoundboardSound]
- await fetch_sticker(sticker_id, /)¶
This function is a coroutine.
Retrieves a custom
Stickerfrom the guild.Added in version 2.0.
Note
This method is an API call. For general usage, consider iterating over
stickersinstead.- Parameters:
sticker_id (
int) – The sticker’s ID.- Returns:
The retrieved sticker.
- Return type:
GuildSticker- Raises:
NotFound – The sticker requested could not be found.
HTTPException – An error occurred fetching the sticker.
- await fetch_stickers()¶
This function is a coroutine.
Retrieves a list of all
Stickers for the guild.Added in version 2.0.
Note
This method is an API call. For general usage, consider
stickersinstead.- Raises:
HTTPException – An error occurred fetching the stickers.
- Returns:
The retrieved stickers.
- Return type:
List[
GuildSticker]
- property filesize_limit: int¶
The maximum number of bytes files can have when uploaded to this guild.
- property forum_channels: list[ForumChannel]¶
A list of forum channels that belong to this guild.
Added in version 2.0.
This is sorted by the position and are in UI order from top to bottom.
- get_channel(channel_id, /)¶
Returns a channel with the given ID.
Note
This does not search for threads.
- Parameters:
channel_id (
int) – The ID to search for.- Returns:
The returned channel or
Noneif not found.- Return type:
Optional[
abc.GuildChannel]
- get_channel_or_thread(channel_id, /)¶
Returns a channel or thread with the given ID.
Added in version 2.0.
- Parameters:
channel_id (
int) – The ID to search for.- Returns:
The returned channel or thread or
Noneif not found.- Return type:
Optional[Union[
Thread,abc.GuildChannel]]
- await get_me()¶
Similar to
Client.userexcept an instance ofMember. This is essentially used to get the member version of yourself.- Return type:
- await get_member(user_id, /)¶
Returns a member with the given ID.
- Parameters:
user_id (
int) – The ID to search for.- Returns:
The member or
Noneif not found.- Return type:
Optional[
Member]
- get_member_named(name, /)¶
Returns the first member found that matches the name provided.
The name can have an optional discriminator argument, e.g. “Jake#0001” or “Jake” will both do the lookup. However, the former will give a more precise result. Note that the discriminator must have all 4 digits for this to work.
If a nickname is passed, then it is looked up via the nickname. Note however, that a nickname + discriminator combo will not look up the nickname but rather the username + discriminator combo due to nickname + discriminator not being unique.
If no member is found,
Noneis returned.- Parameters:
name (
str) – The name of the member to lookup with an optional discriminator.- Returns:
The member in this guild with the associated name. If not found then
Noneis returned.- Return type:
Optional[
Member]
- get_role(role_id, /)¶
Returns a role with the given ID.
- Parameters:
role_id (
int) – The ID to search for.- Returns:
The role or
Noneif not found.- Return type:
Optional[
Role]
- get_scheduled_event(event_id, /)¶
Returns a Scheduled Event with the given ID.
- Parameters:
event_id (
int) – The ID to search for.- Returns:
The scheduled event or
Noneif not found.- Return type:
Optional[
ScheduledEvent]
- get_sound(sound_id)¶
Returns a sound with the given ID.
Added in version 2.7.
- Parameters:
sound_id (
int) – The ID to search for.- Returns:
The sound or
Noneif not found.- Return type:
Optional[
SoundboardSound]
- get_stage_instance(stage_instance_id, /)¶
Returns a stage instance with the given ID.
Added in version 2.0.
- Parameters:
stage_instance_id (
int) – The ID to search for.- Returns:
The stage instance or
Noneif not found.- Return type:
Optional[
StageInstance]
- get_thread(thread_id, /)¶
Returns a thread with the given ID.
Added in version 2.0.
- Parameters:
thread_id (
int) – The ID to search for.- Returns:
The returned thread or
Noneif not found.- Return type:
Optional[
Thread]
- await integrations()¶
This function is a coroutine.
Returns a list of all integrations attached to the guild.
You must have the
manage_guildpermission to do this.Added in version 1.4.
- Returns:
The list of integrations that are attached to the guild.
- Return type:
List[
Integration]- Raises:
Forbidden – You do not have permission to create the integration.
HTTPException – Fetching the integrations failed.
- await invites()¶
This function is a coroutine.
Returns a list of all active instant invites from the guild.
You must have the
manage_guildpermission to get this information.- Returns:
The list of invites that are currently active.
- Return type:
List[
Invite]- Raises:
Forbidden – You do not have proper permissions to get the information.
HTTPException – An error occurred while fetching the information.
- await is_chunked()¶
Returns a boolean indicating if the guild is “chunked”.
A chunked guild means that
member_countis equal to the number of members stored in the internalmemberscache.If this value returns
False, then you should request for offline members.- Return type:
- await is_large()¶
Indicates if the guild is a ‘large’ guild.
A large guild is defined as having more than
large_thresholdcount members, which for this library is set to the maximum of 250.- Return type:
- property jump_url: str¶
Returns a URL that allows the client to jump to the guild.
Added in version 2.0.
- await kick(user, *, reason=None)¶
This function is a coroutine.
Kicks a user from the guild.
The user must meet the
abc.Snowflakeabc.You must have the
kick_memberspermission to do this.- Parameters:
user (
abc.Snowflake) – The user to kick from their guild.reason (Optional[
str]) – The reason the user got kicked.
- Raises:
Forbidden – You do not have the proper permissions to kick.
HTTPException – Kicking failed.
- Return type:
- await leave()¶
This function is a coroutine.
Leaves the guild. :rtype:
NoneNote
You cannot leave the guild that you own, you must delete it instead via
delete().- Raises:
HTTPException – Leaving the guild failed.
- property member_count: int¶
Returns the true member count regardless of it being loaded fully or not.
Warning
Due to a Discord limitation, in order for this attribute to remain up-to-date and accurate, it requires
Intents.membersto be specified.
- await modify_incident_actions(*, invites_disabled_until=Undefined.MISSING, dms_disabled_until=Undefined.MISSING, reason=Undefined.MISSING)¶
This function is a coroutine.
Modify the guild’s incident actions, controlling when invites or DMs are re-enabled after being temporarily disabled. Requires the
manage_guildpermission.- Parameters:
invites_disabled_until (Optional[
datetime.datetime]) – The ISO8601 timestamp indicating when invites will be enabled again, orNoneto enable invites immediately.dms_disabled_until (Optional[
datetime.datetime]) – The ISO8601 timestamp indicating when DMs will be enabled again, orNoneto enable DMs immediately.reason (Optional[
str]) – The reason for this action, used for the audit log.
- Returns:
The updated incidents data for the guild.
- Return type:
IncidentsData
- await onboarding()¶
This function is a coroutine.
Returns the
Onboardingflow for the guild.Added in version 2.5.
- Returns:
The onboarding flow for the guild.
- Return type:
Onboarding- Raises:
HTTPException – Retrieving the onboarding flow failed somehow.
Gets the premium subscriber role, AKA “boost” role, in this guild.
Added in version 1.6.
A list of members who have “boosted” this guild.
- await prune_members(*, days, compute_prune_count=True, roles=Undefined.MISSING, reason=None)¶
This function is a coroutine.
Prunes the guild from its inactive members.
The inactive members are denoted if they have not logged on in
daysnumber of days and have no roles.You must have the
kick_memberspermission to use this.To check how many members you would prune without actually pruning, see the
estimate_pruned_members()function.To prune members that have specific roles see the
rolesparameter.Changed in version 1.4: The
roleskeyword-only parameter was added.- Parameters:
days (
int) – The number of days before counting as inactive.reason (Optional[
str]) – The reason for doing this action. Shows up on the audit log.compute_prune_count (
bool) – Whether to compute the prune count. This defaults toTruewhich makes it prone to timeouts in very large guilds. In order to prevent timeouts, you must set this toFalse. If this is set toFalse, then this function will always returnNone.roles (List[
abc.Snowflake]) – A list ofabc.Snowflakethat represent roles to include in the pruning process. If a member has a role that is not specified, they’ll be excluded.
- Raises:
Forbidden – You do not have permissions to prune members.
HTTPException – An error occurred while pruning members.
InvalidArgument – An integer was not passed for
days.
- Returns:
The number of members pruned. If
compute_prune_countisFalsethen this returnsNone.- Return type:
Optional[
int]
- property public_updates_channel: TextChannel | None¶
Return’s the guild’s channel where admins and moderators of the guilds receive notices from Discord. The guild must be a Community guild.
If no channel is set, then this returns
None.Added in version 1.4.
- await query_members(query=None, *, limit=5, user_ids=None, presences=False, cache=True)¶
This function is a coroutine.
Request members that belong to this guild whose username starts with the query given.
This is a websocket operation and can be slow.
Added in version 1.3.
- Parameters:
query (Optional[
str]) – The string that the username’s start with.user_ids (Optional[List[
int]]) –List of user IDs to search for. If the user ID is not in the guild then it won’t be returned.
Added in version 1.4.
limit (Optional[
int]) – The maximum number of members to send back. If no query is passed, passingNonereturns all members. If aqueryoruser_idsis passed, must be between 1 and 100. Defaults to 5.presences (Optional[
bool]) –Whether to request for presences to be provided. This defaults to
False.Added in version 1.6.
cache (
bool) – Whether to cache the members internally. This makes operations such asget_member()work for those that matched. Defaults toTrue.
- Returns:
The list of members that have matched the query.
- Return type:
List[
Member]- Raises:
asyncio.TimeoutError – The query timed out waiting for the members.
ValueError – Invalid parameters were passed to the function
ClientException – The presences intent is not enabled.
- property roles: list[Role]¶
Returns a
listof the guild’s roles in hierarchy order.The first element of this list will be the lowest role in the hierarchy.
- property rules_channel: TextChannel | None¶
Return’s the guild’s channel used for the rules. The guild must be a Community guild.
If no channel is set, then this returns
None.Added in version 1.3.
- property scheduled_events: list[ScheduledEvent]¶
A list of scheduled events in this guild.
- await search_members(query, *, limit=1000)¶
Search for guild members whose usernames or nicknames start with the query string. Unlike
fetch_members(), this does not requireIntents.members().Note
This method is an API call. For general usage, consider filtering
membersinstead.Added in version 2.6.
- Parameters:
- Returns:
The list of members that have matched the query.
- Return type:
List[
Member]- Raises:
HTTPException – Getting the members failed.
- property self_role: Role | None¶
Gets the role associated with this client’s user, if any.
Added in version 1.6.
- await set_mfa_required(required, *, reason=None)¶
This function is a coroutine.
Set whether it is required to have MFA enabled on your account to perform moderation actions. You must be the guild owner to do this.
- Parameters:
- Raises:
HTTPException – The operation failed.
Forbidden – You are not the owner of the guild.
- Return type:
- property soundboard_limit: int¶
The maximum number of soundboard slots this guild has.
Added in version 2.7.
- property sounds: list[SoundboardSound]¶
A list of soundboard sounds that belong to this guild.
Added in version 2.7.
This is sorted by the position and are in UI order from top to bottom.
- property stage_channels: list[StageChannel]¶
A list of stage channels that belong to this guild.
Added in version 1.7.
This is sorted by the position and are in UI order from top to bottom.
- property stage_instances: list[StageInstance]¶
Returns a
listof the guild’s stage instances that are currently running.Added in version 2.0.
- property sticker_limit: int¶
The maximum number of sticker slots this guild has.
Added in version 2.0.
- property system_channel: TextChannel | None¶
Returns the guild’s channel used for system messages.
If no channel is set, then this returns
None.
- property system_channel_flags: SystemChannelFlags¶
Returns the guild’s system channel settings.
- await templates()¶
This function is a coroutine.
Gets the list of templates from this guild.
Requires
manage_guildpermissions.Added in version 1.7.
- Returns:
The templates for this guild.
- Return type:
List[
Template]- Raises:
Forbidden – You don’t have permissions to get the templates.
- property text_channels: list[TextChannel]¶
A list of text channels that belong to this guild.
This is sorted by the position and are in UI order from top to bottom.
- property threads: list[Thread]¶
A list of threads that you have permission to view.
Added in version 2.0.
- await unban(user, *, reason=None)¶
This function is a coroutine.
Unbans a user from the guild.
The user must meet the
abc.Snowflakeabc.You must have the
ban_memberspermission to do this.- Parameters:
user (
abc.Snowflake) – The user to unban.reason (Optional[
str]) – The reason for doing this action. Shows up on the audit log.
- Raises:
Forbidden – You do not have the proper permissions to unban.
HTTPException – Unbanning failed.
- Return type:
- await vanity_invite()¶
This function is a coroutine.
Returns the guild’s special vanity invite.
The guild must have
VANITY_URLinfeatures.You must have the
manage_guildpermission to use this as well.- Returns:
The special vanity invite. If
Nonethen the guild does not have a vanity invite set.- Return type:
Optional[
Invite]- Raises:
Forbidden – You do not have the proper permissions to get this.
HTTPException – Retrieving the vanity invite failed.
- property voice_channels: list[VoiceChannel]¶
A list of voice channels that belong to this guild.
This is sorted by the position and are in UI order from top to bottom.
- property voice_client: VoiceClient | None¶
Returns the
VoiceClientassociated with this guild, if any.
- await webhooks()¶
This function is a coroutine.
Gets the list of webhooks from this guild.
Requires
manage_webhookspermissions.- Returns:
The webhooks for this guild.
- Return type:
List[
Webhook]- Raises:
Forbidden – You don’t have permissions to get the webhooks.
- await welcome_screen()¶
This function is a coroutine.
Returns the
WelcomeScreenof the guild.The guild must have
COMMUNITYinfeatures.You must have the
manage_guildpermission in order to get this.Added in version 2.0.
- Returns:
The welcome screen of guild.
- Return type:
WelcomeScreen- Raises:
Forbidden – You do not have the proper permissions to get this.
HTTPException – Retrieving the welcome screen failed somehow.
NotFound – The guild doesn’t have a welcome screen or community feature is disabled.
- await widget()¶
This function is a coroutine.
Returns the widget of the guild.
Note
The guild must have the widget enabled to get this information.
- Returns:
The guild’s widget.
- Return type:
Widget- Raises:
Forbidden – The widget for this guild is disabled.
HTTPException – Retrieving the widget failed.
- class discord.events.GuildCreate[source]¶
Internal event representing a guild becoming available via the gateway.
This event trickles down to the more distinct
GuildJoinandGuildAvailableevents. Users should typically listen to those events instead.This event inherits from
Guild.- await active_threads()¶
This function is a coroutine.
Returns a list of active
Threadthat the client can access.This includes both private and public threads.
Added in version 2.0.
- Returns:
The active threads
- Return type:
List[
Thread]- Raises:
HTTPException – The request to get the active threads failed.
- await audit_logs(*, limit=100, before=None, after=None, user=None, action=None)¶
Returns an
AsyncIteratorthat enables receiving the guild’s audit logs.You must have the
view_audit_logpermission to use this.See API documentation for more information about the before and after parameters.
- Parameters:
limit (Optional[
int]) – The number of entries to retrieve. IfNoneretrieve all entries.before (Union[
abc.Snowflake,datetime.datetime]) – Retrieve entries before this date or entry. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.after (Union[
abc.Snowflake,datetime.datetime]) – Retrieve entries after this date or entry. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.user (
abc.Snowflake) – The moderator to filter entries from.action (
AuditLogAction) – The action to filter with.
- Yields:
AuditLogEntry– The audit log entry.- Raises:
Forbidden – You are not allowed to fetch audit logs
HTTPException – An error occurred while fetching the audit logs.
- Return type:
AuditLogIterator
Examples
Getting the first 100 entries:
async for entry in guild.audit_logs(limit=100): print(f"{entry.user} did {entry.action} to {await entry.get_target()}")
Getting entries for a specific action:
async for entry in guild.audit_logs(action=discord.AuditLogAction.ban): print(f"{entry.user} banned {await entry.get_target()}")
Getting entries made by a specific user:
entries = await guild.audit_logs(limit=None, user=guild.me).flatten() await channel.send(f"I made {len(entries)} moderation actions.")
- await ban(user, *, delete_message_seconds=None, reason=None)¶
This function is a coroutine.
Bans a user from the guild.
The user must meet the
abc.Snowflakeabc.You must have the
ban_memberspermission to do this.- Parameters:
user (
abc.Snowflake) – The user to ban from their guild.delete_message_seconds (Optional[
int]) – The number of seconds worth of messages to delete from the user in the guild. The minimum is 0 and the maximum is 604800 (i.e. 7 days). The default is 0.reason (Optional[
str]) – The reason the user got banned.
- Raises:
Forbidden – You do not have the proper permissions to ban.
HTTPException – Banning failed.
- Return type:
- bans(limit=None, before=None, after=None)¶
This function is a coroutine.
Retrieves an
AsyncIteratorthat enables receiving the guild’s bans. In order to use this, you must have theban_memberspermission. Users will always be returned in ascending order sorted by user ID. If both thebeforeandafterparameters are provided, only before is respected.Changed in version 2.5: The
before. andafterparameters were changed. They are now of the typeabc.Snowflakeinstead of SnowflakeTime to comply with the discord api.Changed in version 2.0: The
limit,before. andafterparameters were added. Now returns aBanIteratorinstead of a list ofBanEntryobjects.All parameters are optional.
- Parameters:
limit (Optional[
int]) – The number of bans to retrieve. Defaults to 1000.before (Optional[
abc.Snowflake]) – Retrieve bans before the given user.after (Optional[
abc.Snowflake]) – Retrieve bans after the given user.
- Yields:
BanEntry– The ban entry for the ban.- Raises:
Forbidden – You do not have proper permissions to get the information.
HTTPException – An error occurred while fetching the information.
- Return type:
BanIterator
Examples
Usage
async for ban in guild.bans(limit=150): print(ban.user.name)
Flattening into a list
bans = await guild.bans(limit=150).flatten() # bans is now a list of BanEntry...
- await bulk_ban(*users, delete_message_seconds=None, reason=None)¶
This function is a coroutine.
Bulk ban users from the guild.
The users must meet the
abc.Snowflakeabc.You must have the
ban_memberspermission to do this.Example Usage:
# Ban multiple users successes, failures = await guild.bulk_ban(user1, user2, user3, ..., reason="Raid") # Ban a list of users successes, failures = await guild.bulk_ban(*users)
- Parameters:
*users (
abc.Snowflake) – An argument list of users to ban from the guild, up to 200.delete_message_seconds (Optional[
int]) – The number of seconds worth of messages to delete from the user in the guild. The minimum is 0 and the maximum is 604800 (i.e. 7 days). The default is 0.reason (Optional[
str]) – The reason the users were banned.
- Returns:
Returns two lists: the first contains members that were successfully banned, while the second is members that could not be banned.
- Return type:
Tuple[List[
abc.Snowflake], List[abc.Snowflake]]- Raises:
ValueError – You tried to ban more than 200 users.
Forbidden – You do not have the proper permissions to ban.
HTTPException – No users were banned.
- by_category()¶
Returns every
CategoryChanneland their associated channels.These channels and categories are sorted in the official Discord UI order.
If the channels do not have a category, then the first element of the tuple is
None.- Returns:
The categories and their associated channels.
- Return type:
List[Tuple[Optional[
CategoryChannel], List[abc.GuildChannel]]]
- property categories: list[CategoryChannel]¶
A list of categories that belong to this guild.
This is sorted by the position and are in UI order from top to bottom.
- await change_voice_state(*, channel, self_mute=False, self_deaf=False)¶
This function is a coroutine.
Changes client’s voice state in the guild.
Added in version 1.4.
- await chunk(*, cache=True)¶
This function is a coroutine.
Requests all members that belong to this guild. In order to use this,
Intents.members()must be enabled.This is a websocket operation and can be slow.
Added in version 1.5.
- Parameters:
cache (
bool) – Whether to cache the members as well.- Raises:
ClientException – The members intent is not enabled.
- Return type:
- await create_auto_moderation_rule(*, name, event_type, trigger_type, trigger_metadata, actions, enabled=False, exempt_roles=None, exempt_channels=None, reason=None)¶
Creates an auto moderation rule.
- Parameters:
name (
str) – The name of the auto moderation rule.event_type (
AutoModEventType) – The type of event that triggers the rule.trigger_type (
AutoModTriggerType) – The rule’s trigger type.trigger_metadata (
AutoModTriggerMetadata) – The rule’s trigger metadata.actions (List[
AutoModAction]) – The actions to take when the rule is triggered.enabled (
bool) – Whether the rule is enabled.exempt_roles (List[
abc.Snowflake]) – A list of roles that are exempt from the rule.exempt_channels (List[
abc.Snowflake]) – A list of channels that are exempt from the rule.reason (Optional[
str]) – The reason for creating the rule. Shows up in the audit log.
- Returns:
The new auto moderation rule.
- Return type:
AutoModRule- Raises:
HTTPException – Creating the auto moderation rule failed.
Forbidden – You do not have the Manage Guild permission.
- await create_category(name, *, overwrites=Undefined.MISSING, reason=None, position=Undefined.MISSING)¶
This function is a coroutine.
Same as
create_text_channel()except makes aCategoryChannelinstead.Note
The
categoryparameter is not supported in this function since categories cannot have categories.- Returns:
The channel that was just created.
- Return type:
CategoryChannel- Raises:
Forbidden – You do not have the proper permissions to create this channel.
HTTPException – Creating the channel failed.
InvalidArgument – The permission overwrite information is not in proper form.
- Parameters:
- await create_category_channel(name, *, overwrites=Undefined.MISSING, reason=None, position=Undefined.MISSING)¶
This function is a coroutine.
Same as
create_text_channel()except makes aCategoryChannelinstead.Note
The
categoryparameter is not supported in this function since categories cannot have categories.- Returns:
The channel that was just created.
- Return type:
CategoryChannel- Raises:
Forbidden – You do not have the proper permissions to create this channel.
HTTPException – Creating the channel failed.
InvalidArgument – The permission overwrite information is not in proper form.
- Parameters:
- await create_custom_emoji(*, name, image, roles=Undefined.MISSING, reason=None)¶
This function is a coroutine.
Creates a custom
GuildEmojifor the guild.There is currently a limit of 50 static and animated emojis respectively per guild, unless the guild has the
MORE_EMOJIfeature which extends the limit to 200.You must have the
manage_emojispermission to do this.- Parameters:
name (
str) – The emoji name. Must be at least 2 characters.image (
bytes) – The bytes-like object representing the image data to use. Only JPG, PNG and GIF images are supported.roles (List[
Role]) – AlistofRoles that can use this emoji. Leave empty to make it available to everyone.reason (Optional[
str]) – The reason for creating this emoji. Shows up on the audit log.
- Raises:
Forbidden – You are not allowed to create emojis.
HTTPException – An error occurred creating an emoji.
- Returns:
The created emoji.
- Return type:
GuildEmoji
- await create_forum_channel(name, *, reason=None, category=None, position=Undefined.MISSING, topic=Undefined.MISSING, slowmode_delay=Undefined.MISSING, nsfw=Undefined.MISSING, overwrites=Undefined.MISSING, default_reaction_emoji=Undefined.MISSING, available_tags=Undefined.MISSING, default_sort_order=Undefined.MISSING, default_thread_slowmode_delay=Undefined.MISSING, default_auto_archive_duration=Undefined.MISSING)¶
This function is a coroutine.
Creates a
ForumChannelfor the guild.Note that you need the
manage_channelspermission to create the channel.The
overwritesparameter can be used to create a ‘secret’ channel upon creation. This parameter expects adictof overwrites with the target (either aMemberor aRole) as the key and aPermissionOverwriteas the value.Note
Creating a channel of a specified position will not update the position of other channels to follow suit. A follow-up call to
edit()will be required to update the position of the channel in the channel list.- Parameters:
name (
str) – The channel’s name.overwrites (Dict[Union[
Role,Member,Snowflake],PermissionOverwrite]) – The overwrites to apply to the channel. Useful for creating secret channels.category (Optional[
CategoryChannel]) – The category to place the newly created channel under. The permissions will be automatically synced to category if no overwrites are provided.position (
int) – The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0.topic (
str) – The new channel’s topic.slowmode_delay (
int) – Specifies the slowmode rate limit for user in this channel, in seconds. A value of0disables slowmode. The maximum value possible is21600.nsfw (
bool) – Whether the channel is marked as NSFW.reason (Optional[
str]) – The reason for creating this channel. Shows up on the audit log.default_reaction_emoji (Optional[
GuildEmoji|int|str]) –The default reaction emoji. Can be a unicode emoji or a custom emoji in the forms:
GuildEmoji, snowflake ID, string representation (eg. ‘<a:emoji_name:emoji_id>’).Added in version v2.5.
available_tags (List[
ForumTag]) –The set of tags that can be used in a forum channel.
Added in version 2.7.
default_sort_order (Optional[
SortOrder]) –The default sort order type used to order posts in this channel.
Added in version 2.7.
default_thread_slowmode_delay (Optional[
int]) –The initial slowmode delay to set on newly created threads in this channel.
Added in version 2.7.
default_auto_archive_duration (
int) –The default auto archive duration in minutes for threads created in this channel.
Added in version 2.7.
- Returns:
The channel that was just created.
- Return type:
ForumChannel- Raises:
Forbidden – You do not have the proper permissions to create this channel.
HTTPException – Creating the channel failed.
InvalidArgument – The argument is not in proper form.
Examples
Creating a basic channel:
channel = await guild.create_forum_channel("cool-channel")
Creating a “secret” channel:
overwrites = { guild.default_role: discord.PermissionOverwrite(read_messages=False), guild.me: discord.PermissionOverwrite(read_messages=True), } channel = await guild.create_forum_channel("secret", overwrites=overwrites)
- await create_integration(*, type, id)¶
This function is a coroutine.
Attaches an integration to the guild.
You must have the
manage_guildpermission to do this.Added in version 1.4.
- Parameters:
- Raises:
Forbidden – You do not have permission to create the integration.
HTTPException – The account could not be found.
- Return type:
- await create_role(*, name=Undefined.MISSING, permissions=Undefined.MISSING, color=Undefined.MISSING, colour=Undefined.MISSING, colors=Undefined.MISSING, colours=Undefined.MISSING, holographic=Undefined.MISSING, hoist=Undefined.MISSING, mentionable=Undefined.MISSING, reason=None, icon=Undefined.MISSING, unicode_emoji=Undefined.MISSING)¶
This function is a coroutine.
Creates a
Rolefor the guild.All fields are optional.
You must have the
manage_rolespermission to do this.Changed in version 1.6: Can now pass
inttocolourkeyword-only parameter.- Parameters:
name (
str) – The role name. Defaults to ‘new role’.permissions (
Permissions) – The permissions to have. Defaults to no permissions.colour (Union[
Colour,int]) – The colour for the role. Defaults toColour.default(). This is aliased tocoloras well.hoist (
bool) – Indicates if the role should be shown separately in the member list. Defaults toFalse.mentionable (
bool) – Indicates if the role should be mentionable by others. Defaults toFalse.reason (Optional[
str]) – The reason for creating this role. Shows up on the audit log.icon (Optional[
bytes]) – A bytes-like object representing the icon. Only PNG/JPEG/WebP is supported. If this argument is passed,unicode_emojiis set to None. Only available to guilds that containROLE_ICONSinGuild.features.unicode_emoji (Optional[
str]) – The role’s unicode emoji. If this argument is passed,iconis set to None. Only available to guilds that containROLE_ICONSinGuild.features.color (Colour | int | utils.Undefined)
colors (RoleColours | utils.Undefined)
colours (RoleColours | utils.Undefined)
holographic (bool | utils.Undefined)
- Returns:
The newly created role.
- Return type:
Role- Raises:
Forbidden – You do not have permissions to create the role.
HTTPException – Creating the role failed.
InvalidArgument – An invalid keyword argument was given.
- await create_scheduled_event(*, name, description=Undefined.MISSING, start_time, end_time=Undefined.MISSING, location, privacy_level=ScheduledEventPrivacyLevel.guild_only, reason=None, image=Undefined.MISSING)¶
This function is a coroutine. Creates a scheduled event.
- Parameters:
name (
str) – The name of the scheduled event.description (Optional[
str]) – The description of the scheduled event.start_time (
datetime.datetime) – A datetime object of when the scheduled event is supposed to start.end_time (Optional[
datetime.datetime]) – A datetime object of when the scheduled event is supposed to end.location (
ScheduledEventLocation) – The location of where the event is happening.privacy_level (
ScheduledEventPrivacyLevel) – The privacy level of the event. Currently, the only possible value isScheduledEventPrivacyLevel.guild_only, which is default, so there is no need to change this parameter.reason (Optional[
str]) – The reason to show in the audit log.image (Optional[
bytes]) – The cover image of the scheduled event
- Returns:
The created scheduled event.
- Return type:
Optional[
ScheduledEvent]- Raises:
Forbidden – You do not have the Manage Events permission.
HTTPException – The operation failed.
- await create_sound(name, sound, volume=1.0, emoji=None, reason=None)¶
This function is a coroutine. Creates a
SoundboardSoundin the guild. You must havePermissions.manage_expressionspermission to use this.Added in version 2.7.
- Parameters:
name (
str) – The name of the sound.sound (
bytes) – The bytes-like object representing the sound data. Only MP3 sound files that are less than 5.2 seconds long are supported.volume (
float) – The volume of the sound. Defaults to 1.0.emoji (Optional[Union[
PartialEmoji,GuildEmoji,str]]) – The emoji of the sound.reason (Optional[
str]) – The reason for creating this sound. Shows up on the audit log.
- Returns:
The created sound.
- Return type:
SoundboardSound- Raises:
HTTPException – Creating the sound failed.
Forbidden – You do not have permissions to create sounds.
- await create_stage_channel(name, *, topic, position=Undefined.MISSING, overwrites=Undefined.MISSING, category=None, reason=None, bitrate=Undefined.MISSING, user_limit=Undefined.MISSING, rtc_region=Undefined.MISSING, video_quality_mode=Undefined.MISSING, slowmode_delay=Undefined.MISSING, nsfw=Undefined.MISSING)¶
This function is a coroutine.
This is similar to
create_text_channel()except makes aStageChannelinstead.Added in version 1.7.
- Parameters:
name (
str) – The channel’s name.topic (
str) – The new channel’s topic.overwrites (Dict[Union[
Role,Member,Snowflake],PermissionOverwrite]) – The overwrites to apply to the channel. Useful for creating secret channels.category (Optional[
CategoryChannel]) – The category to place the newly created channel under. The permissions will be automatically synced to category if no overwrites are provided.position (
int) – The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0.reason (Optional[
str]) – The reason for creating this channel. Shows up on the audit log.bitrate (
int) –The channel’s preferred audio bitrate in bits per second.
Added in version 2.7.
user_limit (
int) –The channel’s limit for number of members that can be in a voice channel.
Added in version 2.7.
rtc_region (Optional[
VoiceRegion]) –The region for the voice channel’s voice communication. A value of
Noneindicates automatic voice region detection.Added in version 2.7.
video_quality_mode (
VideoQualityMode) –The camera video quality for the voice channel’s participants.
Added in version 2.7.
slowmode_delay (
int) –Specifies the slowmode rate limit for user in this channel, in seconds. A value of
0disables slowmode. The maximum value possible is21600.Added in version 2.7.
nsfw (
bool) –Whether the channel is marked as NSFW.
Added in version 2.7.
- Returns:
The channel that was just created.
- Return type:
StageChannel- Raises:
Forbidden – You do not have the proper permissions to create this channel.
HTTPException – Creating the channel failed.
InvalidArgument – The permission overwrite information is not in proper form.
- await create_sticker(*, name, description=None, emoji, file, reason=None)¶
This function is a coroutine.
Creates a
Stickerfor the guild.You must have
manage_emojis_and_stickerspermission to do this.Added in version 2.0.
- Parameters:
name (
str) – The sticker name. Must be 2 to 30 characters.description (Optional[
str]) – The sticker’s description. If used, must be 2 to 100 characters.emoji (
str) – The name of a unicode emoji that represents the sticker’s expression.file (
File) – The file of the sticker to upload.reason (
str) – The reason for creating this sticker. Shows up on the audit log.
- Returns:
The created sticker.
- Return type:
GuildSticker- Raises:
Forbidden – You are not allowed to create stickers.
HTTPException – An error occurred creating a sticker.
TypeError – The parameters for the sticker are not correctly formatted.
- await create_template(*, name, description=Undefined.MISSING)¶
This function is a coroutine.
Creates a template for the guild.
You must have the
manage_guildpermission to do this.Added in version 1.7.
- await create_test_entitlement(sku)¶
This function is a coroutine.
Creates a test entitlement for the guild.
- Parameters:
sku (
Snowflake) – The SKU to create a test entitlement for.- Returns:
The created entitlement.
- Return type:
Entitlement
- await create_text_channel(name, *, reason=None, category=None, position=Undefined.MISSING, topic=Undefined.MISSING, slowmode_delay=Undefined.MISSING, nsfw=Undefined.MISSING, overwrites=Undefined.MISSING, default_thread_slowmode_delay=Undefined.MISSING, default_auto_archive_duration=Undefined.MISSING)¶
This function is a coroutine.
Creates a
TextChannelfor the guild.Note that you need the
manage_channelspermission to create the channel.The
overwritesparameter can be used to create a ‘secret’ channel upon creation. This parameter expects adictof overwrites with the target (either aMemberor aRole) as the key and aPermissionOverwriteas the value.Note
Creating a channel of a specified position will not update the position of other channels to follow suit. A follow-up call to
edit()will be required to update the position of the channel in the channel list.- Parameters:
name (
str) – The channel’s name.overwrites (Dict[Union[
Role,Member,Snowflake],PermissionOverwrite]) – The overwrites to apply to the channel. Useful for creating secret channels.category (Optional[
CategoryChannel]) – The category to place the newly created channel under. The permissions will be automatically synced to category if no overwrites are provided.position (
int) – The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0.topic (
str) – The new channel’s topic.slowmode_delay (
int) – Specifies the slowmode rate limit for user in this channel, in seconds. A value of 0 disables slowmode. The maximum value possible is 21600.nsfw (
bool) – Whether the channel is marked as NSFW.reason (Optional[
str]) – The reason for creating this channel. Shows up on the audit log.default_thread_slowmode_delay (Optional[
int]) –The initial slowmode delay to set on newly created threads in this channel.
Added in version 2.7.
default_auto_archive_duration (
int) –The default auto archive duration in minutes for threads created in this channel.
Added in version 2.7.
- Returns:
The channel that was just created.
- Return type:
TextChannel- Raises:
Forbidden – You do not have the proper permissions to create this channel.
HTTPException – Creating the channel failed.
InvalidArgument – The permission overwrite information is not in proper form.
Examples
Creating a basic channel:
channel = await guild.create_text_channel("cool-channel")
Creating a “secret” channel:
overwrites = { guild.default_role: discord.PermissionOverwrite(read_messages=False), guild.me: discord.PermissionOverwrite(read_messages=True), } channel = await guild.create_text_channel("secret", overwrites=overwrites)
- await create_voice_channel(name, *, reason=None, category=None, position=Undefined.MISSING, bitrate=Undefined.MISSING, user_limit=Undefined.MISSING, rtc_region=Undefined.MISSING, video_quality_mode=Undefined.MISSING, overwrites=Undefined.MISSING, slowmode_delay=Undefined.MISSING, nsfw=Undefined.MISSING)¶
This function is a coroutine.
This is similar to
create_text_channel()except makes aVoiceChannelinstead.- Parameters:
name (
str) – The channel’s name.overwrites (Dict[Union[
Role,Member,Snowflake],PermissionOverwrite]) – The overwrites to apply to the channel. Useful for creating secret channels.category (Optional[
CategoryChannel]) – The category to place the newly created channel under. The permissions will be automatically synced to category if no overwrites are provided.position (
int) – The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0.bitrate (
int) – The channel’s preferred audio bitrate in bits per second.user_limit (
int) – The channel’s limit for number of members that can be in a voice channel.rtc_region (Optional[
VoiceRegion]) –The region for the voice channel’s voice communication. A value of
Noneindicates automatic voice region detection.Added in version 1.7.
video_quality_mode (
VideoQualityMode) –The camera video quality for the voice channel’s participants.
Added in version 2.0.
reason (Optional[
str]) – The reason for creating this channel. Shows up on the audit log.slowmode_delay (
int) –Specifies the slowmode rate limit for user in this channel, in seconds. A value of
0disables slowmode. The maximum value possible is21600.Added in version 2.7.
nsfw (
bool) –Whether the channel is marked as NSFW.
Added in version 2.7.
- Returns:
The channel that was just created.
- Return type:
VoiceChannel- Raises:
Forbidden – You do not have the proper permissions to create this channel.
HTTPException – Creating the channel failed.
InvalidArgument – The permission overwrite information is not in proper form.
- await delete()¶
This function is a coroutine.
Deletes the guild. You must be the guild owner to delete the guild.
- Raises:
HTTPException – Deleting the guild failed.
Forbidden – You do not have permissions to delete the guild.
- Return type:
- await delete_auto_moderation_rule(id, *, reason=None)¶
Deletes an auto moderation rule.
- Parameters:
- Raises:
HTTPException – Deleting the auto moderation rule failed.
Forbidden – You do not have the Manage Guild permission.
- Return type:
- await delete_emoji(emoji, *, reason=None)¶
This function is a coroutine.
Deletes the custom
GuildEmojifrom the guild.You must have
manage_emojispermission to do this.- Parameters:
emoji (
abc.Snowflake) – The emoji you are deleting.reason (Optional[
str]) – The reason for deleting this emoji. Shows up on the audit log.
- Raises:
Forbidden – You are not allowed to delete emojis.
HTTPException – An error occurred deleting the emoji.
- Return type:
- await delete_sticker(sticker, *, reason=None)¶
This function is a coroutine.
Deletes the custom
Stickerfrom the guild.You must have
manage_emojis_and_stickerspermission to do this.Added in version 2.0.
- Parameters:
sticker (
abc.Snowflake) – The sticker you are deleting.reason (Optional[
str]) – The reason for deleting this sticker. Shows up on the audit log.
- Raises:
Forbidden – You are not allowed to delete stickers.
HTTPException – An error occurred deleting the sticker.
- Return type:
- await edit(*, reason=Undefined.MISSING, name=Undefined.MISSING, description=Undefined.MISSING, icon=Undefined.MISSING, banner=Undefined.MISSING, splash=Undefined.MISSING, discovery_splash=Undefined.MISSING, community=Undefined.MISSING, afk_channel=Undefined.MISSING, owner=Undefined.MISSING, afk_timeout=Undefined.MISSING, default_notifications=Undefined.MISSING, verification_level=Undefined.MISSING, explicit_content_filter=Undefined.MISSING, system_channel=Undefined.MISSING, system_channel_flags=Undefined.MISSING, preferred_locale=Undefined.MISSING, rules_channel=Undefined.MISSING, public_updates_channel=Undefined.MISSING, premium_progress_bar_enabled=Undefined.MISSING, disable_invites=Undefined.MISSING, discoverable=Undefined.MISSING, disable_raid_alerts=Undefined.MISSING, enable_activity_feed=Undefined.MISSING)¶
This function is a coroutine.
Edits the guild.
You must have the
manage_guildpermission to edit the guild.Changed in version 1.4: The rules_channel and public_updates_channel keyword-only parameters were added.
Changed in version 2.0: The discovery_splash and community keyword-only parameters were added.
Changed in version 2.0: The newly updated guild is returned.
- Parameters:
name (
str) – The new name of the guild.description (Optional[
str]) – The new description of the guild. Could beNonefor no description. This is only available to guilds that containPUBLICinGuild.features.icon (
bytes) – A bytes-like object representing the icon. Only PNG/JPEG is supported. GIF is only available to guilds that containANIMATED_ICONinGuild.features. Could beNoneto denote removal of the icon.banner (
bytes) – A bytes-like object representing the banner. Could beNoneto denote removal of the banner. This is only available to guilds that containBANNERinGuild.features.splash (
bytes) – A bytes-like object representing the invite splash. Only PNG/JPEG supported. Could beNoneto denote removing the splash. This is only available to guilds that containINVITE_SPLASHinGuild.features.discovery_splash (
bytes) – A bytes-like object representing the discovery splash. Only PNG/JPEG supported. Could beNoneto denote removing the splash. This is only available to guilds that containDISCOVERABLEinGuild.features.community (
bool) – Whether the guild should be a Community guild. If set toTrue, bothrules_channelandpublic_updates_channelparameters are required.afk_channel (Optional[
VoiceChannel]) – The new channel that is the AFK channel. Could beNonefor no AFK channel.afk_timeout (
int) – The number of seconds until someone is moved to the AFK channel.owner (
Member) – The new owner of the guild to transfer ownership to. Note that you must be owner of the guild to do this.verification_level (
VerificationLevel) – The new verification level for the guild.default_notifications (
NotificationLevel) – The new default notification level for the guild.explicit_content_filter (
ContentFilter) – The new explicit content filter for the guild.system_channel (Optional[
TextChannel]) – The new channel that is used for the system channel. Could beNonefor no system channel.system_channel_flags (
SystemChannelFlags) – The new system channel settings to use with the new system channel.preferred_locale (
str) – The new preferred locale for the guild. Used as the primary language in the guild. If set, this must be an ISO 639 code, e.g.en-USorjaorzh-CN.rules_channel (Optional[
TextChannel]) – The new channel that is used for rules. This is only available to guilds that containPUBLICinGuild.features. Could beNonefor no rules channel.public_updates_channel (Optional[
TextChannel]) – The new channel that is used for public updates from Discord. This is only available to guilds that containPUBLICinGuild.features. Could beNonefor no public updates channel.premium_progress_bar_enabled (
bool) – Whether the guild should have premium progress bar enabled.disable_invites (
bool) – Whether the guild should have server invites enabled or disabled.discoverable (
bool) – Whether the guild should be discoverable in the discover tab.disable_raid_alerts (
bool) – Whether activity alerts for the guild should be disabled.enable_activity_feed (class:bool) – Whether the guild’s user activity feed should be enabled.
reason (Optional[
str]) – The reason for editing this guild. Shows up on the audit log.
- Raises:
Forbidden – You do not have permissions to edit the guild.
HTTPException – Editing the guild failed.
InvalidArgument – The image format passed in to
iconis invalid. It must be PNG or JPG. This is also raised if you are not the owner of the guild and request an ownership transfer.
- Returns:
The newly updated guild. Note that this has the same limitations as mentioned in
Client.fetch_guild()and may not have full data.- Return type:
Guild
- await edit_onboarding(*, prompts=Undefined.MISSING, default_channels=Undefined.MISSING, enabled=Undefined.MISSING, mode=Undefined.MISSING, reason=Undefined.MISSING)¶
This function is a coroutine.
A shorthand for
Onboarding.editwithout fetching the onboarding flow.You must have the
manage_guildandmanage_rolespermissions in the guild to do this.- Parameters:
prompts (Optional[List[
OnboardingPrompt]]) – The new list of prompts for this flow.default_channels (Optional[List[
Snowflake]]) – The new default channels that users are opted into.enabled (Optional[
bool]) – Whether onboarding should be enabled. Setting this toTruerequires the guild to haveCOMMUNITYinfeaturesand at least 7default_channels.mode (Optional[
OnboardingMode]) – The new onboarding mode.reason (Optional[
str]) – The reason that shows up on Audit log.
- Returns:
The updated onboarding flow.
- Return type:
Onboarding- Raises:
HTTPException – Editing the onboarding flow failed somehow.
Forbidden – You don’t have permissions to edit the onboarding flow.
- await edit_role_positions(positions, *, reason=None)¶
This function is a coroutine.
Bulk edits a list of
Rolein the guild.You must have the
manage_rolespermission to do this.Added in version 1.4.
Example:
positions = { bots_role: 1, # penultimate role tester_role: 2, admin_role: 6, } await guild.edit_role_positions(positions=positions)
- Parameters:
- Returns:
A list of all the roles in the guild.
- Return type:
List[
Role]- Raises:
Forbidden – You do not have permissions to move the roles.
HTTPException – Moving the roles failed.
InvalidArgument – An invalid keyword argument was given.
- await edit_welcome_screen(**options)¶
This function is a coroutine.
A shorthand for
WelcomeScreen.editwithout fetching the welcome screen.You must have the
manage_guildpermission in the guild to do this.The guild must have
COMMUNITYinGuild.features- Parameters:
description (Optional[
str]) – The new description of welcome screen.welcome_channels (Optional[List[
WelcomeScreenChannel]]) – The welcome channels. The order of the channels would be same as the passed list order.enabled (Optional[
bool]) – Whether the welcome screen should be displayed.reason (Optional[
str]) – The reason that shows up on audit log.
- Returns:
The edited welcome screen.
- Return type:
WelcomeScreen- Raises:
HTTPException – Editing the welcome screen failed somehow.
Forbidden – You don’t have permissions to edit the welcome screen.
NotFound – This welcome screen does not exist.
- await edit_widget(*, enabled=Undefined.MISSING, channel=Undefined.MISSING)¶
This function is a coroutine.
Edits the widget of the guild.
You must have the
manage_guildpermission to use thisAdded in version 2.0.
- Parameters:
- Raises:
Forbidden – You do not have permission to edit the widget.
HTTPException – Editing the widget failed.
- Return type:
- entitlements(skus=None, before=None, after=None, limit=100, exclude_ended=False)¶
Returns an
AsyncIteratorthat enables fetching the guild’s entitlements.This is identical to
Client.entitlements()with theguildparameter.Added in version 2.6.
- Parameters:
skus (list[
abc.Snowflake] | None) – Limit the fetched entitlements to entitlements that are for these SKUs.before (
abc.Snowflake|datetime.datetime| None) – Retrieves guilds before this date or object. If a datetime is provided, it is recommended to use a UTC-aware datetime. If the datetime is naive, it is assumed to be local time.after (
abc.Snowflake|datetime.datetime| None) – Retrieve guilds after this date or object. If a datetime is provided, it is recommended to use a UTC-aware datetime. If the datetime is naive, it is assumed to be local time.limit (Optional[
int]) – The number of entitlements to retrieve. IfNone, retrieves every entitlement, which may be slow. Defaults to100.exclude_ended (
bool) – Whether to limit the fetched entitlements to those that have not ended. Defaults toFalse.
- Yields:
Entitlement– The application’s entitlements.- Raises:
HTTPException – Retrieving the entitlements failed.
- Return type:
EntitlementIterator
- await estimate_pruned_members(*, days, roles=Undefined.MISSING)¶
This function is a coroutine.
Similar to
prune_members()except instead of actually pruning members, it returns how many members it would prune from the guild had it been called.- Parameters:
days (
int) – The number of days before counting as inactive.roles (List[
abc.Snowflake]) –A list of
abc.Snowflakethat represent roles to include in the estimate. If a member has a role that is not specified, they’ll be excluded.Added in version 1.7.
- Returns:
The number of members estimated to be pruned.
- Return type:
- Raises:
Forbidden – You do not have permissions to prune members.
HTTPException – An error occurred while fetching the prune members estimate.
InvalidArgument – An integer was not passed for
days.
- await fetch_auto_moderation_rule(id)¶
This function is a coroutine.
Retrieves a
AutoModRulefrom rule ID.- Returns:
The requested auto moderation rule.
- Return type:
AutoModRule- Raises:
HTTPException – Getting the auto moderation rule failed.
Forbidden – You do not have the Manage Guild permission.
- Parameters:
id (
int)
- await fetch_auto_moderation_rules()¶
This function is a coroutine.
Retrieves a list of auto moderation rules for this guild.
- Returns:
The auto moderation rules for this guild.
- Return type:
List[
AutoModRule]- Raises:
HTTPException – Getting the auto moderation rules failed.
Forbidden – You do not have the Manage Guild permission.
- await fetch_ban(user)¶
This function is a coroutine.
Retrieves the
BanEntryfor a user.You must have the
ban_memberspermission to get this information.- Parameters:
user (
abc.Snowflake) – The user to get ban information from.- Returns:
The
BanEntryobject for the specified user.- Return type:
BanEntry- Raises:
Forbidden – You do not have proper permissions to get the information.
NotFound – This user is not banned.
HTTPException – An error occurred while fetching the information.
- await fetch_channel(channel_id, /)¶
This function is a coroutine.
Retrieves a
abc.GuildChannelorThreadwith the specified ID.Note
This method is an API call. For general usage, consider
get_channel_or_thread()instead.Added in version 2.0.
- Returns:
The channel from the ID.
- Return type:
Union[
abc.GuildChannel,Thread]- Raises:
InvalidData – An unknown channel type was received from Discord or the guild the channel belongs to is not the same as the one in this object points to.
HTTPException – Retrieving the channel failed.
NotFound – Invalid Channel ID.
Forbidden – You do not have permission to fetch this channel.
- Parameters:
channel_id (
int)
- await fetch_channels()¶
This function is a coroutine.
Retrieves all
abc.GuildChannelthat the guild has.Note
This method is an API call. For general usage, consider
channelsinstead.Added in version 1.2.
- Returns:
All channels in the guild.
- Return type:
Sequence[
discord.channel.base.GuildChannel]- Raises:
InvalidData – An unknown channel type was received from Discord.
HTTPException – Retrieving the channels failed.
- await fetch_emoji(emoji_id, /)¶
This function is a coroutine.
Retrieves a custom
GuildEmojifrom the guild.Note
This method is an API call. For general usage, consider iterating over
emojisinstead.- Parameters:
emoji_id (
int) – The emoji’s ID.- Returns:
The retrieved emoji.
- Return type:
GuildEmoji- Raises:
NotFound – The emoji requested could not be found.
HTTPException – An error occurred fetching the emoji.
- await fetch_emojis()¶
This function is a coroutine.
Retrieves all custom
GuildEmojis from the guild.Note
This method is an API call. For general usage, consider
emojisinstead.- Raises:
HTTPException – An error occurred fetching the emojis.
- Returns:
The retrieved emojis.
- Return type:
List[
GuildEmoji]
- await fetch_member(member_id, /)¶
This function is a coroutine.
Retrieves a
Memberfrom a guild ID, and a member ID.Note
This method is an API call. If you have
Intents.membersand member cache enabled, considerget_member()instead.- Parameters:
member_id (
int) – The member’s ID to fetch from.- Returns:
The member from the member ID.
- Return type:
Member- Raises:
Forbidden – You do not have access to the guild.
HTTPException – Fetching the member failed.
- fetch_members(*, limit=1000, after=None)¶
Retrieves an
AsyncIteratorthat enables receiving the guild’s members. In order to use this,Intents.members()must be enabled.Note
This method is an API call. For general usage, consider
membersinstead.Added in version 1.3.
All parameters are optional.
- Parameters:
limit (Optional[
int]) – The number of members to retrieve. Defaults to 1000. PassNoneto fetch all members. Note that this is potentially slow.after (Optional[Union[
abc.Snowflake,datetime.datetime]]) – Retrieve members after this date or object. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.
- Yields:
Member– The member with the member data parsed.- Raises:
ClientException – The members intent is not enabled.
HTTPException – Getting the members failed.
- Return type:
MemberIterator
Examples
Usage
async for member in guild.fetch_members(limit=150): print(member.name)
Flattening into a list
members = await guild.fetch_members(limit=150).flatten() # members is now a list of Member...
- await fetch_role(role_id)¶
This function is a coroutine.
Retrieves a
Rolethat the guild has.Note
This method is an API call. For general usage, consider using
get_roleinstead.Added in version 2.7.
- Returns:
The role in the guild with the specified ID.
- Return type:
Role- Raises:
HTTPException – Retrieving the role failed.
- Parameters:
role_id (
int)
- await fetch_roles()¶
This function is a coroutine.
Retrieves all
Rolethat the guild has.Note
This method is an API call. For general usage, consider
rolesinstead.Added in version 1.3.
- Returns:
All roles in the guild.
- Return type:
List[
Role]- Raises:
HTTPException – Retrieving the roles failed.
- await fetch_scheduled_event(event_id, /, *, with_user_count=True)¶
This function is a coroutine.
Retrieves a
ScheduledEventfrom event ID.Note
This method is an API call. If you have
Intents.scheduled_events, considerget_scheduled_event()instead.- Parameters:
- Returns:
The scheduled event from the event ID.
- Return type:
Optional[
ScheduledEvent]- Raises:
HTTPException – Fetching the event failed.
NotFound – Event not found.
- await fetch_scheduled_events(*, with_user_count=True)¶
This function is a coroutine.
Returns a list of
ScheduledEventin the guild.Note
This method is an API call. For general usage, consider
scheduled_eventsinstead.- Parameters:
with_user_count (Optional[
bool]) – If the scheduled event should be fetched with the number of users that are interested in the events. Defaults toTrue.- Returns:
The fetched scheduled events.
- Return type:
List[
ScheduledEvent]- Raises:
ClientException – The scheduled events intent is not enabled.
HTTPException – Getting the scheduled events failed.
- await fetch_sound(sound_id)¶
This function is a coroutine. Fetches a soundboard sound in the guild.
Added in version 2.7.
- Parameters:
sound_id (
int) – The ID of the sound.- Returns:
The sound.
- Return type:
SoundboardSound
- await fetch_sounds()¶
This function is a coroutine. Fetches all the soundboard sounds in the guild.
Added in version 2.7.
- Returns:
The sounds in the guild.
- Return type:
List[
SoundboardSound]
- await fetch_sticker(sticker_id, /)¶
This function is a coroutine.
Retrieves a custom
Stickerfrom the guild.Added in version 2.0.
Note
This method is an API call. For general usage, consider iterating over
stickersinstead.- Parameters:
sticker_id (
int) – The sticker’s ID.- Returns:
The retrieved sticker.
- Return type:
GuildSticker- Raises:
NotFound – The sticker requested could not be found.
HTTPException – An error occurred fetching the sticker.
- await fetch_stickers()¶
This function is a coroutine.
Retrieves a list of all
Stickers for the guild.Added in version 2.0.
Note
This method is an API call. For general usage, consider
stickersinstead.- Raises:
HTTPException – An error occurred fetching the stickers.
- Returns:
The retrieved stickers.
- Return type:
List[
GuildSticker]
- property filesize_limit: int¶
The maximum number of bytes files can have when uploaded to this guild.
- property forum_channels: list[ForumChannel]¶
A list of forum channels that belong to this guild.
Added in version 2.0.
This is sorted by the position and are in UI order from top to bottom.
- get_channel(channel_id, /)¶
Returns a channel with the given ID.
Note
This does not search for threads.
- Parameters:
channel_id (
int) – The ID to search for.- Returns:
The returned channel or
Noneif not found.- Return type:
Optional[
abc.GuildChannel]
- get_channel_or_thread(channel_id, /)¶
Returns a channel or thread with the given ID.
Added in version 2.0.
- Parameters:
channel_id (
int) – The ID to search for.- Returns:
The returned channel or thread or
Noneif not found.- Return type:
Optional[Union[
Thread,abc.GuildChannel]]
- await get_me()¶
Similar to
Client.userexcept an instance ofMember. This is essentially used to get the member version of yourself.- Return type:
- await get_member(user_id, /)¶
Returns a member with the given ID.
- Parameters:
user_id (
int) – The ID to search for.- Returns:
The member or
Noneif not found.- Return type:
Optional[
Member]
- get_member_named(name, /)¶
Returns the first member found that matches the name provided.
The name can have an optional discriminator argument, e.g. “Jake#0001” or “Jake” will both do the lookup. However, the former will give a more precise result. Note that the discriminator must have all 4 digits for this to work.
If a nickname is passed, then it is looked up via the nickname. Note however, that a nickname + discriminator combo will not look up the nickname but rather the username + discriminator combo due to nickname + discriminator not being unique.
If no member is found,
Noneis returned.- Parameters:
name (
str) – The name of the member to lookup with an optional discriminator.- Returns:
The member in this guild with the associated name. If not found then
Noneis returned.- Return type:
Optional[
Member]
- get_role(role_id, /)¶
Returns a role with the given ID.
- Parameters:
role_id (
int) – The ID to search for.- Returns:
The role or
Noneif not found.- Return type:
Optional[
Role]
- get_scheduled_event(event_id, /)¶
Returns a Scheduled Event with the given ID.
- Parameters:
event_id (
int) – The ID to search for.- Returns:
The scheduled event or
Noneif not found.- Return type:
Optional[
ScheduledEvent]
- get_sound(sound_id)¶
Returns a sound with the given ID.
Added in version 2.7.
- Parameters:
sound_id (
int) – The ID to search for.- Returns:
The sound or
Noneif not found.- Return type:
Optional[
SoundboardSound]
- get_stage_instance(stage_instance_id, /)¶
Returns a stage instance with the given ID.
Added in version 2.0.
- Parameters:
stage_instance_id (
int) – The ID to search for.- Returns:
The stage instance or
Noneif not found.- Return type:
Optional[
StageInstance]
- get_thread(thread_id, /)¶
Returns a thread with the given ID.
Added in version 2.0.
- Parameters:
thread_id (
int) – The ID to search for.- Returns:
The returned thread or
Noneif not found.- Return type:
Optional[
Thread]
- await integrations()¶
This function is a coroutine.
Returns a list of all integrations attached to the guild.
You must have the
manage_guildpermission to do this.Added in version 1.4.
- Returns:
The list of integrations that are attached to the guild.
- Return type:
List[
Integration]- Raises:
Forbidden – You do not have permission to create the integration.
HTTPException – Fetching the integrations failed.
- await invites()¶
This function is a coroutine.
Returns a list of all active instant invites from the guild.
You must have the
manage_guildpermission to get this information.- Returns:
The list of invites that are currently active.
- Return type:
List[
Invite]- Raises:
Forbidden – You do not have proper permissions to get the information.
HTTPException – An error occurred while fetching the information.
- await is_chunked()¶
Returns a boolean indicating if the guild is “chunked”.
A chunked guild means that
member_countis equal to the number of members stored in the internalmemberscache.If this value returns
False, then you should request for offline members.- Return type:
- await is_large()¶
Indicates if the guild is a ‘large’ guild.
A large guild is defined as having more than
large_thresholdcount members, which for this library is set to the maximum of 250.- Return type:
- property jump_url: str¶
Returns a URL that allows the client to jump to the guild.
Added in version 2.0.
- await kick(user, *, reason=None)¶
This function is a coroutine.
Kicks a user from the guild.
The user must meet the
abc.Snowflakeabc.You must have the
kick_memberspermission to do this.- Parameters:
user (
abc.Snowflake) – The user to kick from their guild.reason (Optional[
str]) – The reason the user got kicked.
- Raises:
Forbidden – You do not have the proper permissions to kick.
HTTPException – Kicking failed.
- Return type:
- await leave()¶
This function is a coroutine.
Leaves the guild. :rtype:
NoneNote
You cannot leave the guild that you own, you must delete it instead via
delete().- Raises:
HTTPException – Leaving the guild failed.
- property member_count: int¶
Returns the true member count regardless of it being loaded fully or not.
Warning
Due to a Discord limitation, in order for this attribute to remain up-to-date and accurate, it requires
Intents.membersto be specified.
- await modify_incident_actions(*, invites_disabled_until=Undefined.MISSING, dms_disabled_until=Undefined.MISSING, reason=Undefined.MISSING)¶
This function is a coroutine.
Modify the guild’s incident actions, controlling when invites or DMs are re-enabled after being temporarily disabled. Requires the
manage_guildpermission.- Parameters:
invites_disabled_until (Optional[
datetime.datetime]) – The ISO8601 timestamp indicating when invites will be enabled again, orNoneto enable invites immediately.dms_disabled_until (Optional[
datetime.datetime]) – The ISO8601 timestamp indicating when DMs will be enabled again, orNoneto enable DMs immediately.reason (Optional[
str]) – The reason for this action, used for the audit log.
- Returns:
The updated incidents data for the guild.
- Return type:
IncidentsData
- await onboarding()¶
This function is a coroutine.
Returns the
Onboardingflow for the guild.Added in version 2.5.
- Returns:
The onboarding flow for the guild.
- Return type:
Onboarding- Raises:
HTTPException – Retrieving the onboarding flow failed somehow.
Gets the premium subscriber role, AKA “boost” role, in this guild.
Added in version 1.6.
A list of members who have “boosted” this guild.
- await prune_members(*, days, compute_prune_count=True, roles=Undefined.MISSING, reason=None)¶
This function is a coroutine.
Prunes the guild from its inactive members.
The inactive members are denoted if they have not logged on in
daysnumber of days and have no roles.You must have the
kick_memberspermission to use this.To check how many members you would prune without actually pruning, see the
estimate_pruned_members()function.To prune members that have specific roles see the
rolesparameter.Changed in version 1.4: The
roleskeyword-only parameter was added.- Parameters:
days (
int) – The number of days before counting as inactive.reason (Optional[
str]) – The reason for doing this action. Shows up on the audit log.compute_prune_count (
bool) – Whether to compute the prune count. This defaults toTruewhich makes it prone to timeouts in very large guilds. In order to prevent timeouts, you must set this toFalse. If this is set toFalse, then this function will always returnNone.roles (List[
abc.Snowflake]) – A list ofabc.Snowflakethat represent roles to include in the pruning process. If a member has a role that is not specified, they’ll be excluded.
- Raises:
Forbidden – You do not have permissions to prune members.
HTTPException – An error occurred while pruning members.
InvalidArgument – An integer was not passed for
days.
- Returns:
The number of members pruned. If
compute_prune_countisFalsethen this returnsNone.- Return type:
Optional[
int]
- property public_updates_channel: TextChannel | None¶
Return’s the guild’s channel where admins and moderators of the guilds receive notices from Discord. The guild must be a Community guild.
If no channel is set, then this returns
None.Added in version 1.4.
- await query_members(query=None, *, limit=5, user_ids=None, presences=False, cache=True)¶
This function is a coroutine.
Request members that belong to this guild whose username starts with the query given.
This is a websocket operation and can be slow.
Added in version 1.3.
- Parameters:
query (Optional[
str]) – The string that the username’s start with.user_ids (Optional[List[
int]]) –List of user IDs to search for. If the user ID is not in the guild then it won’t be returned.
Added in version 1.4.
limit (Optional[
int]) – The maximum number of members to send back. If no query is passed, passingNonereturns all members. If aqueryoruser_idsis passed, must be between 1 and 100. Defaults to 5.presences (Optional[
bool]) –Whether to request for presences to be provided. This defaults to
False.Added in version 1.6.
cache (
bool) – Whether to cache the members internally. This makes operations such asget_member()work for those that matched. Defaults toTrue.
- Returns:
The list of members that have matched the query.
- Return type:
List[
Member]- Raises:
asyncio.TimeoutError – The query timed out waiting for the members.
ValueError – Invalid parameters were passed to the function
ClientException – The presences intent is not enabled.
- property roles: list[Role]¶
Returns a
listof the guild’s roles in hierarchy order.The first element of this list will be the lowest role in the hierarchy.
- property rules_channel: TextChannel | None¶
Return’s the guild’s channel used for the rules. The guild must be a Community guild.
If no channel is set, then this returns
None.Added in version 1.3.
- property scheduled_events: list[ScheduledEvent]¶
A list of scheduled events in this guild.
- await search_members(query, *, limit=1000)¶
Search for guild members whose usernames or nicknames start with the query string. Unlike
fetch_members(), this does not requireIntents.members().Note
This method is an API call. For general usage, consider filtering
membersinstead.Added in version 2.6.
- Parameters:
- Returns:
The list of members that have matched the query.
- Return type:
List[
Member]- Raises:
HTTPException – Getting the members failed.
- property self_role: Role | None¶
Gets the role associated with this client’s user, if any.
Added in version 1.6.
- await set_mfa_required(required, *, reason=None)¶
This function is a coroutine.
Set whether it is required to have MFA enabled on your account to perform moderation actions. You must be the guild owner to do this.
- Parameters:
- Raises:
HTTPException – The operation failed.
Forbidden – You are not the owner of the guild.
- Return type:
- property soundboard_limit: int¶
The maximum number of soundboard slots this guild has.
Added in version 2.7.
- property sounds: list[SoundboardSound]¶
A list of soundboard sounds that belong to this guild.
Added in version 2.7.
This is sorted by the position and are in UI order from top to bottom.
- property stage_channels: list[StageChannel]¶
A list of stage channels that belong to this guild.
Added in version 1.7.
This is sorted by the position and are in UI order from top to bottom.
- property stage_instances: list[StageInstance]¶
Returns a
listof the guild’s stage instances that are currently running.Added in version 2.0.
- property sticker_limit: int¶
The maximum number of sticker slots this guild has.
Added in version 2.0.
- property system_channel: TextChannel | None¶
Returns the guild’s channel used for system messages.
If no channel is set, then this returns
None.
- property system_channel_flags: SystemChannelFlags¶
Returns the guild’s system channel settings.
- await templates()¶
This function is a coroutine.
Gets the list of templates from this guild.
Requires
manage_guildpermissions.Added in version 1.7.
- Returns:
The templates for this guild.
- Return type:
List[
Template]- Raises:
Forbidden – You don’t have permissions to get the templates.
- property text_channels: list[TextChannel]¶
A list of text channels that belong to this guild.
This is sorted by the position and are in UI order from top to bottom.
- property threads: list[Thread]¶
A list of threads that you have permission to view.
Added in version 2.0.
- await unban(user, *, reason=None)¶
This function is a coroutine.
Unbans a user from the guild.
The user must meet the
abc.Snowflakeabc.You must have the
ban_memberspermission to do this.- Parameters:
user (
abc.Snowflake) – The user to unban.reason (Optional[
str]) – The reason for doing this action. Shows up on the audit log.
- Raises:
Forbidden – You do not have the proper permissions to unban.
HTTPException – Unbanning failed.
- Return type:
- await vanity_invite()¶
This function is a coroutine.
Returns the guild’s special vanity invite.
The guild must have
VANITY_URLinfeatures.You must have the
manage_guildpermission to use this as well.- Returns:
The special vanity invite. If
Nonethen the guild does not have a vanity invite set.- Return type:
Optional[
Invite]- Raises:
Forbidden – You do not have the proper permissions to get this.
HTTPException – Retrieving the vanity invite failed.
- property voice_channels: list[VoiceChannel]¶
A list of voice channels that belong to this guild.
This is sorted by the position and are in UI order from top to bottom.
- property voice_client: VoiceClient | None¶
Returns the
VoiceClientassociated with this guild, if any.
- await webhooks()¶
This function is a coroutine.
Gets the list of webhooks from this guild.
Requires
manage_webhookspermissions.- Returns:
The webhooks for this guild.
- Return type:
List[
Webhook]- Raises:
Forbidden – You don’t have permissions to get the webhooks.
- await welcome_screen()¶
This function is a coroutine.
Returns the
WelcomeScreenof the guild.The guild must have
COMMUNITYinfeatures.You must have the
manage_guildpermission in order to get this.Added in version 2.0.
- Returns:
The welcome screen of guild.
- Return type:
WelcomeScreen- Raises:
Forbidden – You do not have the proper permissions to get this.
HTTPException – Retrieving the welcome screen failed somehow.
NotFound – The guild doesn’t have a welcome screen or community feature is disabled.
- await widget()¶
This function is a coroutine.
Returns the widget of the guild.
Note
The guild must have the widget enabled to get this information.
- Returns:
The guild’s widget.
- Return type:
Widget- Raises:
Forbidden – The widget for this guild is disabled.
HTTPException – Retrieving the widget failed.
- class discord.events.GuildDelete[source]¶
Called when a guild is removed from the client.
This happens through, but not limited to, these circumstances: - The client got banned. - The client got kicked. - The client left the guild. - The client or the guild owner deleted the guild.
In order for this event to be invoked then the client must have been part of the guild to begin with (i.e., it is part of
Client.guilds).This requires
Intents.guildsto be enabled.This event inherits from
Guild.- old¶
The guild that was removed.
- Type:
Guild
- await active_threads()¶
This function is a coroutine.
Returns a list of active
Threadthat the client can access.This includes both private and public threads.
Added in version 2.0.
- Returns:
The active threads
- Return type:
List[
Thread]- Raises:
HTTPException – The request to get the active threads failed.
- await audit_logs(*, limit=100, before=None, after=None, user=None, action=None)¶
Returns an
AsyncIteratorthat enables receiving the guild’s audit logs.You must have the
view_audit_logpermission to use this.See API documentation for more information about the before and after parameters.
- Parameters:
limit (Optional[
int]) – The number of entries to retrieve. IfNoneretrieve all entries.before (Union[
abc.Snowflake,datetime.datetime]) – Retrieve entries before this date or entry. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.after (Union[
abc.Snowflake,datetime.datetime]) – Retrieve entries after this date or entry. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.user (
abc.Snowflake) – The moderator to filter entries from.action (
AuditLogAction) – The action to filter with.
- Yields:
AuditLogEntry– The audit log entry.- Raises:
Forbidden – You are not allowed to fetch audit logs
HTTPException – An error occurred while fetching the audit logs.
- Return type:
AuditLogIterator
Examples
Getting the first 100 entries:
async for entry in guild.audit_logs(limit=100): print(f"{entry.user} did {entry.action} to {await entry.get_target()}")
Getting entries for a specific action:
async for entry in guild.audit_logs(action=discord.AuditLogAction.ban): print(f"{entry.user} banned {await entry.get_target()}")
Getting entries made by a specific user:
entries = await guild.audit_logs(limit=None, user=guild.me).flatten() await channel.send(f"I made {len(entries)} moderation actions.")
- await ban(user, *, delete_message_seconds=None, reason=None)¶
This function is a coroutine.
Bans a user from the guild.
The user must meet the
abc.Snowflakeabc.You must have the
ban_memberspermission to do this.- Parameters:
user (
abc.Snowflake) – The user to ban from their guild.delete_message_seconds (Optional[
int]) – The number of seconds worth of messages to delete from the user in the guild. The minimum is 0 and the maximum is 604800 (i.e. 7 days). The default is 0.reason (Optional[
str]) – The reason the user got banned.
- Raises:
Forbidden – You do not have the proper permissions to ban.
HTTPException – Banning failed.
- Return type:
- bans(limit=None, before=None, after=None)¶
This function is a coroutine.
Retrieves an
AsyncIteratorthat enables receiving the guild’s bans. In order to use this, you must have theban_memberspermission. Users will always be returned in ascending order sorted by user ID. If both thebeforeandafterparameters are provided, only before is respected.Changed in version 2.5: The
before. andafterparameters were changed. They are now of the typeabc.Snowflakeinstead of SnowflakeTime to comply with the discord api.Changed in version 2.0: The
limit,before. andafterparameters were added. Now returns aBanIteratorinstead of a list ofBanEntryobjects.All parameters are optional.
- Parameters:
limit (Optional[
int]) – The number of bans to retrieve. Defaults to 1000.before (Optional[
abc.Snowflake]) – Retrieve bans before the given user.after (Optional[
abc.Snowflake]) – Retrieve bans after the given user.
- Yields:
BanEntry– The ban entry for the ban.- Raises:
Forbidden – You do not have proper permissions to get the information.
HTTPException – An error occurred while fetching the information.
- Return type:
BanIterator
Examples
Usage
async for ban in guild.bans(limit=150): print(ban.user.name)
Flattening into a list
bans = await guild.bans(limit=150).flatten() # bans is now a list of BanEntry...
- await bulk_ban(*users, delete_message_seconds=None, reason=None)¶
This function is a coroutine.
Bulk ban users from the guild.
The users must meet the
abc.Snowflakeabc.You must have the
ban_memberspermission to do this.Example Usage:
# Ban multiple users successes, failures = await guild.bulk_ban(user1, user2, user3, ..., reason="Raid") # Ban a list of users successes, failures = await guild.bulk_ban(*users)
- Parameters:
*users (
abc.Snowflake) – An argument list of users to ban from the guild, up to 200.delete_message_seconds (Optional[
int]) – The number of seconds worth of messages to delete from the user in the guild. The minimum is 0 and the maximum is 604800 (i.e. 7 days). The default is 0.reason (Optional[
str]) – The reason the users were banned.
- Returns:
Returns two lists: the first contains members that were successfully banned, while the second is members that could not be banned.
- Return type:
Tuple[List[
abc.Snowflake], List[abc.Snowflake]]- Raises:
ValueError – You tried to ban more than 200 users.
Forbidden – You do not have the proper permissions to ban.
HTTPException – No users were banned.
- by_category()¶
Returns every
CategoryChanneland their associated channels.These channels and categories are sorted in the official Discord UI order.
If the channels do not have a category, then the first element of the tuple is
None.- Returns:
The categories and their associated channels.
- Return type:
List[Tuple[Optional[
CategoryChannel], List[abc.GuildChannel]]]
- property categories: list[CategoryChannel]¶
A list of categories that belong to this guild.
This is sorted by the position and are in UI order from top to bottom.
- await change_voice_state(*, channel, self_mute=False, self_deaf=False)¶
This function is a coroutine.
Changes client’s voice state in the guild.
Added in version 1.4.
- await chunk(*, cache=True)¶
This function is a coroutine.
Requests all members that belong to this guild. In order to use this,
Intents.members()must be enabled.This is a websocket operation and can be slow.
Added in version 1.5.
- Parameters:
cache (
bool) – Whether to cache the members as well.- Raises:
ClientException – The members intent is not enabled.
- Return type:
- await create_auto_moderation_rule(*, name, event_type, trigger_type, trigger_metadata, actions, enabled=False, exempt_roles=None, exempt_channels=None, reason=None)¶
Creates an auto moderation rule.
- Parameters:
name (
str) – The name of the auto moderation rule.event_type (
AutoModEventType) – The type of event that triggers the rule.trigger_type (
AutoModTriggerType) – The rule’s trigger type.trigger_metadata (
AutoModTriggerMetadata) – The rule’s trigger metadata.actions (List[
AutoModAction]) – The actions to take when the rule is triggered.enabled (
bool) – Whether the rule is enabled.exempt_roles (List[
abc.Snowflake]) – A list of roles that are exempt from the rule.exempt_channels (List[
abc.Snowflake]) – A list of channels that are exempt from the rule.reason (Optional[
str]) – The reason for creating the rule. Shows up in the audit log.
- Returns:
The new auto moderation rule.
- Return type:
AutoModRule- Raises:
HTTPException – Creating the auto moderation rule failed.
Forbidden – You do not have the Manage Guild permission.
- await create_category(name, *, overwrites=Undefined.MISSING, reason=None, position=Undefined.MISSING)¶
This function is a coroutine.
Same as
create_text_channel()except makes aCategoryChannelinstead.Note
The
categoryparameter is not supported in this function since categories cannot have categories.- Returns:
The channel that was just created.
- Return type:
CategoryChannel- Raises:
Forbidden – You do not have the proper permissions to create this channel.
HTTPException – Creating the channel failed.
InvalidArgument – The permission overwrite information is not in proper form.
- Parameters:
- await create_category_channel(name, *, overwrites=Undefined.MISSING, reason=None, position=Undefined.MISSING)¶
This function is a coroutine.
Same as
create_text_channel()except makes aCategoryChannelinstead.Note
The
categoryparameter is not supported in this function since categories cannot have categories.- Returns:
The channel that was just created.
- Return type:
CategoryChannel- Raises:
Forbidden – You do not have the proper permissions to create this channel.
HTTPException – Creating the channel failed.
InvalidArgument – The permission overwrite information is not in proper form.
- Parameters:
- await create_custom_emoji(*, name, image, roles=Undefined.MISSING, reason=None)¶
This function is a coroutine.
Creates a custom
GuildEmojifor the guild.There is currently a limit of 50 static and animated emojis respectively per guild, unless the guild has the
MORE_EMOJIfeature which extends the limit to 200.You must have the
manage_emojispermission to do this.- Parameters:
name (
str) – The emoji name. Must be at least 2 characters.image (
bytes) – The bytes-like object representing the image data to use. Only JPG, PNG and GIF images are supported.roles (List[
Role]) – AlistofRoles that can use this emoji. Leave empty to make it available to everyone.reason (Optional[
str]) – The reason for creating this emoji. Shows up on the audit log.
- Raises:
Forbidden – You are not allowed to create emojis.
HTTPException – An error occurred creating an emoji.
- Returns:
The created emoji.
- Return type:
GuildEmoji
- await create_forum_channel(name, *, reason=None, category=None, position=Undefined.MISSING, topic=Undefined.MISSING, slowmode_delay=Undefined.MISSING, nsfw=Undefined.MISSING, overwrites=Undefined.MISSING, default_reaction_emoji=Undefined.MISSING, available_tags=Undefined.MISSING, default_sort_order=Undefined.MISSING, default_thread_slowmode_delay=Undefined.MISSING, default_auto_archive_duration=Undefined.MISSING)¶
This function is a coroutine.
Creates a
ForumChannelfor the guild.Note that you need the
manage_channelspermission to create the channel.The
overwritesparameter can be used to create a ‘secret’ channel upon creation. This parameter expects adictof overwrites with the target (either aMemberor aRole) as the key and aPermissionOverwriteas the value.Note
Creating a channel of a specified position will not update the position of other channels to follow suit. A follow-up call to
edit()will be required to update the position of the channel in the channel list.- Parameters:
name (
str) – The channel’s name.overwrites (Dict[Union[
Role,Member,Snowflake],PermissionOverwrite]) – The overwrites to apply to the channel. Useful for creating secret channels.category (Optional[
CategoryChannel]) – The category to place the newly created channel under. The permissions will be automatically synced to category if no overwrites are provided.position (
int) – The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0.topic (
str) – The new channel’s topic.slowmode_delay (
int) – Specifies the slowmode rate limit for user in this channel, in seconds. A value of0disables slowmode. The maximum value possible is21600.nsfw (
bool) – Whether the channel is marked as NSFW.reason (Optional[
str]) – The reason for creating this channel. Shows up on the audit log.default_reaction_emoji (Optional[
GuildEmoji|int|str]) –The default reaction emoji. Can be a unicode emoji or a custom emoji in the forms:
GuildEmoji, snowflake ID, string representation (eg. ‘<a:emoji_name:emoji_id>’).Added in version v2.5.
available_tags (List[
ForumTag]) –The set of tags that can be used in a forum channel.
Added in version 2.7.
default_sort_order (Optional[
SortOrder]) –The default sort order type used to order posts in this channel.
Added in version 2.7.
default_thread_slowmode_delay (Optional[
int]) –The initial slowmode delay to set on newly created threads in this channel.
Added in version 2.7.
default_auto_archive_duration (
int) –The default auto archive duration in minutes for threads created in this channel.
Added in version 2.7.
- Returns:
The channel that was just created.
- Return type:
ForumChannel- Raises:
Forbidden – You do not have the proper permissions to create this channel.
HTTPException – Creating the channel failed.
InvalidArgument – The argument is not in proper form.
Examples
Creating a basic channel:
channel = await guild.create_forum_channel("cool-channel")
Creating a “secret” channel:
overwrites = { guild.default_role: discord.PermissionOverwrite(read_messages=False), guild.me: discord.PermissionOverwrite(read_messages=True), } channel = await guild.create_forum_channel("secret", overwrites=overwrites)
- await create_integration(*, type, id)¶
This function is a coroutine.
Attaches an integration to the guild.
You must have the
manage_guildpermission to do this.Added in version 1.4.
- Parameters:
- Raises:
Forbidden – You do not have permission to create the integration.
HTTPException – The account could not be found.
- Return type:
- await create_role(*, name=Undefined.MISSING, permissions=Undefined.MISSING, color=Undefined.MISSING, colour=Undefined.MISSING, colors=Undefined.MISSING, colours=Undefined.MISSING, holographic=Undefined.MISSING, hoist=Undefined.MISSING, mentionable=Undefined.MISSING, reason=None, icon=Undefined.MISSING, unicode_emoji=Undefined.MISSING)¶
This function is a coroutine.
Creates a
Rolefor the guild.All fields are optional.
You must have the
manage_rolespermission to do this.Changed in version 1.6: Can now pass
inttocolourkeyword-only parameter.- Parameters:
name (
str) – The role name. Defaults to ‘new role’.permissions (
Permissions) – The permissions to have. Defaults to no permissions.colour (Union[
Colour,int]) – The colour for the role. Defaults toColour.default(). This is aliased tocoloras well.hoist (
bool) – Indicates if the role should be shown separately in the member list. Defaults toFalse.mentionable (
bool) – Indicates if the role should be mentionable by others. Defaults toFalse.reason (Optional[
str]) – The reason for creating this role. Shows up on the audit log.icon (Optional[
bytes]) – A bytes-like object representing the icon. Only PNG/JPEG/WebP is supported. If this argument is passed,unicode_emojiis set to None. Only available to guilds that containROLE_ICONSinGuild.features.unicode_emoji (Optional[
str]) – The role’s unicode emoji. If this argument is passed,iconis set to None. Only available to guilds that containROLE_ICONSinGuild.features.color (Colour | int | utils.Undefined)
colors (RoleColours | utils.Undefined)
colours (RoleColours | utils.Undefined)
holographic (bool | utils.Undefined)
- Returns:
The newly created role.
- Return type:
Role- Raises:
Forbidden – You do not have permissions to create the role.
HTTPException – Creating the role failed.
InvalidArgument – An invalid keyword argument was given.
- await create_scheduled_event(*, name, description=Undefined.MISSING, start_time, end_time=Undefined.MISSING, location, privacy_level=ScheduledEventPrivacyLevel.guild_only, reason=None, image=Undefined.MISSING)¶
This function is a coroutine. Creates a scheduled event.
- Parameters:
name (
str) – The name of the scheduled event.description (Optional[
str]) – The description of the scheduled event.start_time (
datetime.datetime) – A datetime object of when the scheduled event is supposed to start.end_time (Optional[
datetime.datetime]) – A datetime object of when the scheduled event is supposed to end.location (
ScheduledEventLocation) – The location of where the event is happening.privacy_level (
ScheduledEventPrivacyLevel) – The privacy level of the event. Currently, the only possible value isScheduledEventPrivacyLevel.guild_only, which is default, so there is no need to change this parameter.reason (Optional[
str]) – The reason to show in the audit log.image (Optional[
bytes]) – The cover image of the scheduled event
- Returns:
The created scheduled event.
- Return type:
Optional[
ScheduledEvent]- Raises:
Forbidden – You do not have the Manage Events permission.
HTTPException – The operation failed.
- await create_sound(name, sound, volume=1.0, emoji=None, reason=None)¶
This function is a coroutine. Creates a
SoundboardSoundin the guild. You must havePermissions.manage_expressionspermission to use this.Added in version 2.7.
- Parameters:
name (
str) – The name of the sound.sound (
bytes) – The bytes-like object representing the sound data. Only MP3 sound files that are less than 5.2 seconds long are supported.volume (
float) – The volume of the sound. Defaults to 1.0.emoji (Optional[Union[
PartialEmoji,GuildEmoji,str]]) – The emoji of the sound.reason (Optional[
str]) – The reason for creating this sound. Shows up on the audit log.
- Returns:
The created sound.
- Return type:
SoundboardSound- Raises:
HTTPException – Creating the sound failed.
Forbidden – You do not have permissions to create sounds.
- await create_stage_channel(name, *, topic, position=Undefined.MISSING, overwrites=Undefined.MISSING, category=None, reason=None, bitrate=Undefined.MISSING, user_limit=Undefined.MISSING, rtc_region=Undefined.MISSING, video_quality_mode=Undefined.MISSING, slowmode_delay=Undefined.MISSING, nsfw=Undefined.MISSING)¶
This function is a coroutine.
This is similar to
create_text_channel()except makes aStageChannelinstead.Added in version 1.7.
- Parameters:
name (
str) – The channel’s name.topic (
str) – The new channel’s topic.overwrites (Dict[Union[
Role,Member,Snowflake],PermissionOverwrite]) – The overwrites to apply to the channel. Useful for creating secret channels.category (Optional[
CategoryChannel]) – The category to place the newly created channel under. The permissions will be automatically synced to category if no overwrites are provided.position (
int) – The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0.reason (Optional[
str]) – The reason for creating this channel. Shows up on the audit log.bitrate (
int) –The channel’s preferred audio bitrate in bits per second.
Added in version 2.7.
user_limit (
int) –The channel’s limit for number of members that can be in a voice channel.
Added in version 2.7.
rtc_region (Optional[
VoiceRegion]) –The region for the voice channel’s voice communication. A value of
Noneindicates automatic voice region detection.Added in version 2.7.
video_quality_mode (
VideoQualityMode) –The camera video quality for the voice channel’s participants.
Added in version 2.7.
slowmode_delay (
int) –Specifies the slowmode rate limit for user in this channel, in seconds. A value of
0disables slowmode. The maximum value possible is21600.Added in version 2.7.
nsfw (
bool) –Whether the channel is marked as NSFW.
Added in version 2.7.
- Returns:
The channel that was just created.
- Return type:
StageChannel- Raises:
Forbidden – You do not have the proper permissions to create this channel.
HTTPException – Creating the channel failed.
InvalidArgument – The permission overwrite information is not in proper form.
- await create_sticker(*, name, description=None, emoji, file, reason=None)¶
This function is a coroutine.
Creates a
Stickerfor the guild.You must have
manage_emojis_and_stickerspermission to do this.Added in version 2.0.
- Parameters:
name (
str) – The sticker name. Must be 2 to 30 characters.description (Optional[
str]) – The sticker’s description. If used, must be 2 to 100 characters.emoji (
str) – The name of a unicode emoji that represents the sticker’s expression.file (
File) – The file of the sticker to upload.reason (
str) – The reason for creating this sticker. Shows up on the audit log.
- Returns:
The created sticker.
- Return type:
GuildSticker- Raises:
Forbidden – You are not allowed to create stickers.
HTTPException – An error occurred creating a sticker.
TypeError – The parameters for the sticker are not correctly formatted.
- await create_template(*, name, description=Undefined.MISSING)¶
This function is a coroutine.
Creates a template for the guild.
You must have the
manage_guildpermission to do this.Added in version 1.7.
- await create_test_entitlement(sku)¶
This function is a coroutine.
Creates a test entitlement for the guild.
- Parameters:
sku (
Snowflake) – The SKU to create a test entitlement for.- Returns:
The created entitlement.
- Return type:
Entitlement
- await create_text_channel(name, *, reason=None, category=None, position=Undefined.MISSING, topic=Undefined.MISSING, slowmode_delay=Undefined.MISSING, nsfw=Undefined.MISSING, overwrites=Undefined.MISSING, default_thread_slowmode_delay=Undefined.MISSING, default_auto_archive_duration=Undefined.MISSING)¶
This function is a coroutine.
Creates a
TextChannelfor the guild.Note that you need the
manage_channelspermission to create the channel.The
overwritesparameter can be used to create a ‘secret’ channel upon creation. This parameter expects adictof overwrites with the target (either aMemberor aRole) as the key and aPermissionOverwriteas the value.Note
Creating a channel of a specified position will not update the position of other channels to follow suit. A follow-up call to
edit()will be required to update the position of the channel in the channel list.- Parameters:
name (
str) – The channel’s name.overwrites (Dict[Union[
Role,Member,Snowflake],PermissionOverwrite]) – The overwrites to apply to the channel. Useful for creating secret channels.category (Optional[
CategoryChannel]) – The category to place the newly created channel under. The permissions will be automatically synced to category if no overwrites are provided.position (
int) – The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0.topic (
str) – The new channel’s topic.slowmode_delay (
int) – Specifies the slowmode rate limit for user in this channel, in seconds. A value of 0 disables slowmode. The maximum value possible is 21600.nsfw (
bool) – Whether the channel is marked as NSFW.reason (Optional[
str]) – The reason for creating this channel. Shows up on the audit log.default_thread_slowmode_delay (Optional[
int]) –The initial slowmode delay to set on newly created threads in this channel.
Added in version 2.7.
default_auto_archive_duration (
int) –The default auto archive duration in minutes for threads created in this channel.
Added in version 2.7.
- Returns:
The channel that was just created.
- Return type:
TextChannel- Raises:
Forbidden – You do not have the proper permissions to create this channel.
HTTPException – Creating the channel failed.
InvalidArgument – The permission overwrite information is not in proper form.
Examples
Creating a basic channel:
channel = await guild.create_text_channel("cool-channel")
Creating a “secret” channel:
overwrites = { guild.default_role: discord.PermissionOverwrite(read_messages=False), guild.me: discord.PermissionOverwrite(read_messages=True), } channel = await guild.create_text_channel("secret", overwrites=overwrites)
- await create_voice_channel(name, *, reason=None, category=None, position=Undefined.MISSING, bitrate=Undefined.MISSING, user_limit=Undefined.MISSING, rtc_region=Undefined.MISSING, video_quality_mode=Undefined.MISSING, overwrites=Undefined.MISSING, slowmode_delay=Undefined.MISSING, nsfw=Undefined.MISSING)¶
This function is a coroutine.
This is similar to
create_text_channel()except makes aVoiceChannelinstead.- Parameters:
name (
str) – The channel’s name.overwrites (Dict[Union[
Role,Member,Snowflake],PermissionOverwrite]) – The overwrites to apply to the channel. Useful for creating secret channels.category (Optional[
CategoryChannel]) – The category to place the newly created channel under. The permissions will be automatically synced to category if no overwrites are provided.position (
int) – The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0.bitrate (
int) – The channel’s preferred audio bitrate in bits per second.user_limit (
int) – The channel’s limit for number of members that can be in a voice channel.rtc_region (Optional[
VoiceRegion]) –The region for the voice channel’s voice communication. A value of
Noneindicates automatic voice region detection.Added in version 1.7.
video_quality_mode (
VideoQualityMode) –The camera video quality for the voice channel’s participants.
Added in version 2.0.
reason (Optional[
str]) – The reason for creating this channel. Shows up on the audit log.slowmode_delay (
int) –Specifies the slowmode rate limit for user in this channel, in seconds. A value of
0disables slowmode. The maximum value possible is21600.Added in version 2.7.
nsfw (
bool) –Whether the channel is marked as NSFW.
Added in version 2.7.
- Returns:
The channel that was just created.
- Return type:
VoiceChannel- Raises:
Forbidden – You do not have the proper permissions to create this channel.
HTTPException – Creating the channel failed.
InvalidArgument – The permission overwrite information is not in proper form.
- await delete()¶
This function is a coroutine.
Deletes the guild. You must be the guild owner to delete the guild.
- Raises:
HTTPException – Deleting the guild failed.
Forbidden – You do not have permissions to delete the guild.
- Return type:
- await delete_auto_moderation_rule(id, *, reason=None)¶
Deletes an auto moderation rule.
- Parameters:
- Raises:
HTTPException – Deleting the auto moderation rule failed.
Forbidden – You do not have the Manage Guild permission.
- Return type:
- await delete_emoji(emoji, *, reason=None)¶
This function is a coroutine.
Deletes the custom
GuildEmojifrom the guild.You must have
manage_emojispermission to do this.- Parameters:
emoji (
abc.Snowflake) – The emoji you are deleting.reason (Optional[
str]) – The reason for deleting this emoji. Shows up on the audit log.
- Raises:
Forbidden – You are not allowed to delete emojis.
HTTPException – An error occurred deleting the emoji.
- Return type:
- await delete_sticker(sticker, *, reason=None)¶
This function is a coroutine.
Deletes the custom
Stickerfrom the guild.You must have
manage_emojis_and_stickerspermission to do this.Added in version 2.0.
- Parameters:
sticker (
abc.Snowflake) – The sticker you are deleting.reason (Optional[
str]) – The reason for deleting this sticker. Shows up on the audit log.
- Raises:
Forbidden – You are not allowed to delete stickers.
HTTPException – An error occurred deleting the sticker.
- Return type:
- await edit(*, reason=Undefined.MISSING, name=Undefined.MISSING, description=Undefined.MISSING, icon=Undefined.MISSING, banner=Undefined.MISSING, splash=Undefined.MISSING, discovery_splash=Undefined.MISSING, community=Undefined.MISSING, afk_channel=Undefined.MISSING, owner=Undefined.MISSING, afk_timeout=Undefined.MISSING, default_notifications=Undefined.MISSING, verification_level=Undefined.MISSING, explicit_content_filter=Undefined.MISSING, system_channel=Undefined.MISSING, system_channel_flags=Undefined.MISSING, preferred_locale=Undefined.MISSING, rules_channel=Undefined.MISSING, public_updates_channel=Undefined.MISSING, premium_progress_bar_enabled=Undefined.MISSING, disable_invites=Undefined.MISSING, discoverable=Undefined.MISSING, disable_raid_alerts=Undefined.MISSING, enable_activity_feed=Undefined.MISSING)¶
This function is a coroutine.
Edits the guild.
You must have the
manage_guildpermission to edit the guild.Changed in version 1.4: The rules_channel and public_updates_channel keyword-only parameters were added.
Changed in version 2.0: The discovery_splash and community keyword-only parameters were added.
Changed in version 2.0: The newly updated guild is returned.
- Parameters:
name (
str) – The new name of the guild.description (Optional[
str]) – The new description of the guild. Could beNonefor no description. This is only available to guilds that containPUBLICinGuild.features.icon (
bytes) – A bytes-like object representing the icon. Only PNG/JPEG is supported. GIF is only available to guilds that containANIMATED_ICONinGuild.features. Could beNoneto denote removal of the icon.banner (
bytes) – A bytes-like object representing the banner. Could beNoneto denote removal of the banner. This is only available to guilds that containBANNERinGuild.features.splash (
bytes) – A bytes-like object representing the invite splash. Only PNG/JPEG supported. Could beNoneto denote removing the splash. This is only available to guilds that containINVITE_SPLASHinGuild.features.discovery_splash (
bytes) – A bytes-like object representing the discovery splash. Only PNG/JPEG supported. Could beNoneto denote removing the splash. This is only available to guilds that containDISCOVERABLEinGuild.features.community (
bool) – Whether the guild should be a Community guild. If set toTrue, bothrules_channelandpublic_updates_channelparameters are required.afk_channel (Optional[
VoiceChannel]) – The new channel that is the AFK channel. Could beNonefor no AFK channel.afk_timeout (
int) – The number of seconds until someone is moved to the AFK channel.owner (
Member) – The new owner of the guild to transfer ownership to. Note that you must be owner of the guild to do this.verification_level (
VerificationLevel) – The new verification level for the guild.default_notifications (
NotificationLevel) – The new default notification level for the guild.explicit_content_filter (
ContentFilter) – The new explicit content filter for the guild.system_channel (Optional[
TextChannel]) – The new channel that is used for the system channel. Could beNonefor no system channel.system_channel_flags (
SystemChannelFlags) – The new system channel settings to use with the new system channel.preferred_locale (
str) – The new preferred locale for the guild. Used as the primary language in the guild. If set, this must be an ISO 639 code, e.g.en-USorjaorzh-CN.rules_channel (Optional[
TextChannel]) – The new channel that is used for rules. This is only available to guilds that containPUBLICinGuild.features. Could beNonefor no rules channel.public_updates_channel (Optional[
TextChannel]) – The new channel that is used for public updates from Discord. This is only available to guilds that containPUBLICinGuild.features. Could beNonefor no public updates channel.premium_progress_bar_enabled (
bool) – Whether the guild should have premium progress bar enabled.disable_invites (
bool) – Whether the guild should have server invites enabled or disabled.discoverable (
bool) – Whether the guild should be discoverable in the discover tab.disable_raid_alerts (
bool) – Whether activity alerts for the guild should be disabled.enable_activity_feed (class:bool) – Whether the guild’s user activity feed should be enabled.
reason (Optional[
str]) – The reason for editing this guild. Shows up on the audit log.
- Raises:
Forbidden – You do not have permissions to edit the guild.
HTTPException – Editing the guild failed.
InvalidArgument – The image format passed in to
iconis invalid. It must be PNG or JPG. This is also raised if you are not the owner of the guild and request an ownership transfer.
- Returns:
The newly updated guild. Note that this has the same limitations as mentioned in
Client.fetch_guild()and may not have full data.- Return type:
Guild
- await edit_onboarding(*, prompts=Undefined.MISSING, default_channels=Undefined.MISSING, enabled=Undefined.MISSING, mode=Undefined.MISSING, reason=Undefined.MISSING)¶
This function is a coroutine.
A shorthand for
Onboarding.editwithout fetching the onboarding flow.You must have the
manage_guildandmanage_rolespermissions in the guild to do this.- Parameters:
prompts (Optional[List[
OnboardingPrompt]]) – The new list of prompts for this flow.default_channels (Optional[List[
Snowflake]]) – The new default channels that users are opted into.enabled (Optional[
bool]) – Whether onboarding should be enabled. Setting this toTruerequires the guild to haveCOMMUNITYinfeaturesand at least 7default_channels.mode (Optional[
OnboardingMode]) – The new onboarding mode.reason (Optional[
str]) – The reason that shows up on Audit log.
- Returns:
The updated onboarding flow.
- Return type:
Onboarding- Raises:
HTTPException – Editing the onboarding flow failed somehow.
Forbidden – You don’t have permissions to edit the onboarding flow.
- await edit_role_positions(positions, *, reason=None)¶
This function is a coroutine.
Bulk edits a list of
Rolein the guild.You must have the
manage_rolespermission to do this.Added in version 1.4.
Example:
positions = { bots_role: 1, # penultimate role tester_role: 2, admin_role: 6, } await guild.edit_role_positions(positions=positions)
- Parameters:
- Returns:
A list of all the roles in the guild.
- Return type:
List[
Role]- Raises:
Forbidden – You do not have permissions to move the roles.
HTTPException – Moving the roles failed.
InvalidArgument – An invalid keyword argument was given.
- await edit_welcome_screen(**options)¶
This function is a coroutine.
A shorthand for
WelcomeScreen.editwithout fetching the welcome screen.You must have the
manage_guildpermission in the guild to do this.The guild must have
COMMUNITYinGuild.features- Parameters:
description (Optional[
str]) – The new description of welcome screen.welcome_channels (Optional[List[
WelcomeScreenChannel]]) – The welcome channels. The order of the channels would be same as the passed list order.enabled (Optional[
bool]) – Whether the welcome screen should be displayed.reason (Optional[
str]) – The reason that shows up on audit log.
- Returns:
The edited welcome screen.
- Return type:
WelcomeScreen- Raises:
HTTPException – Editing the welcome screen failed somehow.
Forbidden – You don’t have permissions to edit the welcome screen.
NotFound – This welcome screen does not exist.
- await edit_widget(*, enabled=Undefined.MISSING, channel=Undefined.MISSING)¶
This function is a coroutine.
Edits the widget of the guild.
You must have the
manage_guildpermission to use thisAdded in version 2.0.
- Parameters:
- Raises:
Forbidden – You do not have permission to edit the widget.
HTTPException – Editing the widget failed.
- Return type:
- entitlements(skus=None, before=None, after=None, limit=100, exclude_ended=False)¶
Returns an
AsyncIteratorthat enables fetching the guild’s entitlements.This is identical to
Client.entitlements()with theguildparameter.Added in version 2.6.
- Parameters:
skus (list[
abc.Snowflake] | None) – Limit the fetched entitlements to entitlements that are for these SKUs.before (
abc.Snowflake|datetime.datetime| None) – Retrieves guilds before this date or object. If a datetime is provided, it is recommended to use a UTC-aware datetime. If the datetime is naive, it is assumed to be local time.after (
abc.Snowflake|datetime.datetime| None) – Retrieve guilds after this date or object. If a datetime is provided, it is recommended to use a UTC-aware datetime. If the datetime is naive, it is assumed to be local time.limit (Optional[
int]) – The number of entitlements to retrieve. IfNone, retrieves every entitlement, which may be slow. Defaults to100.exclude_ended (
bool) – Whether to limit the fetched entitlements to those that have not ended. Defaults toFalse.
- Yields:
Entitlement– The application’s entitlements.- Raises:
HTTPException – Retrieving the entitlements failed.
- Return type:
EntitlementIterator
- await estimate_pruned_members(*, days, roles=Undefined.MISSING)¶
This function is a coroutine.
Similar to
prune_members()except instead of actually pruning members, it returns how many members it would prune from the guild had it been called.- Parameters:
days (
int) – The number of days before counting as inactive.roles (List[
abc.Snowflake]) –A list of
abc.Snowflakethat represent roles to include in the estimate. If a member has a role that is not specified, they’ll be excluded.Added in version 1.7.
- Returns:
The number of members estimated to be pruned.
- Return type:
- Raises:
Forbidden – You do not have permissions to prune members.
HTTPException – An error occurred while fetching the prune members estimate.
InvalidArgument – An integer was not passed for
days.
- await fetch_auto_moderation_rule(id)¶
This function is a coroutine.
Retrieves a
AutoModRulefrom rule ID.- Returns:
The requested auto moderation rule.
- Return type:
AutoModRule- Raises:
HTTPException – Getting the auto moderation rule failed.
Forbidden – You do not have the Manage Guild permission.
- Parameters:
id (
int)
- await fetch_auto_moderation_rules()¶
This function is a coroutine.
Retrieves a list of auto moderation rules for this guild.
- Returns:
The auto moderation rules for this guild.
- Return type:
List[
AutoModRule]- Raises:
HTTPException – Getting the auto moderation rules failed.
Forbidden – You do not have the Manage Guild permission.
- await fetch_ban(user)¶
This function is a coroutine.
Retrieves the
BanEntryfor a user.You must have the
ban_memberspermission to get this information.- Parameters:
user (
abc.Snowflake) – The user to get ban information from.- Returns:
The
BanEntryobject for the specified user.- Return type:
BanEntry- Raises:
Forbidden – You do not have proper permissions to get the information.
NotFound – This user is not banned.
HTTPException – An error occurred while fetching the information.
- await fetch_channel(channel_id, /)¶
This function is a coroutine.
Retrieves a
abc.GuildChannelorThreadwith the specified ID.Note
This method is an API call. For general usage, consider
get_channel_or_thread()instead.Added in version 2.0.
- Returns:
The channel from the ID.
- Return type:
Union[
abc.GuildChannel,Thread]- Raises:
InvalidData – An unknown channel type was received from Discord or the guild the channel belongs to is not the same as the one in this object points to.
HTTPException – Retrieving the channel failed.
NotFound – Invalid Channel ID.
Forbidden – You do not have permission to fetch this channel.
- Parameters:
channel_id (
int)
- await fetch_channels()¶
This function is a coroutine.
Retrieves all
abc.GuildChannelthat the guild has.Note
This method is an API call. For general usage, consider
channelsinstead.Added in version 1.2.
- Returns:
All channels in the guild.
- Return type:
Sequence[
discord.channel.base.GuildChannel]- Raises:
InvalidData – An unknown channel type was received from Discord.
HTTPException – Retrieving the channels failed.
- await fetch_emoji(emoji_id, /)¶
This function is a coroutine.
Retrieves a custom
GuildEmojifrom the guild.Note
This method is an API call. For general usage, consider iterating over
emojisinstead.- Parameters:
emoji_id (
int) – The emoji’s ID.- Returns:
The retrieved emoji.
- Return type:
GuildEmoji- Raises:
NotFound – The emoji requested could not be found.
HTTPException – An error occurred fetching the emoji.
- await fetch_emojis()¶
This function is a coroutine.
Retrieves all custom
GuildEmojis from the guild.Note
This method is an API call. For general usage, consider
emojisinstead.- Raises:
HTTPException – An error occurred fetching the emojis.
- Returns:
The retrieved emojis.
- Return type:
List[
GuildEmoji]
- await fetch_member(member_id, /)¶
This function is a coroutine.
Retrieves a
Memberfrom a guild ID, and a member ID.Note
This method is an API call. If you have
Intents.membersand member cache enabled, considerget_member()instead.- Parameters:
member_id (
int) – The member’s ID to fetch from.- Returns:
The member from the member ID.
- Return type:
Member- Raises:
Forbidden – You do not have access to the guild.
HTTPException – Fetching the member failed.
- fetch_members(*, limit=1000, after=None)¶
Retrieves an
AsyncIteratorthat enables receiving the guild’s members. In order to use this,Intents.members()must be enabled.Note
This method is an API call. For general usage, consider
membersinstead.Added in version 1.3.
All parameters are optional.
- Parameters:
limit (Optional[
int]) – The number of members to retrieve. Defaults to 1000. PassNoneto fetch all members. Note that this is potentially slow.after (Optional[Union[
abc.Snowflake,datetime.datetime]]) – Retrieve members after this date or object. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.
- Yields:
Member– The member with the member data parsed.- Raises:
ClientException – The members intent is not enabled.
HTTPException – Getting the members failed.
- Return type:
MemberIterator
Examples
Usage
async for member in guild.fetch_members(limit=150): print(member.name)
Flattening into a list
members = await guild.fetch_members(limit=150).flatten() # members is now a list of Member...
- await fetch_role(role_id)¶
This function is a coroutine.
Retrieves a
Rolethat the guild has.Note
This method is an API call. For general usage, consider using
get_roleinstead.Added in version 2.7.
- Returns:
The role in the guild with the specified ID.
- Return type:
Role- Raises:
HTTPException – Retrieving the role failed.
- Parameters:
role_id (
int)
- await fetch_roles()¶
This function is a coroutine.
Retrieves all
Rolethat the guild has.Note
This method is an API call. For general usage, consider
rolesinstead.Added in version 1.3.
- Returns:
All roles in the guild.
- Return type:
List[
Role]- Raises:
HTTPException – Retrieving the roles failed.
- await fetch_scheduled_event(event_id, /, *, with_user_count=True)¶
This function is a coroutine.
Retrieves a
ScheduledEventfrom event ID.Note
This method is an API call. If you have
Intents.scheduled_events, considerget_scheduled_event()instead.- Parameters:
- Returns:
The scheduled event from the event ID.
- Return type:
Optional[
ScheduledEvent]- Raises:
HTTPException – Fetching the event failed.
NotFound – Event not found.
- await fetch_scheduled_events(*, with_user_count=True)¶
This function is a coroutine.
Returns a list of
ScheduledEventin the guild.Note
This method is an API call. For general usage, consider
scheduled_eventsinstead.- Parameters:
with_user_count (Optional[
bool]) – If the scheduled event should be fetched with the number of users that are interested in the events. Defaults toTrue.- Returns:
The fetched scheduled events.
- Return type:
List[
ScheduledEvent]- Raises:
ClientException – The scheduled events intent is not enabled.
HTTPException – Getting the scheduled events failed.
- await fetch_sound(sound_id)¶
This function is a coroutine. Fetches a soundboard sound in the guild.
Added in version 2.7.
- Parameters:
sound_id (
int) – The ID of the sound.- Returns:
The sound.
- Return type:
SoundboardSound
- await fetch_sounds()¶
This function is a coroutine. Fetches all the soundboard sounds in the guild.
Added in version 2.7.
- Returns:
The sounds in the guild.
- Return type:
List[
SoundboardSound]
- await fetch_sticker(sticker_id, /)¶
This function is a coroutine.
Retrieves a custom
Stickerfrom the guild.Added in version 2.0.
Note
This method is an API call. For general usage, consider iterating over
stickersinstead.- Parameters:
sticker_id (
int) – The sticker’s ID.- Returns:
The retrieved sticker.
- Return type:
GuildSticker- Raises:
NotFound – The sticker requested could not be found.
HTTPException – An error occurred fetching the sticker.
- await fetch_stickers()¶
This function is a coroutine.
Retrieves a list of all
Stickers for the guild.Added in version 2.0.
Note
This method is an API call. For general usage, consider
stickersinstead.- Raises:
HTTPException – An error occurred fetching the stickers.
- Returns:
The retrieved stickers.
- Return type:
List[
GuildSticker]
- property filesize_limit: int¶
The maximum number of bytes files can have when uploaded to this guild.
- property forum_channels: list[ForumChannel]¶
A list of forum channels that belong to this guild.
Added in version 2.0.
This is sorted by the position and are in UI order from top to bottom.
- get_channel(channel_id, /)¶
Returns a channel with the given ID.
Note
This does not search for threads.
- Parameters:
channel_id (
int) – The ID to search for.- Returns:
The returned channel or
Noneif not found.- Return type:
Optional[
abc.GuildChannel]
- get_channel_or_thread(channel_id, /)¶
Returns a channel or thread with the given ID.
Added in version 2.0.
- Parameters:
channel_id (
int) – The ID to search for.- Returns:
The returned channel or thread or
Noneif not found.- Return type:
Optional[Union[
Thread,abc.GuildChannel]]
- await get_me()¶
Similar to
Client.userexcept an instance ofMember. This is essentially used to get the member version of yourself.- Return type:
- await get_member(user_id, /)¶
Returns a member with the given ID.
- Parameters:
user_id (
int) – The ID to search for.- Returns:
The member or
Noneif not found.- Return type:
Optional[
Member]
- get_member_named(name, /)¶
Returns the first member found that matches the name provided.
The name can have an optional discriminator argument, e.g. “Jake#0001” or “Jake” will both do the lookup. However, the former will give a more precise result. Note that the discriminator must have all 4 digits for this to work.
If a nickname is passed, then it is looked up via the nickname. Note however, that a nickname + discriminator combo will not look up the nickname but rather the username + discriminator combo due to nickname + discriminator not being unique.
If no member is found,
Noneis returned.- Parameters:
name (
str) – The name of the member to lookup with an optional discriminator.- Returns:
The member in this guild with the associated name. If not found then
Noneis returned.- Return type:
Optional[
Member]
- get_role(role_id, /)¶
Returns a role with the given ID.
- Parameters:
role_id (
int) – The ID to search for.- Returns:
The role or
Noneif not found.- Return type:
Optional[
Role]
- get_scheduled_event(event_id, /)¶
Returns a Scheduled Event with the given ID.
- Parameters:
event_id (
int) – The ID to search for.- Returns:
The scheduled event or
Noneif not found.- Return type:
Optional[
ScheduledEvent]
- get_sound(sound_id)¶
Returns a sound with the given ID.
Added in version 2.7.
- Parameters:
sound_id (
int) – The ID to search for.- Returns:
The sound or
Noneif not found.- Return type:
Optional[
SoundboardSound]
- get_stage_instance(stage_instance_id, /)¶
Returns a stage instance with the given ID.
Added in version 2.0.
- Parameters:
stage_instance_id (
int) – The ID to search for.- Returns:
The stage instance or
Noneif not found.- Return type:
Optional[
StageInstance]
- get_thread(thread_id, /)¶
Returns a thread with the given ID.
Added in version 2.0.
- Parameters:
thread_id (
int) – The ID to search for.- Returns:
The returned thread or
Noneif not found.- Return type:
Optional[
Thread]
- await integrations()¶
This function is a coroutine.
Returns a list of all integrations attached to the guild.
You must have the
manage_guildpermission to do this.Added in version 1.4.
- Returns:
The list of integrations that are attached to the guild.
- Return type:
List[
Integration]- Raises:
Forbidden – You do not have permission to create the integration.
HTTPException – Fetching the integrations failed.
- await invites()¶
This function is a coroutine.
Returns a list of all active instant invites from the guild.
You must have the
manage_guildpermission to get this information.- Returns:
The list of invites that are currently active.
- Return type:
List[
Invite]- Raises:
Forbidden – You do not have proper permissions to get the information.
HTTPException – An error occurred while fetching the information.
- await is_chunked()¶
Returns a boolean indicating if the guild is “chunked”.
A chunked guild means that
member_countis equal to the number of members stored in the internalmemberscache.If this value returns
False, then you should request for offline members.- Return type:
- await is_large()¶
Indicates if the guild is a ‘large’ guild.
A large guild is defined as having more than
large_thresholdcount members, which for this library is set to the maximum of 250.- Return type:
- property jump_url: str¶
Returns a URL that allows the client to jump to the guild.
Added in version 2.0.
- await kick(user, *, reason=None)¶
This function is a coroutine.
Kicks a user from the guild.
The user must meet the
abc.Snowflakeabc.You must have the
kick_memberspermission to do this.- Parameters:
user (
abc.Snowflake) – The user to kick from their guild.reason (Optional[
str]) – The reason the user got kicked.
- Raises:
Forbidden – You do not have the proper permissions to kick.
HTTPException – Kicking failed.
- Return type:
- await leave()¶
This function is a coroutine.
Leaves the guild. :rtype:
NoneNote
You cannot leave the guild that you own, you must delete it instead via
delete().- Raises:
HTTPException – Leaving the guild failed.
- property member_count: int¶
Returns the true member count regardless of it being loaded fully or not.
Warning
Due to a Discord limitation, in order for this attribute to remain up-to-date and accurate, it requires
Intents.membersto be specified.
- await modify_incident_actions(*, invites_disabled_until=Undefined.MISSING, dms_disabled_until=Undefined.MISSING, reason=Undefined.MISSING)¶
This function is a coroutine.
Modify the guild’s incident actions, controlling when invites or DMs are re-enabled after being temporarily disabled. Requires the
manage_guildpermission.- Parameters:
invites_disabled_until (Optional[
datetime.datetime]) – The ISO8601 timestamp indicating when invites will be enabled again, orNoneto enable invites immediately.dms_disabled_until (Optional[
datetime.datetime]) – The ISO8601 timestamp indicating when DMs will be enabled again, orNoneto enable DMs immediately.reason (Optional[
str]) – The reason for this action, used for the audit log.
- Returns:
The updated incidents data for the guild.
- Return type:
IncidentsData
- await onboarding()¶
This function is a coroutine.
Returns the
Onboardingflow for the guild.Added in version 2.5.
- Returns:
The onboarding flow for the guild.
- Return type:
Onboarding- Raises:
HTTPException – Retrieving the onboarding flow failed somehow.
Gets the premium subscriber role, AKA “boost” role, in this guild.
Added in version 1.6.
A list of members who have “boosted” this guild.
- await prune_members(*, days, compute_prune_count=True, roles=Undefined.MISSING, reason=None)¶
This function is a coroutine.
Prunes the guild from its inactive members.
The inactive members are denoted if they have not logged on in
daysnumber of days and have no roles.You must have the
kick_memberspermission to use this.To check how many members you would prune without actually pruning, see the
estimate_pruned_members()function.To prune members that have specific roles see the
rolesparameter.Changed in version 1.4: The
roleskeyword-only parameter was added.- Parameters:
days (
int) – The number of days before counting as inactive.reason (Optional[
str]) – The reason for doing this action. Shows up on the audit log.compute_prune_count (
bool) – Whether to compute the prune count. This defaults toTruewhich makes it prone to timeouts in very large guilds. In order to prevent timeouts, you must set this toFalse. If this is set toFalse, then this function will always returnNone.roles (List[
abc.Snowflake]) – A list ofabc.Snowflakethat represent roles to include in the pruning process. If a member has a role that is not specified, they’ll be excluded.
- Raises:
Forbidden – You do not have permissions to prune members.
HTTPException – An error occurred while pruning members.
InvalidArgument – An integer was not passed for
days.
- Returns:
The number of members pruned. If
compute_prune_countisFalsethen this returnsNone.- Return type:
Optional[
int]
- property public_updates_channel: TextChannel | None¶
Return’s the guild’s channel where admins and moderators of the guilds receive notices from Discord. The guild must be a Community guild.
If no channel is set, then this returns
None.Added in version 1.4.
- await query_members(query=None, *, limit=5, user_ids=None, presences=False, cache=True)¶
This function is a coroutine.
Request members that belong to this guild whose username starts with the query given.
This is a websocket operation and can be slow.
Added in version 1.3.
- Parameters:
query (Optional[
str]) – The string that the username’s start with.user_ids (Optional[List[
int]]) –List of user IDs to search for. If the user ID is not in the guild then it won’t be returned.
Added in version 1.4.
limit (Optional[
int]) – The maximum number of members to send back. If no query is passed, passingNonereturns all members. If aqueryoruser_idsis passed, must be between 1 and 100. Defaults to 5.presences (Optional[
bool]) –Whether to request for presences to be provided. This defaults to
False.Added in version 1.6.
cache (
bool) – Whether to cache the members internally. This makes operations such asget_member()work for those that matched. Defaults toTrue.
- Returns:
The list of members that have matched the query.
- Return type:
List[
Member]- Raises:
asyncio.TimeoutError – The query timed out waiting for the members.
ValueError – Invalid parameters were passed to the function
ClientException – The presences intent is not enabled.
- property roles: list[Role]¶
Returns a
listof the guild’s roles in hierarchy order.The first element of this list will be the lowest role in the hierarchy.
- property rules_channel: TextChannel | None¶
Return’s the guild’s channel used for the rules. The guild must be a Community guild.
If no channel is set, then this returns
None.Added in version 1.3.
- property scheduled_events: list[ScheduledEvent]¶
A list of scheduled events in this guild.
- await search_members(query, *, limit=1000)¶
Search for guild members whose usernames or nicknames start with the query string. Unlike
fetch_members(), this does not requireIntents.members().Note
This method is an API call. For general usage, consider filtering
membersinstead.Added in version 2.6.
- Parameters:
- Returns:
The list of members that have matched the query.
- Return type:
List[
Member]- Raises:
HTTPException – Getting the members failed.
- property self_role: Role | None¶
Gets the role associated with this client’s user, if any.
Added in version 1.6.
- await set_mfa_required(required, *, reason=None)¶
This function is a coroutine.
Set whether it is required to have MFA enabled on your account to perform moderation actions. You must be the guild owner to do this.
- Parameters:
- Raises:
HTTPException – The operation failed.
Forbidden – You are not the owner of the guild.
- Return type:
- property soundboard_limit: int¶
The maximum number of soundboard slots this guild has.
Added in version 2.7.
- property sounds: list[SoundboardSound]¶
A list of soundboard sounds that belong to this guild.
Added in version 2.7.
This is sorted by the position and are in UI order from top to bottom.
- property stage_channels: list[StageChannel]¶
A list of stage channels that belong to this guild.
Added in version 1.7.
This is sorted by the position and are in UI order from top to bottom.
- property stage_instances: list[StageInstance]¶
Returns a
listof the guild’s stage instances that are currently running.Added in version 2.0.
- property sticker_limit: int¶
The maximum number of sticker slots this guild has.
Added in version 2.0.
- property system_channel: TextChannel | None¶
Returns the guild’s channel used for system messages.
If no channel is set, then this returns
None.
- property system_channel_flags: SystemChannelFlags¶
Returns the guild’s system channel settings.
- await templates()¶
This function is a coroutine.
Gets the list of templates from this guild.
Requires
manage_guildpermissions.Added in version 1.7.
- Returns:
The templates for this guild.
- Return type:
List[
Template]- Raises:
Forbidden – You don’t have permissions to get the templates.
- property text_channels: list[TextChannel]¶
A list of text channels that belong to this guild.
This is sorted by the position and are in UI order from top to bottom.
- property threads: list[Thread]¶
A list of threads that you have permission to view.
Added in version 2.0.
- await unban(user, *, reason=None)¶
This function is a coroutine.
Unbans a user from the guild.
The user must meet the
abc.Snowflakeabc.You must have the
ban_memberspermission to do this.- Parameters:
user (
abc.Snowflake) – The user to unban.reason (Optional[
str]) – The reason for doing this action. Shows up on the audit log.
- Raises:
Forbidden – You do not have the proper permissions to unban.
HTTPException – Unbanning failed.
- Return type:
- await vanity_invite()¶
This function is a coroutine.
Returns the guild’s special vanity invite.
The guild must have
VANITY_URLinfeatures.You must have the
manage_guildpermission to use this as well.- Returns:
The special vanity invite. If
Nonethen the guild does not have a vanity invite set.- Return type:
Optional[
Invite]- Raises:
Forbidden – You do not have the proper permissions to get this.
HTTPException – Retrieving the vanity invite failed.
- property voice_channels: list[VoiceChannel]¶
A list of voice channels that belong to this guild.
This is sorted by the position and are in UI order from top to bottom.
- property voice_client: VoiceClient | None¶
Returns the
VoiceClientassociated with this guild, if any.
- await webhooks()¶
This function is a coroutine.
Gets the list of webhooks from this guild.
Requires
manage_webhookspermissions.- Returns:
The webhooks for this guild.
- Return type:
List[
Webhook]- Raises:
Forbidden – You don’t have permissions to get the webhooks.
- await welcome_screen()¶
This function is a coroutine.
Returns the
WelcomeScreenof the guild.The guild must have
COMMUNITYinfeatures.You must have the
manage_guildpermission in order to get this.Added in version 2.0.
- Returns:
The welcome screen of guild.
- Return type:
WelcomeScreen- Raises:
Forbidden – You do not have the proper permissions to get this.
HTTPException – Retrieving the welcome screen failed somehow.
NotFound – The guild doesn’t have a welcome screen or community feature is disabled.
- await widget()¶
This function is a coroutine.
Returns the widget of the guild.
Note
The guild must have the widget enabled to get this information.
- Returns:
The guild’s widget.
- Return type:
Widget- Raises:
Forbidden – The widget for this guild is disabled.
HTTPException – Retrieving the widget failed.
- class discord.events.GuildUpdate[source]¶
Called when a guild is updated.
Examples of when this is called: - Changed name - Changed AFK channel - Changed AFK timeout - etc.
This requires
Intents.guildsto be enabled.This event inherits from
Guild.- old¶
The guild prior to being updated.
- Type:
Guild
- await active_threads()¶
This function is a coroutine.
Returns a list of active
Threadthat the client can access.This includes both private and public threads.
Added in version 2.0.
- Returns:
The active threads
- Return type:
List[
Thread]- Raises:
HTTPException – The request to get the active threads failed.
- await audit_logs(*, limit=100, before=None, after=None, user=None, action=None)¶
Returns an
AsyncIteratorthat enables receiving the guild’s audit logs.You must have the
view_audit_logpermission to use this.See API documentation for more information about the before and after parameters.
- Parameters:
limit (Optional[
int]) – The number of entries to retrieve. IfNoneretrieve all entries.before (Union[
abc.Snowflake,datetime.datetime]) – Retrieve entries before this date or entry. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.after (Union[
abc.Snowflake,datetime.datetime]) – Retrieve entries after this date or entry. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.user (
abc.Snowflake) – The moderator to filter entries from.action (
AuditLogAction) – The action to filter with.
- Yields:
AuditLogEntry– The audit log entry.- Raises:
Forbidden – You are not allowed to fetch audit logs
HTTPException – An error occurred while fetching the audit logs.
- Return type:
AuditLogIterator
Examples
Getting the first 100 entries:
async for entry in guild.audit_logs(limit=100): print(f"{entry.user} did {entry.action} to {await entry.get_target()}")
Getting entries for a specific action:
async for entry in guild.audit_logs(action=discord.AuditLogAction.ban): print(f"{entry.user} banned {await entry.get_target()}")
Getting entries made by a specific user:
entries = await guild.audit_logs(limit=None, user=guild.me).flatten() await channel.send(f"I made {len(entries)} moderation actions.")
- await ban(user, *, delete_message_seconds=None, reason=None)¶
This function is a coroutine.
Bans a user from the guild.
The user must meet the
abc.Snowflakeabc.You must have the
ban_memberspermission to do this.- Parameters:
user (
abc.Snowflake) – The user to ban from their guild.delete_message_seconds (Optional[
int]) – The number of seconds worth of messages to delete from the user in the guild. The minimum is 0 and the maximum is 604800 (i.e. 7 days). The default is 0.reason (Optional[
str]) – The reason the user got banned.
- Raises:
Forbidden – You do not have the proper permissions to ban.
HTTPException – Banning failed.
- Return type:
- bans(limit=None, before=None, after=None)¶
This function is a coroutine.
Retrieves an
AsyncIteratorthat enables receiving the guild’s bans. In order to use this, you must have theban_memberspermission. Users will always be returned in ascending order sorted by user ID. If both thebeforeandafterparameters are provided, only before is respected.Changed in version 2.5: The
before. andafterparameters were changed. They are now of the typeabc.Snowflakeinstead of SnowflakeTime to comply with the discord api.Changed in version 2.0: The
limit,before. andafterparameters were added. Now returns aBanIteratorinstead of a list ofBanEntryobjects.All parameters are optional.
- Parameters:
limit (Optional[
int]) – The number of bans to retrieve. Defaults to 1000.before (Optional[
abc.Snowflake]) – Retrieve bans before the given user.after (Optional[
abc.Snowflake]) – Retrieve bans after the given user.
- Yields:
BanEntry– The ban entry for the ban.- Raises:
Forbidden – You do not have proper permissions to get the information.
HTTPException – An error occurred while fetching the information.
- Return type:
BanIterator
Examples
Usage
async for ban in guild.bans(limit=150): print(ban.user.name)
Flattening into a list
bans = await guild.bans(limit=150).flatten() # bans is now a list of BanEntry...
- await bulk_ban(*users, delete_message_seconds=None, reason=None)¶
This function is a coroutine.
Bulk ban users from the guild.
The users must meet the
abc.Snowflakeabc.You must have the
ban_memberspermission to do this.Example Usage:
# Ban multiple users successes, failures = await guild.bulk_ban(user1, user2, user3, ..., reason="Raid") # Ban a list of users successes, failures = await guild.bulk_ban(*users)
- Parameters:
*users (
abc.Snowflake) – An argument list of users to ban from the guild, up to 200.delete_message_seconds (Optional[
int]) – The number of seconds worth of messages to delete from the user in the guild. The minimum is 0 and the maximum is 604800 (i.e. 7 days). The default is 0.reason (Optional[
str]) – The reason the users were banned.
- Returns:
Returns two lists: the first contains members that were successfully banned, while the second is members that could not be banned.
- Return type:
Tuple[List[
abc.Snowflake], List[abc.Snowflake]]- Raises:
ValueError – You tried to ban more than 200 users.
Forbidden – You do not have the proper permissions to ban.
HTTPException – No users were banned.
- by_category()¶
Returns every
CategoryChanneland their associated channels.These channels and categories are sorted in the official Discord UI order.
If the channels do not have a category, then the first element of the tuple is
None.- Returns:
The categories and their associated channels.
- Return type:
List[Tuple[Optional[
CategoryChannel], List[abc.GuildChannel]]]
- property categories: list[CategoryChannel]¶
A list of categories that belong to this guild.
This is sorted by the position and are in UI order from top to bottom.
- await change_voice_state(*, channel, self_mute=False, self_deaf=False)¶
This function is a coroutine.
Changes client’s voice state in the guild.
Added in version 1.4.
- await chunk(*, cache=True)¶
This function is a coroutine.
Requests all members that belong to this guild. In order to use this,
Intents.members()must be enabled.This is a websocket operation and can be slow.
Added in version 1.5.
- Parameters:
cache (
bool) – Whether to cache the members as well.- Raises:
ClientException – The members intent is not enabled.
- Return type:
- await create_auto_moderation_rule(*, name, event_type, trigger_type, trigger_metadata, actions, enabled=False, exempt_roles=None, exempt_channels=None, reason=None)¶
Creates an auto moderation rule.
- Parameters:
name (
str) – The name of the auto moderation rule.event_type (
AutoModEventType) – The type of event that triggers the rule.trigger_type (
AutoModTriggerType) – The rule’s trigger type.trigger_metadata (
AutoModTriggerMetadata) – The rule’s trigger metadata.actions (List[
AutoModAction]) – The actions to take when the rule is triggered.enabled (
bool) – Whether the rule is enabled.exempt_roles (List[
abc.Snowflake]) – A list of roles that are exempt from the rule.exempt_channels (List[
abc.Snowflake]) – A list of channels that are exempt from the rule.reason (Optional[
str]) – The reason for creating the rule. Shows up in the audit log.
- Returns:
The new auto moderation rule.
- Return type:
AutoModRule- Raises:
HTTPException – Creating the auto moderation rule failed.
Forbidden – You do not have the Manage Guild permission.
- await create_category(name, *, overwrites=Undefined.MISSING, reason=None, position=Undefined.MISSING)¶
This function is a coroutine.
Same as
create_text_channel()except makes aCategoryChannelinstead.Note
The
categoryparameter is not supported in this function since categories cannot have categories.- Returns:
The channel that was just created.
- Return type:
CategoryChannel- Raises:
Forbidden – You do not have the proper permissions to create this channel.
HTTPException – Creating the channel failed.
InvalidArgument – The permission overwrite information is not in proper form.
- Parameters:
- await create_category_channel(name, *, overwrites=Undefined.MISSING, reason=None, position=Undefined.MISSING)¶
This function is a coroutine.
Same as
create_text_channel()except makes aCategoryChannelinstead.Note
The
categoryparameter is not supported in this function since categories cannot have categories.- Returns:
The channel that was just created.
- Return type:
CategoryChannel- Raises:
Forbidden – You do not have the proper permissions to create this channel.
HTTPException – Creating the channel failed.
InvalidArgument – The permission overwrite information is not in proper form.
- Parameters:
- await create_custom_emoji(*, name, image, roles=Undefined.MISSING, reason=None)¶
This function is a coroutine.
Creates a custom
GuildEmojifor the guild.There is currently a limit of 50 static and animated emojis respectively per guild, unless the guild has the
MORE_EMOJIfeature which extends the limit to 200.You must have the
manage_emojispermission to do this.- Parameters:
name (
str) – The emoji name. Must be at least 2 characters.image (
bytes) – The bytes-like object representing the image data to use. Only JPG, PNG and GIF images are supported.roles (List[
Role]) – AlistofRoles that can use this emoji. Leave empty to make it available to everyone.reason (Optional[
str]) – The reason for creating this emoji. Shows up on the audit log.
- Raises:
Forbidden – You are not allowed to create emojis.
HTTPException – An error occurred creating an emoji.
- Returns:
The created emoji.
- Return type:
GuildEmoji
- await create_forum_channel(name, *, reason=None, category=None, position=Undefined.MISSING, topic=Undefined.MISSING, slowmode_delay=Undefined.MISSING, nsfw=Undefined.MISSING, overwrites=Undefined.MISSING, default_reaction_emoji=Undefined.MISSING, available_tags=Undefined.MISSING, default_sort_order=Undefined.MISSING, default_thread_slowmode_delay=Undefined.MISSING, default_auto_archive_duration=Undefined.MISSING)¶
This function is a coroutine.
Creates a
ForumChannelfor the guild.Note that you need the
manage_channelspermission to create the channel.The
overwritesparameter can be used to create a ‘secret’ channel upon creation. This parameter expects adictof overwrites with the target (either aMemberor aRole) as the key and aPermissionOverwriteas the value.Note
Creating a channel of a specified position will not update the position of other channels to follow suit. A follow-up call to
edit()will be required to update the position of the channel in the channel list.- Parameters:
name (
str) – The channel’s name.overwrites (Dict[Union[
Role,Member,Snowflake],PermissionOverwrite]) – The overwrites to apply to the channel. Useful for creating secret channels.category (Optional[
CategoryChannel]) – The category to place the newly created channel under. The permissions will be automatically synced to category if no overwrites are provided.position (
int) – The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0.topic (
str) – The new channel’s topic.slowmode_delay (
int) – Specifies the slowmode rate limit for user in this channel, in seconds. A value of0disables slowmode. The maximum value possible is21600.nsfw (
bool) – Whether the channel is marked as NSFW.reason (Optional[
str]) – The reason for creating this channel. Shows up on the audit log.default_reaction_emoji (Optional[
GuildEmoji|int|str]) –The default reaction emoji. Can be a unicode emoji or a custom emoji in the forms:
GuildEmoji, snowflake ID, string representation (eg. ‘<a:emoji_name:emoji_id>’).Added in version v2.5.
available_tags (List[
ForumTag]) –The set of tags that can be used in a forum channel.
Added in version 2.7.
default_sort_order (Optional[
SortOrder]) –The default sort order type used to order posts in this channel.
Added in version 2.7.
default_thread_slowmode_delay (Optional[
int]) –The initial slowmode delay to set on newly created threads in this channel.
Added in version 2.7.
default_auto_archive_duration (
int) –The default auto archive duration in minutes for threads created in this channel.
Added in version 2.7.
- Returns:
The channel that was just created.
- Return type:
ForumChannel- Raises:
Forbidden – You do not have the proper permissions to create this channel.
HTTPException – Creating the channel failed.
InvalidArgument – The argument is not in proper form.
Examples
Creating a basic channel:
channel = await guild.create_forum_channel("cool-channel")
Creating a “secret” channel:
overwrites = { guild.default_role: discord.PermissionOverwrite(read_messages=False), guild.me: discord.PermissionOverwrite(read_messages=True), } channel = await guild.create_forum_channel("secret", overwrites=overwrites)
- await create_integration(*, type, id)¶
This function is a coroutine.
Attaches an integration to the guild.
You must have the
manage_guildpermission to do this.Added in version 1.4.
- Parameters:
- Raises:
Forbidden – You do not have permission to create the integration.
HTTPException – The account could not be found.
- Return type:
- await create_role(*, name=Undefined.MISSING, permissions=Undefined.MISSING, color=Undefined.MISSING, colour=Undefined.MISSING, colors=Undefined.MISSING, colours=Undefined.MISSING, holographic=Undefined.MISSING, hoist=Undefined.MISSING, mentionable=Undefined.MISSING, reason=None, icon=Undefined.MISSING, unicode_emoji=Undefined.MISSING)¶
This function is a coroutine.
Creates a
Rolefor the guild.All fields are optional.
You must have the
manage_rolespermission to do this.Changed in version 1.6: Can now pass
inttocolourkeyword-only parameter.- Parameters:
name (
str) – The role name. Defaults to ‘new role’.permissions (
Permissions) – The permissions to have. Defaults to no permissions.colour (Union[
Colour,int]) – The colour for the role. Defaults toColour.default(). This is aliased tocoloras well.hoist (
bool) – Indicates if the role should be shown separately in the member list. Defaults toFalse.mentionable (
bool) – Indicates if the role should be mentionable by others. Defaults toFalse.reason (Optional[
str]) – The reason for creating this role. Shows up on the audit log.icon (Optional[
bytes]) – A bytes-like object representing the icon. Only PNG/JPEG/WebP is supported. If this argument is passed,unicode_emojiis set to None. Only available to guilds that containROLE_ICONSinGuild.features.unicode_emoji (Optional[
str]) – The role’s unicode emoji. If this argument is passed,iconis set to None. Only available to guilds that containROLE_ICONSinGuild.features.color (Colour | int | utils.Undefined)
colors (RoleColours | utils.Undefined)
colours (RoleColours | utils.Undefined)
holographic (bool | utils.Undefined)
- Returns:
The newly created role.
- Return type:
Role- Raises:
Forbidden – You do not have permissions to create the role.
HTTPException – Creating the role failed.
InvalidArgument – An invalid keyword argument was given.
- await create_scheduled_event(*, name, description=Undefined.MISSING, start_time, end_time=Undefined.MISSING, location, privacy_level=ScheduledEventPrivacyLevel.guild_only, reason=None, image=Undefined.MISSING)¶
This function is a coroutine. Creates a scheduled event.
- Parameters:
name (
str) – The name of the scheduled event.description (Optional[
str]) – The description of the scheduled event.start_time (
datetime.datetime) – A datetime object of when the scheduled event is supposed to start.end_time (Optional[
datetime.datetime]) – A datetime object of when the scheduled event is supposed to end.location (
ScheduledEventLocation) – The location of where the event is happening.privacy_level (
ScheduledEventPrivacyLevel) – The privacy level of the event. Currently, the only possible value isScheduledEventPrivacyLevel.guild_only, which is default, so there is no need to change this parameter.reason (Optional[
str]) – The reason to show in the audit log.image (Optional[
bytes]) – The cover image of the scheduled event
- Returns:
The created scheduled event.
- Return type:
Optional[
ScheduledEvent]- Raises:
Forbidden – You do not have the Manage Events permission.
HTTPException – The operation failed.
- await create_sound(name, sound, volume=1.0, emoji=None, reason=None)¶
This function is a coroutine. Creates a
SoundboardSoundin the guild. You must havePermissions.manage_expressionspermission to use this.Added in version 2.7.
- Parameters:
name (
str) – The name of the sound.sound (
bytes) – The bytes-like object representing the sound data. Only MP3 sound files that are less than 5.2 seconds long are supported.volume (
float) – The volume of the sound. Defaults to 1.0.emoji (Optional[Union[
PartialEmoji,GuildEmoji,str]]) – The emoji of the sound.reason (Optional[
str]) – The reason for creating this sound. Shows up on the audit log.
- Returns:
The created sound.
- Return type:
SoundboardSound- Raises:
HTTPException – Creating the sound failed.
Forbidden – You do not have permissions to create sounds.
- await create_stage_channel(name, *, topic, position=Undefined.MISSING, overwrites=Undefined.MISSING, category=None, reason=None, bitrate=Undefined.MISSING, user_limit=Undefined.MISSING, rtc_region=Undefined.MISSING, video_quality_mode=Undefined.MISSING, slowmode_delay=Undefined.MISSING, nsfw=Undefined.MISSING)¶
This function is a coroutine.
This is similar to
create_text_channel()except makes aStageChannelinstead.Added in version 1.7.
- Parameters:
name (
str) – The channel’s name.topic (
str) – The new channel’s topic.overwrites (Dict[Union[
Role,Member,Snowflake],PermissionOverwrite]) – The overwrites to apply to the channel. Useful for creating secret channels.category (Optional[
CategoryChannel]) – The category to place the newly created channel under. The permissions will be automatically synced to category if no overwrites are provided.position (
int) – The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0.reason (Optional[
str]) – The reason for creating this channel. Shows up on the audit log.bitrate (
int) –The channel’s preferred audio bitrate in bits per second.
Added in version 2.7.
user_limit (
int) –The channel’s limit for number of members that can be in a voice channel.
Added in version 2.7.
rtc_region (Optional[
VoiceRegion]) –The region for the voice channel’s voice communication. A value of
Noneindicates automatic voice region detection.Added in version 2.7.
video_quality_mode (
VideoQualityMode) –The camera video quality for the voice channel’s participants.
Added in version 2.7.
slowmode_delay (
int) –Specifies the slowmode rate limit for user in this channel, in seconds. A value of
0disables slowmode. The maximum value possible is21600.Added in version 2.7.
nsfw (
bool) –Whether the channel is marked as NSFW.
Added in version 2.7.
- Returns:
The channel that was just created.
- Return type:
StageChannel- Raises:
Forbidden – You do not have the proper permissions to create this channel.
HTTPException – Creating the channel failed.
InvalidArgument – The permission overwrite information is not in proper form.
- await create_sticker(*, name, description=None, emoji, file, reason=None)¶
This function is a coroutine.
Creates a
Stickerfor the guild.You must have
manage_emojis_and_stickerspermission to do this.Added in version 2.0.
- Parameters:
name (
str) – The sticker name. Must be 2 to 30 characters.description (Optional[
str]) – The sticker’s description. If used, must be 2 to 100 characters.emoji (
str) – The name of a unicode emoji that represents the sticker’s expression.file (
File) – The file of the sticker to upload.reason (
str) – The reason for creating this sticker. Shows up on the audit log.
- Returns:
The created sticker.
- Return type:
GuildSticker- Raises:
Forbidden – You are not allowed to create stickers.
HTTPException – An error occurred creating a sticker.
TypeError – The parameters for the sticker are not correctly formatted.
- await create_template(*, name, description=Undefined.MISSING)¶
This function is a coroutine.
Creates a template for the guild.
You must have the
manage_guildpermission to do this.Added in version 1.7.
- await create_test_entitlement(sku)¶
This function is a coroutine.
Creates a test entitlement for the guild.
- Parameters:
sku (
Snowflake) – The SKU to create a test entitlement for.- Returns:
The created entitlement.
- Return type:
Entitlement
- await create_text_channel(name, *, reason=None, category=None, position=Undefined.MISSING, topic=Undefined.MISSING, slowmode_delay=Undefined.MISSING, nsfw=Undefined.MISSING, overwrites=Undefined.MISSING, default_thread_slowmode_delay=Undefined.MISSING, default_auto_archive_duration=Undefined.MISSING)¶
This function is a coroutine.
Creates a
TextChannelfor the guild.Note that you need the
manage_channelspermission to create the channel.The
overwritesparameter can be used to create a ‘secret’ channel upon creation. This parameter expects adictof overwrites with the target (either aMemberor aRole) as the key and aPermissionOverwriteas the value.Note
Creating a channel of a specified position will not update the position of other channels to follow suit. A follow-up call to
edit()will be required to update the position of the channel in the channel list.- Parameters:
name (
str) – The channel’s name.overwrites (Dict[Union[
Role,Member,Snowflake],PermissionOverwrite]) – The overwrites to apply to the channel. Useful for creating secret channels.category (Optional[
CategoryChannel]) – The category to place the newly created channel under. The permissions will be automatically synced to category if no overwrites are provided.position (
int) – The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0.topic (
str) – The new channel’s topic.slowmode_delay (
int) – Specifies the slowmode rate limit for user in this channel, in seconds. A value of 0 disables slowmode. The maximum value possible is 21600.nsfw (
bool) – Whether the channel is marked as NSFW.reason (Optional[
str]) – The reason for creating this channel. Shows up on the audit log.default_thread_slowmode_delay (Optional[
int]) –The initial slowmode delay to set on newly created threads in this channel.
Added in version 2.7.
default_auto_archive_duration (
int) –The default auto archive duration in minutes for threads created in this channel.
Added in version 2.7.
- Returns:
The channel that was just created.
- Return type:
TextChannel- Raises:
Forbidden – You do not have the proper permissions to create this channel.
HTTPException – Creating the channel failed.
InvalidArgument – The permission overwrite information is not in proper form.
Examples
Creating a basic channel:
channel = await guild.create_text_channel("cool-channel")
Creating a “secret” channel:
overwrites = { guild.default_role: discord.PermissionOverwrite(read_messages=False), guild.me: discord.PermissionOverwrite(read_messages=True), } channel = await guild.create_text_channel("secret", overwrites=overwrites)
- await create_voice_channel(name, *, reason=None, category=None, position=Undefined.MISSING, bitrate=Undefined.MISSING, user_limit=Undefined.MISSING, rtc_region=Undefined.MISSING, video_quality_mode=Undefined.MISSING, overwrites=Undefined.MISSING, slowmode_delay=Undefined.MISSING, nsfw=Undefined.MISSING)¶
This function is a coroutine.
This is similar to
create_text_channel()except makes aVoiceChannelinstead.- Parameters:
name (
str) – The channel’s name.overwrites (Dict[Union[
Role,Member,Snowflake],PermissionOverwrite]) – The overwrites to apply to the channel. Useful for creating secret channels.category (Optional[
CategoryChannel]) – The category to place the newly created channel under. The permissions will be automatically synced to category if no overwrites are provided.position (
int) – The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0.bitrate (
int) – The channel’s preferred audio bitrate in bits per second.user_limit (
int) – The channel’s limit for number of members that can be in a voice channel.rtc_region (Optional[
VoiceRegion]) –The region for the voice channel’s voice communication. A value of
Noneindicates automatic voice region detection.Added in version 1.7.
video_quality_mode (
VideoQualityMode) –The camera video quality for the voice channel’s participants.
Added in version 2.0.
reason (Optional[
str]) – The reason for creating this channel. Shows up on the audit log.slowmode_delay (
int) –Specifies the slowmode rate limit for user in this channel, in seconds. A value of
0disables slowmode. The maximum value possible is21600.Added in version 2.7.
nsfw (
bool) –Whether the channel is marked as NSFW.
Added in version 2.7.
- Returns:
The channel that was just created.
- Return type:
VoiceChannel- Raises:
Forbidden – You do not have the proper permissions to create this channel.
HTTPException – Creating the channel failed.
InvalidArgument – The permission overwrite information is not in proper form.
- await delete()¶
This function is a coroutine.
Deletes the guild. You must be the guild owner to delete the guild.
- Raises:
HTTPException – Deleting the guild failed.
Forbidden – You do not have permissions to delete the guild.
- Return type:
- await delete_auto_moderation_rule(id, *, reason=None)¶
Deletes an auto moderation rule.
- Parameters:
- Raises:
HTTPException – Deleting the auto moderation rule failed.
Forbidden – You do not have the Manage Guild permission.
- Return type:
- await delete_emoji(emoji, *, reason=None)¶
This function is a coroutine.
Deletes the custom
GuildEmojifrom the guild.You must have
manage_emojispermission to do this.- Parameters:
emoji (
abc.Snowflake) – The emoji you are deleting.reason (Optional[
str]) – The reason for deleting this emoji. Shows up on the audit log.
- Raises:
Forbidden – You are not allowed to delete emojis.
HTTPException – An error occurred deleting the emoji.
- Return type:
- await delete_sticker(sticker, *, reason=None)¶
This function is a coroutine.
Deletes the custom
Stickerfrom the guild.You must have
manage_emojis_and_stickerspermission to do this.Added in version 2.0.
- Parameters:
sticker (
abc.Snowflake) – The sticker you are deleting.reason (Optional[
str]) – The reason for deleting this sticker. Shows up on the audit log.
- Raises:
Forbidden – You are not allowed to delete stickers.
HTTPException – An error occurred deleting the sticker.
- Return type:
- await edit(*, reason=Undefined.MISSING, name=Undefined.MISSING, description=Undefined.MISSING, icon=Undefined.MISSING, banner=Undefined.MISSING, splash=Undefined.MISSING, discovery_splash=Undefined.MISSING, community=Undefined.MISSING, afk_channel=Undefined.MISSING, owner=Undefined.MISSING, afk_timeout=Undefined.MISSING, default_notifications=Undefined.MISSING, verification_level=Undefined.MISSING, explicit_content_filter=Undefined.MISSING, system_channel=Undefined.MISSING, system_channel_flags=Undefined.MISSING, preferred_locale=Undefined.MISSING, rules_channel=Undefined.MISSING, public_updates_channel=Undefined.MISSING, premium_progress_bar_enabled=Undefined.MISSING, disable_invites=Undefined.MISSING, discoverable=Undefined.MISSING, disable_raid_alerts=Undefined.MISSING, enable_activity_feed=Undefined.MISSING)¶
This function is a coroutine.
Edits the guild.
You must have the
manage_guildpermission to edit the guild.Changed in version 1.4: The rules_channel and public_updates_channel keyword-only parameters were added.
Changed in version 2.0: The discovery_splash and community keyword-only parameters were added.
Changed in version 2.0: The newly updated guild is returned.
- Parameters:
name (
str) – The new name of the guild.description (Optional[
str]) – The new description of the guild. Could beNonefor no description. This is only available to guilds that containPUBLICinGuild.features.icon (
bytes) – A bytes-like object representing the icon. Only PNG/JPEG is supported. GIF is only available to guilds that containANIMATED_ICONinGuild.features. Could beNoneto denote removal of the icon.banner (
bytes) – A bytes-like object representing the banner. Could beNoneto denote removal of the banner. This is only available to guilds that containBANNERinGuild.features.splash (
bytes) – A bytes-like object representing the invite splash. Only PNG/JPEG supported. Could beNoneto denote removing the splash. This is only available to guilds that containINVITE_SPLASHinGuild.features.discovery_splash (
bytes) – A bytes-like object representing the discovery splash. Only PNG/JPEG supported. Could beNoneto denote removing the splash. This is only available to guilds that containDISCOVERABLEinGuild.features.community (
bool) – Whether the guild should be a Community guild. If set toTrue, bothrules_channelandpublic_updates_channelparameters are required.afk_channel (Optional[
VoiceChannel]) – The new channel that is the AFK channel. Could beNonefor no AFK channel.afk_timeout (
int) – The number of seconds until someone is moved to the AFK channel.owner (
Member) – The new owner of the guild to transfer ownership to. Note that you must be owner of the guild to do this.verification_level (
VerificationLevel) – The new verification level for the guild.default_notifications (
NotificationLevel) – The new default notification level for the guild.explicit_content_filter (
ContentFilter) – The new explicit content filter for the guild.system_channel (Optional[
TextChannel]) – The new channel that is used for the system channel. Could beNonefor no system channel.system_channel_flags (
SystemChannelFlags) – The new system channel settings to use with the new system channel.preferred_locale (
str) – The new preferred locale for the guild. Used as the primary language in the guild. If set, this must be an ISO 639 code, e.g.en-USorjaorzh-CN.rules_channel (Optional[
TextChannel]) – The new channel that is used for rules. This is only available to guilds that containPUBLICinGuild.features. Could beNonefor no rules channel.public_updates_channel (Optional[
TextChannel]) – The new channel that is used for public updates from Discord. This is only available to guilds that containPUBLICinGuild.features. Could beNonefor no public updates channel.premium_progress_bar_enabled (
bool) – Whether the guild should have premium progress bar enabled.disable_invites (
bool) – Whether the guild should have server invites enabled or disabled.discoverable (
bool) – Whether the guild should be discoverable in the discover tab.disable_raid_alerts (
bool) – Whether activity alerts for the guild should be disabled.enable_activity_feed (class:bool) – Whether the guild’s user activity feed should be enabled.
reason (Optional[
str]) – The reason for editing this guild. Shows up on the audit log.
- Raises:
Forbidden – You do not have permissions to edit the guild.
HTTPException – Editing the guild failed.
InvalidArgument – The image format passed in to
iconis invalid. It must be PNG or JPG. This is also raised if you are not the owner of the guild and request an ownership transfer.
- Returns:
The newly updated guild. Note that this has the same limitations as mentioned in
Client.fetch_guild()and may not have full data.- Return type:
Guild
- await edit_onboarding(*, prompts=Undefined.MISSING, default_channels=Undefined.MISSING, enabled=Undefined.MISSING, mode=Undefined.MISSING, reason=Undefined.MISSING)¶
This function is a coroutine.
A shorthand for
Onboarding.editwithout fetching the onboarding flow.You must have the
manage_guildandmanage_rolespermissions in the guild to do this.- Parameters:
prompts (Optional[List[
OnboardingPrompt]]) – The new list of prompts for this flow.default_channels (Optional[List[
Snowflake]]) – The new default channels that users are opted into.enabled (Optional[
bool]) – Whether onboarding should be enabled. Setting this toTruerequires the guild to haveCOMMUNITYinfeaturesand at least 7default_channels.mode (Optional[
OnboardingMode]) – The new onboarding mode.reason (Optional[
str]) – The reason that shows up on Audit log.
- Returns:
The updated onboarding flow.
- Return type:
Onboarding- Raises:
HTTPException – Editing the onboarding flow failed somehow.
Forbidden – You don’t have permissions to edit the onboarding flow.
- await edit_role_positions(positions, *, reason=None)¶
This function is a coroutine.
Bulk edits a list of
Rolein the guild.You must have the
manage_rolespermission to do this.Added in version 1.4.
Example:
positions = { bots_role: 1, # penultimate role tester_role: 2, admin_role: 6, } await guild.edit_role_positions(positions=positions)
- Parameters:
- Returns:
A list of all the roles in the guild.
- Return type:
List[
Role]- Raises:
Forbidden – You do not have permissions to move the roles.
HTTPException – Moving the roles failed.
InvalidArgument – An invalid keyword argument was given.
- await edit_welcome_screen(**options)¶
This function is a coroutine.
A shorthand for
WelcomeScreen.editwithout fetching the welcome screen.You must have the
manage_guildpermission in the guild to do this.The guild must have
COMMUNITYinGuild.features- Parameters:
description (Optional[
str]) – The new description of welcome screen.welcome_channels (Optional[List[
WelcomeScreenChannel]]) – The welcome channels. The order of the channels would be same as the passed list order.enabled (Optional[
bool]) – Whether the welcome screen should be displayed.reason (Optional[
str]) – The reason that shows up on audit log.
- Returns:
The edited welcome screen.
- Return type:
WelcomeScreen- Raises:
HTTPException – Editing the welcome screen failed somehow.
Forbidden – You don’t have permissions to edit the welcome screen.
NotFound – This welcome screen does not exist.
- await edit_widget(*, enabled=Undefined.MISSING, channel=Undefined.MISSING)¶
This function is a coroutine.
Edits the widget of the guild.
You must have the
manage_guildpermission to use thisAdded in version 2.0.
- Parameters:
- Raises:
Forbidden – You do not have permission to edit the widget.
HTTPException – Editing the widget failed.
- Return type:
- entitlements(skus=None, before=None, after=None, limit=100, exclude_ended=False)¶
Returns an
AsyncIteratorthat enables fetching the guild’s entitlements.This is identical to
Client.entitlements()with theguildparameter.Added in version 2.6.
- Parameters:
skus (list[
abc.Snowflake] | None) – Limit the fetched entitlements to entitlements that are for these SKUs.before (
abc.Snowflake|datetime.datetime| None) – Retrieves guilds before this date or object. If a datetime is provided, it is recommended to use a UTC-aware datetime. If the datetime is naive, it is assumed to be local time.after (
abc.Snowflake|datetime.datetime| None) – Retrieve guilds after this date or object. If a datetime is provided, it is recommended to use a UTC-aware datetime. If the datetime is naive, it is assumed to be local time.limit (Optional[
int]) – The number of entitlements to retrieve. IfNone, retrieves every entitlement, which may be slow. Defaults to100.exclude_ended (
bool) – Whether to limit the fetched entitlements to those that have not ended. Defaults toFalse.
- Yields:
Entitlement– The application’s entitlements.- Raises:
HTTPException – Retrieving the entitlements failed.
- Return type:
EntitlementIterator
- await estimate_pruned_members(*, days, roles=Undefined.MISSING)¶
This function is a coroutine.
Similar to
prune_members()except instead of actually pruning members, it returns how many members it would prune from the guild had it been called.- Parameters:
days (
int) – The number of days before counting as inactive.roles (List[
abc.Snowflake]) –A list of
abc.Snowflakethat represent roles to include in the estimate. If a member has a role that is not specified, they’ll be excluded.Added in version 1.7.
- Returns:
The number of members estimated to be pruned.
- Return type:
- Raises:
Forbidden – You do not have permissions to prune members.
HTTPException – An error occurred while fetching the prune members estimate.
InvalidArgument – An integer was not passed for
days.
- await fetch_auto_moderation_rule(id)¶
This function is a coroutine.
Retrieves a
AutoModRulefrom rule ID.- Returns:
The requested auto moderation rule.
- Return type:
AutoModRule- Raises:
HTTPException – Getting the auto moderation rule failed.
Forbidden – You do not have the Manage Guild permission.
- Parameters:
id (
int)
- await fetch_auto_moderation_rules()¶
This function is a coroutine.
Retrieves a list of auto moderation rules for this guild.
- Returns:
The auto moderation rules for this guild.
- Return type:
List[
AutoModRule]- Raises:
HTTPException – Getting the auto moderation rules failed.
Forbidden – You do not have the Manage Guild permission.
- await fetch_ban(user)¶
This function is a coroutine.
Retrieves the
BanEntryfor a user.You must have the
ban_memberspermission to get this information.- Parameters:
user (
abc.Snowflake) – The user to get ban information from.- Returns:
The
BanEntryobject for the specified user.- Return type:
BanEntry- Raises:
Forbidden – You do not have proper permissions to get the information.
NotFound – This user is not banned.
HTTPException – An error occurred while fetching the information.
- await fetch_channel(channel_id, /)¶
This function is a coroutine.
Retrieves a
abc.GuildChannelorThreadwith the specified ID.Note
This method is an API call. For general usage, consider
get_channel_or_thread()instead.Added in version 2.0.
- Returns:
The channel from the ID.
- Return type:
Union[
abc.GuildChannel,Thread]- Raises:
InvalidData – An unknown channel type was received from Discord or the guild the channel belongs to is not the same as the one in this object points to.
HTTPException – Retrieving the channel failed.
NotFound – Invalid Channel ID.
Forbidden – You do not have permission to fetch this channel.
- Parameters:
channel_id (
int)
- await fetch_channels()¶
This function is a coroutine.
Retrieves all
abc.GuildChannelthat the guild has.Note
This method is an API call. For general usage, consider
channelsinstead.Added in version 1.2.
- Returns:
All channels in the guild.
- Return type:
Sequence[
discord.channel.base.GuildChannel]- Raises:
InvalidData – An unknown channel type was received from Discord.
HTTPException – Retrieving the channels failed.
- await fetch_emoji(emoji_id, /)¶
This function is a coroutine.
Retrieves a custom
GuildEmojifrom the guild.Note
This method is an API call. For general usage, consider iterating over
emojisinstead.- Parameters:
emoji_id (
int) – The emoji’s ID.- Returns:
The retrieved emoji.
- Return type:
GuildEmoji- Raises:
NotFound – The emoji requested could not be found.
HTTPException – An error occurred fetching the emoji.
- await fetch_emojis()¶
This function is a coroutine.
Retrieves all custom
GuildEmojis from the guild.Note
This method is an API call. For general usage, consider
emojisinstead.- Raises:
HTTPException – An error occurred fetching the emojis.
- Returns:
The retrieved emojis.
- Return type:
List[
GuildEmoji]
- await fetch_member(member_id, /)¶
This function is a coroutine.
Retrieves a
Memberfrom a guild ID, and a member ID.Note
This method is an API call. If you have
Intents.membersand member cache enabled, considerget_member()instead.- Parameters:
member_id (
int) – The member’s ID to fetch from.- Returns:
The member from the member ID.
- Return type:
Member- Raises:
Forbidden – You do not have access to the guild.
HTTPException – Fetching the member failed.
- fetch_members(*, limit=1000, after=None)¶
Retrieves an
AsyncIteratorthat enables receiving the guild’s members. In order to use this,Intents.members()must be enabled.Note
This method is an API call. For general usage, consider
membersinstead.Added in version 1.3.
All parameters are optional.
- Parameters:
limit (Optional[
int]) – The number of members to retrieve. Defaults to 1000. PassNoneto fetch all members. Note that this is potentially slow.after (Optional[Union[
abc.Snowflake,datetime.datetime]]) – Retrieve members after this date or object. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.
- Yields:
Member– The member with the member data parsed.- Raises:
ClientException – The members intent is not enabled.
HTTPException – Getting the members failed.
- Return type:
MemberIterator
Examples
Usage
async for member in guild.fetch_members(limit=150): print(member.name)
Flattening into a list
members = await guild.fetch_members(limit=150).flatten() # members is now a list of Member...
- await fetch_role(role_id)¶
This function is a coroutine.
Retrieves a
Rolethat the guild has.Note
This method is an API call. For general usage, consider using
get_roleinstead.Added in version 2.7.
- Returns:
The role in the guild with the specified ID.
- Return type:
Role- Raises:
HTTPException – Retrieving the role failed.
- Parameters:
role_id (
int)
- await fetch_roles()¶
This function is a coroutine.
Retrieves all
Rolethat the guild has.Note
This method is an API call. For general usage, consider
rolesinstead.Added in version 1.3.
- Returns:
All roles in the guild.
- Return type:
List[
Role]- Raises:
HTTPException – Retrieving the roles failed.
- await fetch_scheduled_event(event_id, /, *, with_user_count=True)¶
This function is a coroutine.
Retrieves a
ScheduledEventfrom event ID.Note
This method is an API call. If you have
Intents.scheduled_events, considerget_scheduled_event()instead.- Parameters:
- Returns:
The scheduled event from the event ID.
- Return type:
Optional[
ScheduledEvent]- Raises:
HTTPException – Fetching the event failed.
NotFound – Event not found.
- await fetch_scheduled_events(*, with_user_count=True)¶
This function is a coroutine.
Returns a list of
ScheduledEventin the guild.Note
This method is an API call. For general usage, consider
scheduled_eventsinstead.- Parameters:
with_user_count (Optional[
bool]) – If the scheduled event should be fetched with the number of users that are interested in the events. Defaults toTrue.- Returns:
The fetched scheduled events.
- Return type:
List[
ScheduledEvent]- Raises:
ClientException – The scheduled events intent is not enabled.
HTTPException – Getting the scheduled events failed.
- await fetch_sound(sound_id)¶
This function is a coroutine. Fetches a soundboard sound in the guild.
Added in version 2.7.
- Parameters:
sound_id (
int) – The ID of the sound.- Returns:
The sound.
- Return type:
SoundboardSound
- await fetch_sounds()¶
This function is a coroutine. Fetches all the soundboard sounds in the guild.
Added in version 2.7.
- Returns:
The sounds in the guild.
- Return type:
List[
SoundboardSound]
- await fetch_sticker(sticker_id, /)¶
This function is a coroutine.
Retrieves a custom
Stickerfrom the guild.Added in version 2.0.
Note
This method is an API call. For general usage, consider iterating over
stickersinstead.- Parameters:
sticker_id (
int) – The sticker’s ID.- Returns:
The retrieved sticker.
- Return type:
GuildSticker- Raises:
NotFound – The sticker requested could not be found.
HTTPException – An error occurred fetching the sticker.
- await fetch_stickers()¶
This function is a coroutine.
Retrieves a list of all
Stickers for the guild.Added in version 2.0.
Note
This method is an API call. For general usage, consider
stickersinstead.- Raises:
HTTPException – An error occurred fetching the stickers.
- Returns:
The retrieved stickers.
- Return type:
List[
GuildSticker]
- property filesize_limit: int¶
The maximum number of bytes files can have when uploaded to this guild.
- property forum_channels: list[ForumChannel]¶
A list of forum channels that belong to this guild.
Added in version 2.0.
This is sorted by the position and are in UI order from top to bottom.
- get_channel(channel_id, /)¶
Returns a channel with the given ID.
Note
This does not search for threads.
- Parameters:
channel_id (
int) – The ID to search for.- Returns:
The returned channel or
Noneif not found.- Return type:
Optional[
abc.GuildChannel]
- get_channel_or_thread(channel_id, /)¶
Returns a channel or thread with the given ID.
Added in version 2.0.
- Parameters:
channel_id (
int) – The ID to search for.- Returns:
The returned channel or thread or
Noneif not found.- Return type:
Optional[Union[
Thread,abc.GuildChannel]]
- await get_me()¶
Similar to
Client.userexcept an instance ofMember. This is essentially used to get the member version of yourself.- Return type:
- await get_member(user_id, /)¶
Returns a member with the given ID.
- Parameters:
user_id (
int) – The ID to search for.- Returns:
The member or
Noneif not found.- Return type:
Optional[
Member]
- get_member_named(name, /)¶
Returns the first member found that matches the name provided.
The name can have an optional discriminator argument, e.g. “Jake#0001” or “Jake” will both do the lookup. However, the former will give a more precise result. Note that the discriminator must have all 4 digits for this to work.
If a nickname is passed, then it is looked up via the nickname. Note however, that a nickname + discriminator combo will not look up the nickname but rather the username + discriminator combo due to nickname + discriminator not being unique.
If no member is found,
Noneis returned.- Parameters:
name (
str) – The name of the member to lookup with an optional discriminator.- Returns:
The member in this guild with the associated name. If not found then
Noneis returned.- Return type:
Optional[
Member]
- get_role(role_id, /)¶
Returns a role with the given ID.
- Parameters:
role_id (
int) – The ID to search for.- Returns:
The role or
Noneif not found.- Return type:
Optional[
Role]
- get_scheduled_event(event_id, /)¶
Returns a Scheduled Event with the given ID.
- Parameters:
event_id (
int) – The ID to search for.- Returns:
The scheduled event or
Noneif not found.- Return type:
Optional[
ScheduledEvent]
- get_sound(sound_id)¶
Returns a sound with the given ID.
Added in version 2.7.
- Parameters:
sound_id (
int) – The ID to search for.- Returns:
The sound or
Noneif not found.- Return type:
Optional[
SoundboardSound]
- get_stage_instance(stage_instance_id, /)¶
Returns a stage instance with the given ID.
Added in version 2.0.
- Parameters:
stage_instance_id (
int) – The ID to search for.- Returns:
The stage instance or
Noneif not found.- Return type:
Optional[
StageInstance]
- get_thread(thread_id, /)¶
Returns a thread with the given ID.
Added in version 2.0.
- Parameters:
thread_id (
int) – The ID to search for.- Returns:
The returned thread or
Noneif not found.- Return type:
Optional[
Thread]
- await integrations()¶
This function is a coroutine.
Returns a list of all integrations attached to the guild.
You must have the
manage_guildpermission to do this.Added in version 1.4.
- Returns:
The list of integrations that are attached to the guild.
- Return type:
List[
Integration]- Raises:
Forbidden – You do not have permission to create the integration.
HTTPException – Fetching the integrations failed.
- await invites()¶
This function is a coroutine.
Returns a list of all active instant invites from the guild.
You must have the
manage_guildpermission to get this information.- Returns:
The list of invites that are currently active.
- Return type:
List[
Invite]- Raises:
Forbidden – You do not have proper permissions to get the information.
HTTPException – An error occurred while fetching the information.
- await is_chunked()¶
Returns a boolean indicating if the guild is “chunked”.
A chunked guild means that
member_countis equal to the number of members stored in the internalmemberscache.If this value returns
False, then you should request for offline members.- Return type:
- await is_large()¶
Indicates if the guild is a ‘large’ guild.
A large guild is defined as having more than
large_thresholdcount members, which for this library is set to the maximum of 250.- Return type:
- property jump_url: str¶
Returns a URL that allows the client to jump to the guild.
Added in version 2.0.
- await kick(user, *, reason=None)¶
This function is a coroutine.
Kicks a user from the guild.
The user must meet the
abc.Snowflakeabc.You must have the
kick_memberspermission to do this.- Parameters:
user (
abc.Snowflake) – The user to kick from their guild.reason (Optional[
str]) – The reason the user got kicked.
- Raises:
Forbidden – You do not have the proper permissions to kick.
HTTPException – Kicking failed.
- Return type:
- await leave()¶
This function is a coroutine.
Leaves the guild. :rtype:
NoneNote
You cannot leave the guild that you own, you must delete it instead via
delete().- Raises:
HTTPException – Leaving the guild failed.
- property member_count: int¶
Returns the true member count regardless of it being loaded fully or not.
Warning
Due to a Discord limitation, in order for this attribute to remain up-to-date and accurate, it requires
Intents.membersto be specified.
- await modify_incident_actions(*, invites_disabled_until=Undefined.MISSING, dms_disabled_until=Undefined.MISSING, reason=Undefined.MISSING)¶
This function is a coroutine.
Modify the guild’s incident actions, controlling when invites or DMs are re-enabled after being temporarily disabled. Requires the
manage_guildpermission.- Parameters:
invites_disabled_until (Optional[
datetime.datetime]) – The ISO8601 timestamp indicating when invites will be enabled again, orNoneto enable invites immediately.dms_disabled_until (Optional[
datetime.datetime]) – The ISO8601 timestamp indicating when DMs will be enabled again, orNoneto enable DMs immediately.reason (Optional[
str]) – The reason for this action, used for the audit log.
- Returns:
The updated incidents data for the guild.
- Return type:
IncidentsData
- await onboarding()¶
This function is a coroutine.
Returns the
Onboardingflow for the guild.Added in version 2.5.
- Returns:
The onboarding flow for the guild.
- Return type:
Onboarding- Raises:
HTTPException – Retrieving the onboarding flow failed somehow.
Gets the premium subscriber role, AKA “boost” role, in this guild.
Added in version 1.6.
A list of members who have “boosted” this guild.
- await prune_members(*, days, compute_prune_count=True, roles=Undefined.MISSING, reason=None)¶
This function is a coroutine.
Prunes the guild from its inactive members.
The inactive members are denoted if they have not logged on in
daysnumber of days and have no roles.You must have the
kick_memberspermission to use this.To check how many members you would prune without actually pruning, see the
estimate_pruned_members()function.To prune members that have specific roles see the
rolesparameter.Changed in version 1.4: The
roleskeyword-only parameter was added.- Parameters:
days (
int) – The number of days before counting as inactive.reason (Optional[
str]) – The reason for doing this action. Shows up on the audit log.compute_prune_count (
bool) – Whether to compute the prune count. This defaults toTruewhich makes it prone to timeouts in very large guilds. In order to prevent timeouts, you must set this toFalse. If this is set toFalse, then this function will always returnNone.roles (List[
abc.Snowflake]) – A list ofabc.Snowflakethat represent roles to include in the pruning process. If a member has a role that is not specified, they’ll be excluded.
- Raises:
Forbidden – You do not have permissions to prune members.
HTTPException – An error occurred while pruning members.
InvalidArgument – An integer was not passed for
days.
- Returns:
The number of members pruned. If
compute_prune_countisFalsethen this returnsNone.- Return type:
Optional[
int]
- property public_updates_channel: TextChannel | None¶
Return’s the guild’s channel where admins and moderators of the guilds receive notices from Discord. The guild must be a Community guild.
If no channel is set, then this returns
None.Added in version 1.4.
- await query_members(query=None, *, limit=5, user_ids=None, presences=False, cache=True)¶
This function is a coroutine.
Request members that belong to this guild whose username starts with the query given.
This is a websocket operation and can be slow.
Added in version 1.3.
- Parameters:
query (Optional[
str]) – The string that the username’s start with.user_ids (Optional[List[
int]]) –List of user IDs to search for. If the user ID is not in the guild then it won’t be returned.
Added in version 1.4.
limit (Optional[
int]) – The maximum number of members to send back. If no query is passed, passingNonereturns all members. If aqueryoruser_idsis passed, must be between 1 and 100. Defaults to 5.presences (Optional[
bool]) –Whether to request for presences to be provided. This defaults to
False.Added in version 1.6.
cache (
bool) – Whether to cache the members internally. This makes operations such asget_member()work for those that matched. Defaults toTrue.
- Returns:
The list of members that have matched the query.
- Return type:
List[
Member]- Raises:
asyncio.TimeoutError – The query timed out waiting for the members.
ValueError – Invalid parameters were passed to the function
ClientException – The presences intent is not enabled.
- property roles: list[Role]¶
Returns a
listof the guild’s roles in hierarchy order.The first element of this list will be the lowest role in the hierarchy.
- property rules_channel: TextChannel | None¶
Return’s the guild’s channel used for the rules. The guild must be a Community guild.
If no channel is set, then this returns
None.Added in version 1.3.
- property scheduled_events: list[ScheduledEvent]¶
A list of scheduled events in this guild.
- await search_members(query, *, limit=1000)¶
Search for guild members whose usernames or nicknames start with the query string. Unlike
fetch_members(), this does not requireIntents.members().Note
This method is an API call. For general usage, consider filtering
membersinstead.Added in version 2.6.
- Parameters:
- Returns:
The list of members that have matched the query.
- Return type:
List[
Member]- Raises:
HTTPException – Getting the members failed.
- property self_role: Role | None¶
Gets the role associated with this client’s user, if any.
Added in version 1.6.
- await set_mfa_required(required, *, reason=None)¶
This function is a coroutine.
Set whether it is required to have MFA enabled on your account to perform moderation actions. You must be the guild owner to do this.
- Parameters:
- Raises:
HTTPException – The operation failed.
Forbidden – You are not the owner of the guild.
- Return type:
- property soundboard_limit: int¶
The maximum number of soundboard slots this guild has.
Added in version 2.7.
- property sounds: list[SoundboardSound]¶
A list of soundboard sounds that belong to this guild.
Added in version 2.7.
This is sorted by the position and are in UI order from top to bottom.
- property stage_channels: list[StageChannel]¶
A list of stage channels that belong to this guild.
Added in version 1.7.
This is sorted by the position and are in UI order from top to bottom.
- property stage_instances: list[StageInstance]¶
Returns a
listof the guild’s stage instances that are currently running.Added in version 2.0.
- property sticker_limit: int¶
The maximum number of sticker slots this guild has.
Added in version 2.0.
- property system_channel: TextChannel | None¶
Returns the guild’s channel used for system messages.
If no channel is set, then this returns
None.
- property system_channel_flags: SystemChannelFlags¶
Returns the guild’s system channel settings.
- await templates()¶
This function is a coroutine.
Gets the list of templates from this guild.
Requires
manage_guildpermissions.Added in version 1.7.
- Returns:
The templates for this guild.
- Return type:
List[
Template]- Raises:
Forbidden – You don’t have permissions to get the templates.
- property text_channels: list[TextChannel]¶
A list of text channels that belong to this guild.
This is sorted by the position and are in UI order from top to bottom.
- property threads: list[Thread]¶
A list of threads that you have permission to view.
Added in version 2.0.
- await unban(user, *, reason=None)¶
This function is a coroutine.
Unbans a user from the guild.
The user must meet the
abc.Snowflakeabc.You must have the
ban_memberspermission to do this.- Parameters:
user (
abc.Snowflake) – The user to unban.reason (Optional[
str]) – The reason for doing this action. Shows up on the audit log.
- Raises:
Forbidden – You do not have the proper permissions to unban.
HTTPException – Unbanning failed.
- Return type:
- await vanity_invite()¶
This function is a coroutine.
Returns the guild’s special vanity invite.
The guild must have
VANITY_URLinfeatures.You must have the
manage_guildpermission to use this as well.- Returns:
The special vanity invite. If
Nonethen the guild does not have a vanity invite set.- Return type:
Optional[
Invite]- Raises:
Forbidden – You do not have the proper permissions to get this.
HTTPException – Retrieving the vanity invite failed.
- property voice_channels: list[VoiceChannel]¶
A list of voice channels that belong to this guild.
This is sorted by the position and are in UI order from top to bottom.
- property voice_client: VoiceClient | None¶
Returns the
VoiceClientassociated with this guild, if any.
- await webhooks()¶
This function is a coroutine.
Gets the list of webhooks from this guild.
Requires
manage_webhookspermissions.- Returns:
The webhooks for this guild.
- Return type:
List[
Webhook]- Raises:
Forbidden – You don’t have permissions to get the webhooks.
- await welcome_screen()¶
This function is a coroutine.
Returns the
WelcomeScreenof the guild.The guild must have
COMMUNITYinfeatures.You must have the
manage_guildpermission in order to get this.Added in version 2.0.
- Returns:
The welcome screen of guild.
- Return type:
WelcomeScreen- Raises:
Forbidden – You do not have the proper permissions to get this.
HTTPException – Retrieving the welcome screen failed somehow.
NotFound – The guild doesn’t have a welcome screen or community feature is disabled.
- await widget()¶
This function is a coroutine.
Returns the widget of the guild.
Note
The guild must have the widget enabled to get this information.
- Returns:
The guild’s widget.
- Return type:
Widget- Raises:
Forbidden – The widget for this guild is disabled.
HTTPException – Retrieving the widget failed.
- class discord.events.GuildAvailable[source]¶
Called when a guild becomes available.
The guild must have existed in the client’s cache. This requires
Intents.guildsto be enabled.This event inherits from
Guild.- await active_threads()¶
This function is a coroutine.
Returns a list of active
Threadthat the client can access.This includes both private and public threads.
Added in version 2.0.
- Returns:
The active threads
- Return type:
List[
Thread]- Raises:
HTTPException – The request to get the active threads failed.
- await audit_logs(*, limit=100, before=None, after=None, user=None, action=None)¶
Returns an
AsyncIteratorthat enables receiving the guild’s audit logs.You must have the
view_audit_logpermission to use this.See API documentation for more information about the before and after parameters.
- Parameters:
limit (Optional[
int]) – The number of entries to retrieve. IfNoneretrieve all entries.before (Union[
abc.Snowflake,datetime.datetime]) – Retrieve entries before this date or entry. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.after (Union[
abc.Snowflake,datetime.datetime]) – Retrieve entries after this date or entry. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.user (
abc.Snowflake) – The moderator to filter entries from.action (
AuditLogAction) – The action to filter with.
- Yields:
AuditLogEntry– The audit log entry.- Raises:
Forbidden – You are not allowed to fetch audit logs
HTTPException – An error occurred while fetching the audit logs.
- Return type:
AuditLogIterator
Examples
Getting the first 100 entries:
async for entry in guild.audit_logs(limit=100): print(f"{entry.user} did {entry.action} to {await entry.get_target()}")
Getting entries for a specific action:
async for entry in guild.audit_logs(action=discord.AuditLogAction.ban): print(f"{entry.user} banned {await entry.get_target()}")
Getting entries made by a specific user:
entries = await guild.audit_logs(limit=None, user=guild.me).flatten() await channel.send(f"I made {len(entries)} moderation actions.")
- await ban(user, *, delete_message_seconds=None, reason=None)¶
This function is a coroutine.
Bans a user from the guild.
The user must meet the
abc.Snowflakeabc.You must have the
ban_memberspermission to do this.- Parameters:
user (
abc.Snowflake) – The user to ban from their guild.delete_message_seconds (Optional[
int]) – The number of seconds worth of messages to delete from the user in the guild. The minimum is 0 and the maximum is 604800 (i.e. 7 days). The default is 0.reason (Optional[
str]) – The reason the user got banned.
- Raises:
Forbidden – You do not have the proper permissions to ban.
HTTPException – Banning failed.
- Return type:
- bans(limit=None, before=None, after=None)¶
This function is a coroutine.
Retrieves an
AsyncIteratorthat enables receiving the guild’s bans. In order to use this, you must have theban_memberspermission. Users will always be returned in ascending order sorted by user ID. If both thebeforeandafterparameters are provided, only before is respected.Changed in version 2.5: The
before. andafterparameters were changed. They are now of the typeabc.Snowflakeinstead of SnowflakeTime to comply with the discord api.Changed in version 2.0: The
limit,before. andafterparameters were added. Now returns aBanIteratorinstead of a list ofBanEntryobjects.All parameters are optional.
- Parameters:
limit (Optional[
int]) – The number of bans to retrieve. Defaults to 1000.before (Optional[
abc.Snowflake]) – Retrieve bans before the given user.after (Optional[
abc.Snowflake]) – Retrieve bans after the given user.
- Yields:
BanEntry– The ban entry for the ban.- Raises:
Forbidden – You do not have proper permissions to get the information.
HTTPException – An error occurred while fetching the information.
- Return type:
BanIterator
Examples
Usage
async for ban in guild.bans(limit=150): print(ban.user.name)
Flattening into a list
bans = await guild.bans(limit=150).flatten() # bans is now a list of BanEntry...
- await bulk_ban(*users, delete_message_seconds=None, reason=None)¶
This function is a coroutine.
Bulk ban users from the guild.
The users must meet the
abc.Snowflakeabc.You must have the
ban_memberspermission to do this.Example Usage:
# Ban multiple users successes, failures = await guild.bulk_ban(user1, user2, user3, ..., reason="Raid") # Ban a list of users successes, failures = await guild.bulk_ban(*users)
- Parameters:
*users (
abc.Snowflake) – An argument list of users to ban from the guild, up to 200.delete_message_seconds (Optional[
int]) – The number of seconds worth of messages to delete from the user in the guild. The minimum is 0 and the maximum is 604800 (i.e. 7 days). The default is 0.reason (Optional[
str]) – The reason the users were banned.
- Returns:
Returns two lists: the first contains members that were successfully banned, while the second is members that could not be banned.
- Return type:
Tuple[List[
abc.Snowflake], List[abc.Snowflake]]- Raises:
ValueError – You tried to ban more than 200 users.
Forbidden – You do not have the proper permissions to ban.
HTTPException – No users were banned.
- by_category()¶
Returns every
CategoryChanneland their associated channels.These channels and categories are sorted in the official Discord UI order.
If the channels do not have a category, then the first element of the tuple is
None.- Returns:
The categories and their associated channels.
- Return type:
List[Tuple[Optional[
CategoryChannel], List[abc.GuildChannel]]]
- property categories: list[CategoryChannel]¶
A list of categories that belong to this guild.
This is sorted by the position and are in UI order from top to bottom.
- await change_voice_state(*, channel, self_mute=False, self_deaf=False)¶
This function is a coroutine.
Changes client’s voice state in the guild.
Added in version 1.4.
- await chunk(*, cache=True)¶
This function is a coroutine.
Requests all members that belong to this guild. In order to use this,
Intents.members()must be enabled.This is a websocket operation and can be slow.
Added in version 1.5.
- Parameters:
cache (
bool) – Whether to cache the members as well.- Raises:
ClientException – The members intent is not enabled.
- Return type:
- await create_auto_moderation_rule(*, name, event_type, trigger_type, trigger_metadata, actions, enabled=False, exempt_roles=None, exempt_channels=None, reason=None)¶
Creates an auto moderation rule.
- Parameters:
name (
str) – The name of the auto moderation rule.event_type (
AutoModEventType) – The type of event that triggers the rule.trigger_type (
AutoModTriggerType) – The rule’s trigger type.trigger_metadata (
AutoModTriggerMetadata) – The rule’s trigger metadata.actions (List[
AutoModAction]) – The actions to take when the rule is triggered.enabled (
bool) – Whether the rule is enabled.exempt_roles (List[
abc.Snowflake]) – A list of roles that are exempt from the rule.exempt_channels (List[
abc.Snowflake]) – A list of channels that are exempt from the rule.reason (Optional[
str]) – The reason for creating the rule. Shows up in the audit log.
- Returns:
The new auto moderation rule.
- Return type:
AutoModRule- Raises:
HTTPException – Creating the auto moderation rule failed.
Forbidden – You do not have the Manage Guild permission.
- await create_category(name, *, overwrites=Undefined.MISSING, reason=None, position=Undefined.MISSING)¶
This function is a coroutine.
Same as
create_text_channel()except makes aCategoryChannelinstead.Note
The
categoryparameter is not supported in this function since categories cannot have categories.- Returns:
The channel that was just created.
- Return type:
CategoryChannel- Raises:
Forbidden – You do not have the proper permissions to create this channel.
HTTPException – Creating the channel failed.
InvalidArgument – The permission overwrite information is not in proper form.
- Parameters:
- await create_category_channel(name, *, overwrites=Undefined.MISSING, reason=None, position=Undefined.MISSING)¶
This function is a coroutine.
Same as
create_text_channel()except makes aCategoryChannelinstead.Note
The
categoryparameter is not supported in this function since categories cannot have categories.- Returns:
The channel that was just created.
- Return type:
CategoryChannel- Raises:
Forbidden – You do not have the proper permissions to create this channel.
HTTPException – Creating the channel failed.
InvalidArgument – The permission overwrite information is not in proper form.
- Parameters:
- await create_custom_emoji(*, name, image, roles=Undefined.MISSING, reason=None)¶
This function is a coroutine.
Creates a custom
GuildEmojifor the guild.There is currently a limit of 50 static and animated emojis respectively per guild, unless the guild has the
MORE_EMOJIfeature which extends the limit to 200.You must have the
manage_emojispermission to do this.- Parameters:
name (
str) – The emoji name. Must be at least 2 characters.image (
bytes) – The bytes-like object representing the image data to use. Only JPG, PNG and GIF images are supported.roles (List[
Role]) – AlistofRoles that can use this emoji. Leave empty to make it available to everyone.reason (Optional[
str]) – The reason for creating this emoji. Shows up on the audit log.
- Raises:
Forbidden – You are not allowed to create emojis.
HTTPException – An error occurred creating an emoji.
- Returns:
The created emoji.
- Return type:
GuildEmoji
- await create_forum_channel(name, *, reason=None, category=None, position=Undefined.MISSING, topic=Undefined.MISSING, slowmode_delay=Undefined.MISSING, nsfw=Undefined.MISSING, overwrites=Undefined.MISSING, default_reaction_emoji=Undefined.MISSING, available_tags=Undefined.MISSING, default_sort_order=Undefined.MISSING, default_thread_slowmode_delay=Undefined.MISSING, default_auto_archive_duration=Undefined.MISSING)¶
This function is a coroutine.
Creates a
ForumChannelfor the guild.Note that you need the
manage_channelspermission to create the channel.The
overwritesparameter can be used to create a ‘secret’ channel upon creation. This parameter expects adictof overwrites with the target (either aMemberor aRole) as the key and aPermissionOverwriteas the value.Note
Creating a channel of a specified position will not update the position of other channels to follow suit. A follow-up call to
edit()will be required to update the position of the channel in the channel list.- Parameters:
name (
str) – The channel’s name.overwrites (Dict[Union[
Role,Member,Snowflake],PermissionOverwrite]) – The overwrites to apply to the channel. Useful for creating secret channels.category (Optional[
CategoryChannel]) – The category to place the newly created channel under. The permissions will be automatically synced to category if no overwrites are provided.position (
int) – The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0.topic (
str) – The new channel’s topic.slowmode_delay (
int) – Specifies the slowmode rate limit for user in this channel, in seconds. A value of0disables slowmode. The maximum value possible is21600.nsfw (
bool) – Whether the channel is marked as NSFW.reason (Optional[
str]) – The reason for creating this channel. Shows up on the audit log.default_reaction_emoji (Optional[
GuildEmoji|int|str]) –The default reaction emoji. Can be a unicode emoji or a custom emoji in the forms:
GuildEmoji, snowflake ID, string representation (eg. ‘<a:emoji_name:emoji_id>’).Added in version v2.5.
available_tags (List[
ForumTag]) –The set of tags that can be used in a forum channel.
Added in version 2.7.
default_sort_order (Optional[
SortOrder]) –The default sort order type used to order posts in this channel.
Added in version 2.7.
default_thread_slowmode_delay (Optional[
int]) –The initial slowmode delay to set on newly created threads in this channel.
Added in version 2.7.
default_auto_archive_duration (
int) –The default auto archive duration in minutes for threads created in this channel.
Added in version 2.7.
- Returns:
The channel that was just created.
- Return type:
ForumChannel- Raises:
Forbidden – You do not have the proper permissions to create this channel.
HTTPException – Creating the channel failed.
InvalidArgument – The argument is not in proper form.
Examples
Creating a basic channel:
channel = await guild.create_forum_channel("cool-channel")
Creating a “secret” channel:
overwrites = { guild.default_role: discord.PermissionOverwrite(read_messages=False), guild.me: discord.PermissionOverwrite(read_messages=True), } channel = await guild.create_forum_channel("secret", overwrites=overwrites)
- await create_integration(*, type, id)¶
This function is a coroutine.
Attaches an integration to the guild.
You must have the
manage_guildpermission to do this.Added in version 1.4.
- Parameters:
- Raises:
Forbidden – You do not have permission to create the integration.
HTTPException – The account could not be found.
- Return type:
- await create_role(*, name=Undefined.MISSING, permissions=Undefined.MISSING, color=Undefined.MISSING, colour=Undefined.MISSING, colors=Undefined.MISSING, colours=Undefined.MISSING, holographic=Undefined.MISSING, hoist=Undefined.MISSING, mentionable=Undefined.MISSING, reason=None, icon=Undefined.MISSING, unicode_emoji=Undefined.MISSING)¶
This function is a coroutine.
Creates a
Rolefor the guild.All fields are optional.
You must have the
manage_rolespermission to do this.Changed in version 1.6: Can now pass
inttocolourkeyword-only parameter.- Parameters:
name (
str) – The role name. Defaults to ‘new role’.permissions (
Permissions) – The permissions to have. Defaults to no permissions.colour (Union[
Colour,int]) – The colour for the role. Defaults toColour.default(). This is aliased tocoloras well.hoist (
bool) – Indicates if the role should be shown separately in the member list. Defaults toFalse.mentionable (
bool) – Indicates if the role should be mentionable by others. Defaults toFalse.reason (Optional[
str]) – The reason for creating this role. Shows up on the audit log.icon (Optional[
bytes]) – A bytes-like object representing the icon. Only PNG/JPEG/WebP is supported. If this argument is passed,unicode_emojiis set to None. Only available to guilds that containROLE_ICONSinGuild.features.unicode_emoji (Optional[
str]) – The role’s unicode emoji. If this argument is passed,iconis set to None. Only available to guilds that containROLE_ICONSinGuild.features.color (Colour | int | utils.Undefined)
colors (RoleColours | utils.Undefined)
colours (RoleColours | utils.Undefined)
holographic (bool | utils.Undefined)
- Returns:
The newly created role.
- Return type:
Role- Raises:
Forbidden – You do not have permissions to create the role.
HTTPException – Creating the role failed.
InvalidArgument – An invalid keyword argument was given.
- await create_scheduled_event(*, name, description=Undefined.MISSING, start_time, end_time=Undefined.MISSING, location, privacy_level=ScheduledEventPrivacyLevel.guild_only, reason=None, image=Undefined.MISSING)¶
This function is a coroutine. Creates a scheduled event.
- Parameters:
name (
str) – The name of the scheduled event.description (Optional[
str]) – The description of the scheduled event.start_time (
datetime.datetime) – A datetime object of when the scheduled event is supposed to start.end_time (Optional[
datetime.datetime]) – A datetime object of when the scheduled event is supposed to end.location (
ScheduledEventLocation) – The location of where the event is happening.privacy_level (
ScheduledEventPrivacyLevel) – The privacy level of the event. Currently, the only possible value isScheduledEventPrivacyLevel.guild_only, which is default, so there is no need to change this parameter.reason (Optional[
str]) – The reason to show in the audit log.image (Optional[
bytes]) – The cover image of the scheduled event
- Returns:
The created scheduled event.
- Return type:
Optional[
ScheduledEvent]- Raises:
Forbidden – You do not have the Manage Events permission.
HTTPException – The operation failed.
- await create_sound(name, sound, volume=1.0, emoji=None, reason=None)¶
This function is a coroutine. Creates a
SoundboardSoundin the guild. You must havePermissions.manage_expressionspermission to use this.Added in version 2.7.
- Parameters:
name (
str) – The name of the sound.sound (
bytes) – The bytes-like object representing the sound data. Only MP3 sound files that are less than 5.2 seconds long are supported.volume (
float) – The volume of the sound. Defaults to 1.0.emoji (Optional[Union[
PartialEmoji,GuildEmoji,str]]) – The emoji of the sound.reason (Optional[
str]) – The reason for creating this sound. Shows up on the audit log.
- Returns:
The created sound.
- Return type:
SoundboardSound- Raises:
HTTPException – Creating the sound failed.
Forbidden – You do not have permissions to create sounds.
- await create_stage_channel(name, *, topic, position=Undefined.MISSING, overwrites=Undefined.MISSING, category=None, reason=None, bitrate=Undefined.MISSING, user_limit=Undefined.MISSING, rtc_region=Undefined.MISSING, video_quality_mode=Undefined.MISSING, slowmode_delay=Undefined.MISSING, nsfw=Undefined.MISSING)¶
This function is a coroutine.
This is similar to
create_text_channel()except makes aStageChannelinstead.Added in version 1.7.
- Parameters:
name (
str) – The channel’s name.topic (
str) – The new channel’s topic.overwrites (Dict[Union[
Role,Member,Snowflake],PermissionOverwrite]) – The overwrites to apply to the channel. Useful for creating secret channels.category (Optional[
CategoryChannel]) – The category to place the newly created channel under. The permissions will be automatically synced to category if no overwrites are provided.position (
int) – The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0.reason (Optional[
str]) – The reason for creating this channel. Shows up on the audit log.bitrate (
int) –The channel’s preferred audio bitrate in bits per second.
Added in version 2.7.
user_limit (
int) –The channel’s limit for number of members that can be in a voice channel.
Added in version 2.7.
rtc_region (Optional[
VoiceRegion]) –The region for the voice channel’s voice communication. A value of
Noneindicates automatic voice region detection.Added in version 2.7.
video_quality_mode (
VideoQualityMode) –The camera video quality for the voice channel’s participants.
Added in version 2.7.
slowmode_delay (
int) –Specifies the slowmode rate limit for user in this channel, in seconds. A value of
0disables slowmode. The maximum value possible is21600.Added in version 2.7.
nsfw (
bool) –Whether the channel is marked as NSFW.
Added in version 2.7.
- Returns:
The channel that was just created.
- Return type:
StageChannel- Raises:
Forbidden – You do not have the proper permissions to create this channel.
HTTPException – Creating the channel failed.
InvalidArgument – The permission overwrite information is not in proper form.
- await create_sticker(*, name, description=None, emoji, file, reason=None)¶
This function is a coroutine.
Creates a
Stickerfor the guild.You must have
manage_emojis_and_stickerspermission to do this.Added in version 2.0.
- Parameters:
name (
str) – The sticker name. Must be 2 to 30 characters.description (Optional[
str]) – The sticker’s description. If used, must be 2 to 100 characters.emoji (
str) – The name of a unicode emoji that represents the sticker’s expression.file (
File) – The file of the sticker to upload.reason (
str) – The reason for creating this sticker. Shows up on the audit log.
- Returns:
The created sticker.
- Return type:
GuildSticker- Raises:
Forbidden – You are not allowed to create stickers.
HTTPException – An error occurred creating a sticker.
TypeError – The parameters for the sticker are not correctly formatted.
- await create_template(*, name, description=Undefined.MISSING)¶
This function is a coroutine.
Creates a template for the guild.
You must have the
manage_guildpermission to do this.Added in version 1.7.
- await create_test_entitlement(sku)¶
This function is a coroutine.
Creates a test entitlement for the guild.
- Parameters:
sku (
Snowflake) – The SKU to create a test entitlement for.- Returns:
The created entitlement.
- Return type:
Entitlement
- await create_text_channel(name, *, reason=None, category=None, position=Undefined.MISSING, topic=Undefined.MISSING, slowmode_delay=Undefined.MISSING, nsfw=Undefined.MISSING, overwrites=Undefined.MISSING, default_thread_slowmode_delay=Undefined.MISSING, default_auto_archive_duration=Undefined.MISSING)¶
This function is a coroutine.
Creates a
TextChannelfor the guild.Note that you need the
manage_channelspermission to create the channel.The
overwritesparameter can be used to create a ‘secret’ channel upon creation. This parameter expects adictof overwrites with the target (either aMemberor aRole) as the key and aPermissionOverwriteas the value.Note
Creating a channel of a specified position will not update the position of other channels to follow suit. A follow-up call to
edit()will be required to update the position of the channel in the channel list.- Parameters:
name (
str) – The channel’s name.overwrites (Dict[Union[
Role,Member,Snowflake],PermissionOverwrite]) – The overwrites to apply to the channel. Useful for creating secret channels.category (Optional[
CategoryChannel]) – The category to place the newly created channel under. The permissions will be automatically synced to category if no overwrites are provided.position (
int) – The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0.topic (
str) – The new channel’s topic.slowmode_delay (
int) – Specifies the slowmode rate limit for user in this channel, in seconds. A value of 0 disables slowmode. The maximum value possible is 21600.nsfw (
bool) – Whether the channel is marked as NSFW.reason (Optional[
str]) – The reason for creating this channel. Shows up on the audit log.default_thread_slowmode_delay (Optional[
int]) –The initial slowmode delay to set on newly created threads in this channel.
Added in version 2.7.
default_auto_archive_duration (
int) –The default auto archive duration in minutes for threads created in this channel.
Added in version 2.7.
- Returns:
The channel that was just created.
- Return type:
TextChannel- Raises:
Forbidden – You do not have the proper permissions to create this channel.
HTTPException – Creating the channel failed.
InvalidArgument – The permission overwrite information is not in proper form.
Examples
Creating a basic channel:
channel = await guild.create_text_channel("cool-channel")
Creating a “secret” channel:
overwrites = { guild.default_role: discord.PermissionOverwrite(read_messages=False), guild.me: discord.PermissionOverwrite(read_messages=True), } channel = await guild.create_text_channel("secret", overwrites=overwrites)
- await create_voice_channel(name, *, reason=None, category=None, position=Undefined.MISSING, bitrate=Undefined.MISSING, user_limit=Undefined.MISSING, rtc_region=Undefined.MISSING, video_quality_mode=Undefined.MISSING, overwrites=Undefined.MISSING, slowmode_delay=Undefined.MISSING, nsfw=Undefined.MISSING)¶
This function is a coroutine.
This is similar to
create_text_channel()except makes aVoiceChannelinstead.- Parameters:
name (
str) – The channel’s name.overwrites (Dict[Union[
Role,Member,Snowflake],PermissionOverwrite]) – The overwrites to apply to the channel. Useful for creating secret channels.category (Optional[
CategoryChannel]) – The category to place the newly created channel under. The permissions will be automatically synced to category if no overwrites are provided.position (
int) – The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0.bitrate (
int) – The channel’s preferred audio bitrate in bits per second.user_limit (
int) – The channel’s limit for number of members that can be in a voice channel.rtc_region (Optional[
VoiceRegion]) –The region for the voice channel’s voice communication. A value of
Noneindicates automatic voice region detection.Added in version 1.7.
video_quality_mode (
VideoQualityMode) –The camera video quality for the voice channel’s participants.
Added in version 2.0.
reason (Optional[
str]) – The reason for creating this channel. Shows up on the audit log.slowmode_delay (
int) –Specifies the slowmode rate limit for user in this channel, in seconds. A value of
0disables slowmode. The maximum value possible is21600.Added in version 2.7.
nsfw (
bool) –Whether the channel is marked as NSFW.
Added in version 2.7.
- Returns:
The channel that was just created.
- Return type:
VoiceChannel- Raises:
Forbidden – You do not have the proper permissions to create this channel.
HTTPException – Creating the channel failed.
InvalidArgument – The permission overwrite information is not in proper form.
- await delete()¶
This function is a coroutine.
Deletes the guild. You must be the guild owner to delete the guild.
- Raises:
HTTPException – Deleting the guild failed.
Forbidden – You do not have permissions to delete the guild.
- Return type:
- await delete_auto_moderation_rule(id, *, reason=None)¶
Deletes an auto moderation rule.
- Parameters:
- Raises:
HTTPException – Deleting the auto moderation rule failed.
Forbidden – You do not have the Manage Guild permission.
- Return type:
- await delete_emoji(emoji, *, reason=None)¶
This function is a coroutine.
Deletes the custom
GuildEmojifrom the guild.You must have
manage_emojispermission to do this.- Parameters:
emoji (
abc.Snowflake) – The emoji you are deleting.reason (Optional[
str]) – The reason for deleting this emoji. Shows up on the audit log.
- Raises:
Forbidden – You are not allowed to delete emojis.
HTTPException – An error occurred deleting the emoji.
- Return type:
- await delete_sticker(sticker, *, reason=None)¶
This function is a coroutine.
Deletes the custom
Stickerfrom the guild.You must have
manage_emojis_and_stickerspermission to do this.Added in version 2.0.
- Parameters:
sticker (
abc.Snowflake) – The sticker you are deleting.reason (Optional[
str]) – The reason for deleting this sticker. Shows up on the audit log.
- Raises:
Forbidden – You are not allowed to delete stickers.
HTTPException – An error occurred deleting the sticker.
- Return type:
- await edit(*, reason=Undefined.MISSING, name=Undefined.MISSING, description=Undefined.MISSING, icon=Undefined.MISSING, banner=Undefined.MISSING, splash=Undefined.MISSING, discovery_splash=Undefined.MISSING, community=Undefined.MISSING, afk_channel=Undefined.MISSING, owner=Undefined.MISSING, afk_timeout=Undefined.MISSING, default_notifications=Undefined.MISSING, verification_level=Undefined.MISSING, explicit_content_filter=Undefined.MISSING, system_channel=Undefined.MISSING, system_channel_flags=Undefined.MISSING, preferred_locale=Undefined.MISSING, rules_channel=Undefined.MISSING, public_updates_channel=Undefined.MISSING, premium_progress_bar_enabled=Undefined.MISSING, disable_invites=Undefined.MISSING, discoverable=Undefined.MISSING, disable_raid_alerts=Undefined.MISSING, enable_activity_feed=Undefined.MISSING)¶
This function is a coroutine.
Edits the guild.
You must have the
manage_guildpermission to edit the guild.Changed in version 1.4: The rules_channel and public_updates_channel keyword-only parameters were added.
Changed in version 2.0: The discovery_splash and community keyword-only parameters were added.
Changed in version 2.0: The newly updated guild is returned.
- Parameters:
name (
str) – The new name of the guild.description (Optional[
str]) – The new description of the guild. Could beNonefor no description. This is only available to guilds that containPUBLICinGuild.features.icon (
bytes) – A bytes-like object representing the icon. Only PNG/JPEG is supported. GIF is only available to guilds that containANIMATED_ICONinGuild.features. Could beNoneto denote removal of the icon.banner (
bytes) – A bytes-like object representing the banner. Could beNoneto denote removal of the banner. This is only available to guilds that containBANNERinGuild.features.splash (
bytes) – A bytes-like object representing the invite splash. Only PNG/JPEG supported. Could beNoneto denote removing the splash. This is only available to guilds that containINVITE_SPLASHinGuild.features.discovery_splash (
bytes) – A bytes-like object representing the discovery splash. Only PNG/JPEG supported. Could beNoneto denote removing the splash. This is only available to guilds that containDISCOVERABLEinGuild.features.community (
bool) – Whether the guild should be a Community guild. If set toTrue, bothrules_channelandpublic_updates_channelparameters are required.afk_channel (Optional[
VoiceChannel]) – The new channel that is the AFK channel. Could beNonefor no AFK channel.afk_timeout (
int) – The number of seconds until someone is moved to the AFK channel.owner (
Member) – The new owner of the guild to transfer ownership to. Note that you must be owner of the guild to do this.verification_level (
VerificationLevel) – The new verification level for the guild.default_notifications (
NotificationLevel) – The new default notification level for the guild.explicit_content_filter (
ContentFilter) – The new explicit content filter for the guild.system_channel (Optional[
TextChannel]) – The new channel that is used for the system channel. Could beNonefor no system channel.system_channel_flags (
SystemChannelFlags) – The new system channel settings to use with the new system channel.preferred_locale (
str) – The new preferred locale for the guild. Used as the primary language in the guild. If set, this must be an ISO 639 code, e.g.en-USorjaorzh-CN.rules_channel (Optional[
TextChannel]) – The new channel that is used for rules. This is only available to guilds that containPUBLICinGuild.features. Could beNonefor no rules channel.public_updates_channel (Optional[
TextChannel]) – The new channel that is used for public updates from Discord. This is only available to guilds that containPUBLICinGuild.features. Could beNonefor no public updates channel.premium_progress_bar_enabled (
bool) – Whether the guild should have premium progress bar enabled.disable_invites (
bool) – Whether the guild should have server invites enabled or disabled.discoverable (
bool) – Whether the guild should be discoverable in the discover tab.disable_raid_alerts (
bool) – Whether activity alerts for the guild should be disabled.enable_activity_feed (class:bool) – Whether the guild’s user activity feed should be enabled.
reason (Optional[
str]) – The reason for editing this guild. Shows up on the audit log.
- Raises:
Forbidden – You do not have permissions to edit the guild.
HTTPException – Editing the guild failed.
InvalidArgument – The image format passed in to
iconis invalid. It must be PNG or JPG. This is also raised if you are not the owner of the guild and request an ownership transfer.
- Returns:
The newly updated guild. Note that this has the same limitations as mentioned in
Client.fetch_guild()and may not have full data.- Return type:
Guild
- await edit_onboarding(*, prompts=Undefined.MISSING, default_channels=Undefined.MISSING, enabled=Undefined.MISSING, mode=Undefined.MISSING, reason=Undefined.MISSING)¶
This function is a coroutine.
A shorthand for
Onboarding.editwithout fetching the onboarding flow.You must have the
manage_guildandmanage_rolespermissions in the guild to do this.- Parameters:
prompts (Optional[List[
OnboardingPrompt]]) – The new list of prompts for this flow.default_channels (Optional[List[
Snowflake]]) – The new default channels that users are opted into.enabled (Optional[
bool]) – Whether onboarding should be enabled. Setting this toTruerequires the guild to haveCOMMUNITYinfeaturesand at least 7default_channels.mode (Optional[
OnboardingMode]) – The new onboarding mode.reason (Optional[
str]) – The reason that shows up on Audit log.
- Returns:
The updated onboarding flow.
- Return type:
Onboarding- Raises:
HTTPException – Editing the onboarding flow failed somehow.
Forbidden – You don’t have permissions to edit the onboarding flow.
- await edit_role_positions(positions, *, reason=None)¶
This function is a coroutine.
Bulk edits a list of
Rolein the guild.You must have the
manage_rolespermission to do this.Added in version 1.4.
Example:
positions = { bots_role: 1, # penultimate role tester_role: 2, admin_role: 6, } await guild.edit_role_positions(positions=positions)
- Parameters:
- Returns:
A list of all the roles in the guild.
- Return type:
List[
Role]- Raises:
Forbidden – You do not have permissions to move the roles.
HTTPException – Moving the roles failed.
InvalidArgument – An invalid keyword argument was given.
- await edit_welcome_screen(**options)¶
This function is a coroutine.
A shorthand for
WelcomeScreen.editwithout fetching the welcome screen.You must have the
manage_guildpermission in the guild to do this.The guild must have
COMMUNITYinGuild.features- Parameters:
description (Optional[
str]) – The new description of welcome screen.welcome_channels (Optional[List[
WelcomeScreenChannel]]) – The welcome channels. The order of the channels would be same as the passed list order.enabled (Optional[
bool]) – Whether the welcome screen should be displayed.reason (Optional[
str]) – The reason that shows up on audit log.
- Returns:
The edited welcome screen.
- Return type:
WelcomeScreen- Raises:
HTTPException – Editing the welcome screen failed somehow.
Forbidden – You don’t have permissions to edit the welcome screen.
NotFound – This welcome screen does not exist.
- await edit_widget(*, enabled=Undefined.MISSING, channel=Undefined.MISSING)¶
This function is a coroutine.
Edits the widget of the guild.
You must have the
manage_guildpermission to use thisAdded in version 2.0.
- Parameters:
- Raises:
Forbidden – You do not have permission to edit the widget.
HTTPException – Editing the widget failed.
- Return type:
- entitlements(skus=None, before=None, after=None, limit=100, exclude_ended=False)¶
Returns an
AsyncIteratorthat enables fetching the guild’s entitlements.This is identical to
Client.entitlements()with theguildparameter.Added in version 2.6.
- Parameters:
skus (list[
abc.Snowflake] | None) – Limit the fetched entitlements to entitlements that are for these SKUs.before (
abc.Snowflake|datetime.datetime| None) – Retrieves guilds before this date or object. If a datetime is provided, it is recommended to use a UTC-aware datetime. If the datetime is naive, it is assumed to be local time.after (
abc.Snowflake|datetime.datetime| None) – Retrieve guilds after this date or object. If a datetime is provided, it is recommended to use a UTC-aware datetime. If the datetime is naive, it is assumed to be local time.limit (Optional[
int]) – The number of entitlements to retrieve. IfNone, retrieves every entitlement, which may be slow. Defaults to100.exclude_ended (
bool) – Whether to limit the fetched entitlements to those that have not ended. Defaults toFalse.
- Yields:
Entitlement– The application’s entitlements.- Raises:
HTTPException – Retrieving the entitlements failed.
- Return type:
EntitlementIterator
- await estimate_pruned_members(*, days, roles=Undefined.MISSING)¶
This function is a coroutine.
Similar to
prune_members()except instead of actually pruning members, it returns how many members it would prune from the guild had it been called.- Parameters:
days (
int) – The number of days before counting as inactive.roles (List[
abc.Snowflake]) –A list of
abc.Snowflakethat represent roles to include in the estimate. If a member has a role that is not specified, they’ll be excluded.Added in version 1.7.
- Returns:
The number of members estimated to be pruned.
- Return type:
- Raises:
Forbidden – You do not have permissions to prune members.
HTTPException – An error occurred while fetching the prune members estimate.
InvalidArgument – An integer was not passed for
days.
- await fetch_auto_moderation_rule(id)¶
This function is a coroutine.
Retrieves a
AutoModRulefrom rule ID.- Returns:
The requested auto moderation rule.
- Return type:
AutoModRule- Raises:
HTTPException – Getting the auto moderation rule failed.
Forbidden – You do not have the Manage Guild permission.
- Parameters:
id (
int)
- await fetch_auto_moderation_rules()¶
This function is a coroutine.
Retrieves a list of auto moderation rules for this guild.
- Returns:
The auto moderation rules for this guild.
- Return type:
List[
AutoModRule]- Raises:
HTTPException – Getting the auto moderation rules failed.
Forbidden – You do not have the Manage Guild permission.
- await fetch_ban(user)¶
This function is a coroutine.
Retrieves the
BanEntryfor a user.You must have the
ban_memberspermission to get this information.- Parameters:
user (
abc.Snowflake) – The user to get ban information from.- Returns:
The
BanEntryobject for the specified user.- Return type:
BanEntry- Raises:
Forbidden – You do not have proper permissions to get the information.
NotFound – This user is not banned.
HTTPException – An error occurred while fetching the information.
- await fetch_channel(channel_id, /)¶
This function is a coroutine.
Retrieves a
abc.GuildChannelorThreadwith the specified ID.Note
This method is an API call. For general usage, consider
get_channel_or_thread()instead.Added in version 2.0.
- Returns:
The channel from the ID.
- Return type:
Union[
abc.GuildChannel,Thread]- Raises:
InvalidData – An unknown channel type was received from Discord or the guild the channel belongs to is not the same as the one in this object points to.
HTTPException – Retrieving the channel failed.
NotFound – Invalid Channel ID.
Forbidden – You do not have permission to fetch this channel.
- Parameters:
channel_id (
int)
- await fetch_channels()¶
This function is a coroutine.
Retrieves all
abc.GuildChannelthat the guild has.Note
This method is an API call. For general usage, consider
channelsinstead.Added in version 1.2.
- Returns:
All channels in the guild.
- Return type:
Sequence[
discord.channel.base.GuildChannel]- Raises:
InvalidData – An unknown channel type was received from Discord.
HTTPException – Retrieving the channels failed.
- await fetch_emoji(emoji_id, /)¶
This function is a coroutine.
Retrieves a custom
GuildEmojifrom the guild.Note
This method is an API call. For general usage, consider iterating over
emojisinstead.- Parameters:
emoji_id (
int) – The emoji’s ID.- Returns:
The retrieved emoji.
- Return type:
GuildEmoji- Raises:
NotFound – The emoji requested could not be found.
HTTPException – An error occurred fetching the emoji.
- await fetch_emojis()¶
This function is a coroutine.
Retrieves all custom
GuildEmojis from the guild.Note
This method is an API call. For general usage, consider
emojisinstead.- Raises:
HTTPException – An error occurred fetching the emojis.
- Returns:
The retrieved emojis.
- Return type:
List[
GuildEmoji]
- await fetch_member(member_id, /)¶
This function is a coroutine.
Retrieves a
Memberfrom a guild ID, and a member ID.Note
This method is an API call. If you have
Intents.membersand member cache enabled, considerget_member()instead.- Parameters:
member_id (
int) – The member’s ID to fetch from.- Returns:
The member from the member ID.
- Return type:
Member- Raises:
Forbidden – You do not have access to the guild.
HTTPException – Fetching the member failed.
- fetch_members(*, limit=1000, after=None)¶
Retrieves an
AsyncIteratorthat enables receiving the guild’s members. In order to use this,Intents.members()must be enabled.Note
This method is an API call. For general usage, consider
membersinstead.Added in version 1.3.
All parameters are optional.
- Parameters:
limit (Optional[
int]) – The number of members to retrieve. Defaults to 1000. PassNoneto fetch all members. Note that this is potentially slow.after (Optional[Union[
abc.Snowflake,datetime.datetime]]) – Retrieve members after this date or object. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.
- Yields:
Member– The member with the member data parsed.- Raises:
ClientException – The members intent is not enabled.
HTTPException – Getting the members failed.
- Return type:
MemberIterator
Examples
Usage
async for member in guild.fetch_members(limit=150): print(member.name)
Flattening into a list
members = await guild.fetch_members(limit=150).flatten() # members is now a list of Member...
- await fetch_role(role_id)¶
This function is a coroutine.
Retrieves a
Rolethat the guild has.Note
This method is an API call. For general usage, consider using
get_roleinstead.Added in version 2.7.
- Returns:
The role in the guild with the specified ID.
- Return type:
Role- Raises:
HTTPException – Retrieving the role failed.
- Parameters:
role_id (
int)
- await fetch_roles()¶
This function is a coroutine.
Retrieves all
Rolethat the guild has.Note
This method is an API call. For general usage, consider
rolesinstead.Added in version 1.3.
- Returns:
All roles in the guild.
- Return type:
List[
Role]- Raises:
HTTPException – Retrieving the roles failed.
- await fetch_scheduled_event(event_id, /, *, with_user_count=True)¶
This function is a coroutine.
Retrieves a
ScheduledEventfrom event ID.Note
This method is an API call. If you have
Intents.scheduled_events, considerget_scheduled_event()instead.- Parameters:
- Returns:
The scheduled event from the event ID.
- Return type:
Optional[
ScheduledEvent]- Raises:
HTTPException – Fetching the event failed.
NotFound – Event not found.
- await fetch_scheduled_events(*, with_user_count=True)¶
This function is a coroutine.
Returns a list of
ScheduledEventin the guild.Note
This method is an API call. For general usage, consider
scheduled_eventsinstead.- Parameters:
with_user_count (Optional[
bool]) – If the scheduled event should be fetched with the number of users that are interested in the events. Defaults toTrue.- Returns:
The fetched scheduled events.
- Return type:
List[
ScheduledEvent]- Raises:
ClientException – The scheduled events intent is not enabled.
HTTPException – Getting the scheduled events failed.
- await fetch_sound(sound_id)¶
This function is a coroutine. Fetches a soundboard sound in the guild.
Added in version 2.7.
- Parameters:
sound_id (
int) – The ID of the sound.- Returns:
The sound.
- Return type:
SoundboardSound
- await fetch_sounds()¶
This function is a coroutine. Fetches all the soundboard sounds in the guild.
Added in version 2.7.
- Returns:
The sounds in the guild.
- Return type:
List[
SoundboardSound]
- await fetch_sticker(sticker_id, /)¶
This function is a coroutine.
Retrieves a custom
Stickerfrom the guild.Added in version 2.0.
Note
This method is an API call. For general usage, consider iterating over
stickersinstead.- Parameters:
sticker_id (
int) – The sticker’s ID.- Returns:
The retrieved sticker.
- Return type:
GuildSticker- Raises:
NotFound – The sticker requested could not be found.
HTTPException – An error occurred fetching the sticker.
- await fetch_stickers()¶
This function is a coroutine.
Retrieves a list of all
Stickers for the guild.Added in version 2.0.
Note
This method is an API call. For general usage, consider
stickersinstead.- Raises:
HTTPException – An error occurred fetching the stickers.
- Returns:
The retrieved stickers.
- Return type:
List[
GuildSticker]
- property filesize_limit: int¶
The maximum number of bytes files can have when uploaded to this guild.
- property forum_channels: list[ForumChannel]¶
A list of forum channels that belong to this guild.
Added in version 2.0.
This is sorted by the position and are in UI order from top to bottom.
- get_channel(channel_id, /)¶
Returns a channel with the given ID.
Note
This does not search for threads.
- Parameters:
channel_id (
int) – The ID to search for.- Returns:
The returned channel or
Noneif not found.- Return type:
Optional[
abc.GuildChannel]
- get_channel_or_thread(channel_id, /)¶
Returns a channel or thread with the given ID.
Added in version 2.0.
- Parameters:
channel_id (
int) – The ID to search for.- Returns:
The returned channel or thread or
Noneif not found.- Return type:
Optional[Union[
Thread,abc.GuildChannel]]
- await get_me()¶
Similar to
Client.userexcept an instance ofMember. This is essentially used to get the member version of yourself.- Return type:
- await get_member(user_id, /)¶
Returns a member with the given ID.
- Parameters:
user_id (
int) – The ID to search for.- Returns:
The member or
Noneif not found.- Return type:
Optional[
Member]
- get_member_named(name, /)¶
Returns the first member found that matches the name provided.
The name can have an optional discriminator argument, e.g. “Jake#0001” or “Jake” will both do the lookup. However, the former will give a more precise result. Note that the discriminator must have all 4 digits for this to work.
If a nickname is passed, then it is looked up via the nickname. Note however, that a nickname + discriminator combo will not look up the nickname but rather the username + discriminator combo due to nickname + discriminator not being unique.
If no member is found,
Noneis returned.- Parameters:
name (
str) – The name of the member to lookup with an optional discriminator.- Returns:
The member in this guild with the associated name. If not found then
Noneis returned.- Return type:
Optional[
Member]
- get_role(role_id, /)¶
Returns a role with the given ID.
- Parameters:
role_id (
int) – The ID to search for.- Returns:
The role or
Noneif not found.- Return type:
Optional[
Role]
- get_scheduled_event(event_id, /)¶
Returns a Scheduled Event with the given ID.
- Parameters:
event_id (
int) – The ID to search for.- Returns:
The scheduled event or
Noneif not found.- Return type:
Optional[
ScheduledEvent]
- get_sound(sound_id)¶
Returns a sound with the given ID.
Added in version 2.7.
- Parameters:
sound_id (
int) – The ID to search for.- Returns:
The sound or
Noneif not found.- Return type:
Optional[
SoundboardSound]
- get_stage_instance(stage_instance_id, /)¶
Returns a stage instance with the given ID.
Added in version 2.0.
- Parameters:
stage_instance_id (
int) – The ID to search for.- Returns:
The stage instance or
Noneif not found.- Return type:
Optional[
StageInstance]
- get_thread(thread_id, /)¶
Returns a thread with the given ID.
Added in version 2.0.
- Parameters:
thread_id (
int) – The ID to search for.- Returns:
The returned thread or
Noneif not found.- Return type:
Optional[
Thread]
- await integrations()¶
This function is a coroutine.
Returns a list of all integrations attached to the guild.
You must have the
manage_guildpermission to do this.Added in version 1.4.
- Returns:
The list of integrations that are attached to the guild.
- Return type:
List[
Integration]- Raises:
Forbidden – You do not have permission to create the integration.
HTTPException – Fetching the integrations failed.
- await invites()¶
This function is a coroutine.
Returns a list of all active instant invites from the guild.
You must have the
manage_guildpermission to get this information.- Returns:
The list of invites that are currently active.
- Return type:
List[
Invite]- Raises:
Forbidden – You do not have proper permissions to get the information.
HTTPException – An error occurred while fetching the information.
- await is_chunked()¶
Returns a boolean indicating if the guild is “chunked”.
A chunked guild means that
member_countis equal to the number of members stored in the internalmemberscache.If this value returns
False, then you should request for offline members.- Return type:
- await is_large()¶
Indicates if the guild is a ‘large’ guild.
A large guild is defined as having more than
large_thresholdcount members, which for this library is set to the maximum of 250.- Return type:
- property jump_url: str¶
Returns a URL that allows the client to jump to the guild.
Added in version 2.0.
- await kick(user, *, reason=None)¶
This function is a coroutine.
Kicks a user from the guild.
The user must meet the
abc.Snowflakeabc.You must have the
kick_memberspermission to do this.- Parameters:
user (
abc.Snowflake) – The user to kick from their guild.reason (Optional[
str]) – The reason the user got kicked.
- Raises:
Forbidden – You do not have the proper permissions to kick.
HTTPException – Kicking failed.
- Return type:
- await leave()¶
This function is a coroutine.
Leaves the guild. :rtype:
NoneNote
You cannot leave the guild that you own, you must delete it instead via
delete().- Raises:
HTTPException – Leaving the guild failed.
- property member_count: int¶
Returns the true member count regardless of it being loaded fully or not.
Warning
Due to a Discord limitation, in order for this attribute to remain up-to-date and accurate, it requires
Intents.membersto be specified.
- await modify_incident_actions(*, invites_disabled_until=Undefined.MISSING, dms_disabled_until=Undefined.MISSING, reason=Undefined.MISSING)¶
This function is a coroutine.
Modify the guild’s incident actions, controlling when invites or DMs are re-enabled after being temporarily disabled. Requires the
manage_guildpermission.- Parameters:
invites_disabled_until (Optional[
datetime.datetime]) – The ISO8601 timestamp indicating when invites will be enabled again, orNoneto enable invites immediately.dms_disabled_until (Optional[
datetime.datetime]) – The ISO8601 timestamp indicating when DMs will be enabled again, orNoneto enable DMs immediately.reason (Optional[
str]) – The reason for this action, used for the audit log.
- Returns:
The updated incidents data for the guild.
- Return type:
IncidentsData
- await onboarding()¶
This function is a coroutine.
Returns the
Onboardingflow for the guild.Added in version 2.5.
- Returns:
The onboarding flow for the guild.
- Return type:
Onboarding- Raises:
HTTPException – Retrieving the onboarding flow failed somehow.
Gets the premium subscriber role, AKA “boost” role, in this guild.
Added in version 1.6.
A list of members who have “boosted” this guild.
- await prune_members(*, days, compute_prune_count=True, roles=Undefined.MISSING, reason=None)¶
This function is a coroutine.
Prunes the guild from its inactive members.
The inactive members are denoted if they have not logged on in
daysnumber of days and have no roles.You must have the
kick_memberspermission to use this.To check how many members you would prune without actually pruning, see the
estimate_pruned_members()function.To prune members that have specific roles see the
rolesparameter.Changed in version 1.4: The
roleskeyword-only parameter was added.- Parameters:
days (
int) – The number of days before counting as inactive.reason (Optional[
str]) – The reason for doing this action. Shows up on the audit log.compute_prune_count (
bool) – Whether to compute the prune count. This defaults toTruewhich makes it prone to timeouts in very large guilds. In order to prevent timeouts, you must set this toFalse. If this is set toFalse, then this function will always returnNone.roles (List[
abc.Snowflake]) – A list ofabc.Snowflakethat represent roles to include in the pruning process. If a member has a role that is not specified, they’ll be excluded.
- Raises:
Forbidden – You do not have permissions to prune members.
HTTPException – An error occurred while pruning members.
InvalidArgument – An integer was not passed for
days.
- Returns:
The number of members pruned. If
compute_prune_countisFalsethen this returnsNone.- Return type:
Optional[
int]
- property public_updates_channel: TextChannel | None¶
Return’s the guild’s channel where admins and moderators of the guilds receive notices from Discord. The guild must be a Community guild.
If no channel is set, then this returns
None.Added in version 1.4.
- await query_members(query=None, *, limit=5, user_ids=None, presences=False, cache=True)¶
This function is a coroutine.
Request members that belong to this guild whose username starts with the query given.
This is a websocket operation and can be slow.
Added in version 1.3.
- Parameters:
query (Optional[
str]) – The string that the username’s start with.user_ids (Optional[List[
int]]) –List of user IDs to search for. If the user ID is not in the guild then it won’t be returned.
Added in version 1.4.
limit (Optional[
int]) – The maximum number of members to send back. If no query is passed, passingNonereturns all members. If aqueryoruser_idsis passed, must be between 1 and 100. Defaults to 5.presences (Optional[
bool]) –Whether to request for presences to be provided. This defaults to
False.Added in version 1.6.
cache (
bool) – Whether to cache the members internally. This makes operations such asget_member()work for those that matched. Defaults toTrue.
- Returns:
The list of members that have matched the query.
- Return type:
List[
Member]- Raises:
asyncio.TimeoutError – The query timed out waiting for the members.
ValueError – Invalid parameters were passed to the function
ClientException – The presences intent is not enabled.
- property roles: list[Role]¶
Returns a
listof the guild’s roles in hierarchy order.The first element of this list will be the lowest role in the hierarchy.
- property rules_channel: TextChannel | None¶
Return’s the guild’s channel used for the rules. The guild must be a Community guild.
If no channel is set, then this returns
None.Added in version 1.3.
- property scheduled_events: list[ScheduledEvent]¶
A list of scheduled events in this guild.
- await search_members(query, *, limit=1000)¶
Search for guild members whose usernames or nicknames start with the query string. Unlike
fetch_members(), this does not requireIntents.members().Note
This method is an API call. For general usage, consider filtering
membersinstead.Added in version 2.6.
- Parameters:
- Returns:
The list of members that have matched the query.
- Return type:
List[
Member]- Raises:
HTTPException – Getting the members failed.
- property self_role: Role | None¶
Gets the role associated with this client’s user, if any.
Added in version 1.6.
- await set_mfa_required(required, *, reason=None)¶
This function is a coroutine.
Set whether it is required to have MFA enabled on your account to perform moderation actions. You must be the guild owner to do this.
- Parameters:
- Raises:
HTTPException – The operation failed.
Forbidden – You are not the owner of the guild.
- Return type:
- property soundboard_limit: int¶
The maximum number of soundboard slots this guild has.
Added in version 2.7.
- property sounds: list[SoundboardSound]¶
A list of soundboard sounds that belong to this guild.
Added in version 2.7.
This is sorted by the position and are in UI order from top to bottom.
- property stage_channels: list[StageChannel]¶
A list of stage channels that belong to this guild.
Added in version 1.7.
This is sorted by the position and are in UI order from top to bottom.
- property stage_instances: list[StageInstance]¶
Returns a
listof the guild’s stage instances that are currently running.Added in version 2.0.
- property sticker_limit: int¶
The maximum number of sticker slots this guild has.
Added in version 2.0.
- property system_channel: TextChannel | None¶
Returns the guild’s channel used for system messages.
If no channel is set, then this returns
None.
- property system_channel_flags: SystemChannelFlags¶
Returns the guild’s system channel settings.
- await templates()¶
This function is a coroutine.
Gets the list of templates from this guild.
Requires
manage_guildpermissions.Added in version 1.7.
- Returns:
The templates for this guild.
- Return type:
List[
Template]- Raises:
Forbidden – You don’t have permissions to get the templates.
- property text_channels: list[TextChannel]¶
A list of text channels that belong to this guild.
This is sorted by the position and are in UI order from top to bottom.
- property threads: list[Thread]¶
A list of threads that you have permission to view.
Added in version 2.0.
- await unban(user, *, reason=None)¶
This function is a coroutine.
Unbans a user from the guild.
The user must meet the
abc.Snowflakeabc.You must have the
ban_memberspermission to do this.- Parameters:
user (
abc.Snowflake) – The user to unban.reason (Optional[
str]) – The reason for doing this action. Shows up on the audit log.
- Raises:
Forbidden – You do not have the proper permissions to unban.
HTTPException – Unbanning failed.
- Return type:
- await vanity_invite()¶
This function is a coroutine.
Returns the guild’s special vanity invite.
The guild must have
VANITY_URLinfeatures.You must have the
manage_guildpermission to use this as well.- Returns:
The special vanity invite. If
Nonethen the guild does not have a vanity invite set.- Return type:
Optional[
Invite]- Raises:
Forbidden – You do not have the proper permissions to get this.
HTTPException – Retrieving the vanity invite failed.
- property voice_channels: list[VoiceChannel]¶
A list of voice channels that belong to this guild.
This is sorted by the position and are in UI order from top to bottom.
- property voice_client: VoiceClient | None¶
Returns the
VoiceClientassociated with this guild, if any.
- await webhooks()¶
This function is a coroutine.
Gets the list of webhooks from this guild.
Requires
manage_webhookspermissions.- Returns:
The webhooks for this guild.
- Return type:
List[
Webhook]- Raises:
Forbidden – You don’t have permissions to get the webhooks.
- await welcome_screen()¶
This function is a coroutine.
Returns the
WelcomeScreenof the guild.The guild must have
COMMUNITYinfeatures.You must have the
manage_guildpermission in order to get this.Added in version 2.0.
- Returns:
The welcome screen of guild.
- Return type:
WelcomeScreen- Raises:
Forbidden – You do not have the proper permissions to get this.
HTTPException – Retrieving the welcome screen failed somehow.
NotFound – The guild doesn’t have a welcome screen or community feature is disabled.
- await widget()¶
This function is a coroutine.
Returns the widget of the guild.
Note
The guild must have the widget enabled to get this information.
- Returns:
The guild’s widget.
- Return type:
Widget- Raises:
Forbidden – The widget for this guild is disabled.
HTTPException – Retrieving the widget failed.
Called when a guild becomes unavailable.
The guild must have existed in the client’s cache. This requires
Intents.guildsto be enabled.This event inherits from
Guild.This function is a coroutine.
Returns a list of active
Threadthat the client can access.This includes both private and public threads.
Added in version 2.0.
- Returns:
The active threads
- Return type:
List[
Thread]- Raises:
HTTPException – The request to get the active threads failed.
Returns an
AsyncIteratorthat enables receiving the guild’s audit logs.You must have the
view_audit_logpermission to use this.See API documentation for more information about the before and after parameters.
- Parameters:
limit (Optional[
int]) – The number of entries to retrieve. IfNoneretrieve all entries.before (Union[
abc.Snowflake,datetime.datetime]) – Retrieve entries before this date or entry. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.after (Union[
abc.Snowflake,datetime.datetime]) – Retrieve entries after this date or entry. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.user (
abc.Snowflake) – The moderator to filter entries from.action (
AuditLogAction) – The action to filter with.
- Yields:
AuditLogEntry– The audit log entry.- Raises:
Forbidden – You are not allowed to fetch audit logs
HTTPException – An error occurred while fetching the audit logs.
- Return type:
AuditLogIterator
Examples
Getting the first 100 entries:
async for entry in guild.audit_logs(limit=100): print(f"{entry.user} did {entry.action} to {await entry.get_target()}")
Getting entries for a specific action:
async for entry in guild.audit_logs(action=discord.AuditLogAction.ban): print(f"{entry.user} banned {await entry.get_target()}")
Getting entries made by a specific user:
entries = await guild.audit_logs(limit=None, user=guild.me).flatten() await channel.send(f"I made {len(entries)} moderation actions.")
This function is a coroutine.
Bans a user from the guild.
The user must meet the
abc.Snowflakeabc.You must have the
ban_memberspermission to do this.- Parameters:
user (
abc.Snowflake) – The user to ban from their guild.delete_message_seconds (Optional[
int]) – The number of seconds worth of messages to delete from the user in the guild. The minimum is 0 and the maximum is 604800 (i.e. 7 days). The default is 0.reason (Optional[
str]) – The reason the user got banned.
- Raises:
Forbidden – You do not have the proper permissions to ban.
HTTPException – Banning failed.
- Return type:
Returns the guild’s banner asset, if available.
This function is a coroutine.
Retrieves an
AsyncIteratorthat enables receiving the guild’s bans. In order to use this, you must have theban_memberspermission. Users will always be returned in ascending order sorted by user ID. If both thebeforeandafterparameters are provided, only before is respected.Changed in version 2.5: The
before. andafterparameters were changed. They are now of the typeabc.Snowflakeinstead of SnowflakeTime to comply with the discord api.Changed in version 2.0: The
limit,before. andafterparameters were added. Now returns aBanIteratorinstead of a list ofBanEntryobjects.All parameters are optional.
- Parameters:
limit (Optional[
int]) – The number of bans to retrieve. Defaults to 1000.before (Optional[
abc.Snowflake]) – Retrieve bans before the given user.after (Optional[
abc.Snowflake]) – Retrieve bans after the given user.
- Yields:
BanEntry– The ban entry for the ban.- Raises:
Forbidden – You do not have proper permissions to get the information.
HTTPException – An error occurred while fetching the information.
- Return type:
BanIterator
Examples
Usage
async for ban in guild.bans(limit=150): print(ban.user.name)
Flattening into a list
bans = await guild.bans(limit=150).flatten() # bans is now a list of BanEntry...
The maximum bitrate for voice channels this guild can have.
This function is a coroutine.
Bulk ban users from the guild.
The users must meet the
abc.Snowflakeabc.You must have the
ban_memberspermission to do this.Example Usage:
# Ban multiple users successes, failures = await guild.bulk_ban(user1, user2, user3, ..., reason="Raid") # Ban a list of users successes, failures = await guild.bulk_ban(*users)
- Parameters:
*users (
abc.Snowflake) – An argument list of users to ban from the guild, up to 200.delete_message_seconds (Optional[
int]) – The number of seconds worth of messages to delete from the user in the guild. The minimum is 0 and the maximum is 604800 (i.e. 7 days). The default is 0.reason (Optional[
str]) – The reason the users were banned.
- Returns:
Returns two lists: the first contains members that were successfully banned, while the second is members that could not be banned.
- Return type:
Tuple[List[
abc.Snowflake], List[abc.Snowflake]]- Raises:
ValueError – You tried to ban more than 200 users.
Forbidden – You do not have the proper permissions to ban.
HTTPException – No users were banned.
Returns every
CategoryChanneland their associated channels.These channels and categories are sorted in the official Discord UI order.
If the channels do not have a category, then the first element of the tuple is
None.- Returns:
The categories and their associated channels.
- Return type:
List[Tuple[Optional[
CategoryChannel], List[abc.GuildChannel]]]
A list of categories that belong to this guild.
This is sorted by the position and are in UI order from top to bottom.
This function is a coroutine.
Changes client’s voice state in the guild.
Added in version 1.4.
A list of channels that belong to this guild.
This function is a coroutine.
Requests all members that belong to this guild. In order to use this,
Intents.members()must be enabled.This is a websocket operation and can be slow.
Added in version 1.5.
- Parameters:
cache (
bool) – Whether to cache the members as well.- Raises:
ClientException – The members intent is not enabled.
- Return type:
Creates an auto moderation rule.
- Parameters:
name (
str) – The name of the auto moderation rule.event_type (
AutoModEventType) – The type of event that triggers the rule.trigger_type (
AutoModTriggerType) – The rule’s trigger type.trigger_metadata (
AutoModTriggerMetadata) – The rule’s trigger metadata.actions (List[
AutoModAction]) – The actions to take when the rule is triggered.enabled (
bool) – Whether the rule is enabled.exempt_roles (List[
abc.Snowflake]) – A list of roles that are exempt from the rule.exempt_channels (List[
abc.Snowflake]) – A list of channels that are exempt from the rule.reason (Optional[
str]) – The reason for creating the rule. Shows up in the audit log.
- Returns:
The new auto moderation rule.
- Return type:
AutoModRule- Raises:
HTTPException – Creating the auto moderation rule failed.
Forbidden – You do not have the Manage Guild permission.
This function is a coroutine.
Same as
create_text_channel()except makes aCategoryChannelinstead.Note
The
categoryparameter is not supported in this function since categories cannot have categories.- Returns:
The channel that was just created.
- Return type:
CategoryChannel- Raises:
Forbidden – You do not have the proper permissions to create this channel.
HTTPException – Creating the channel failed.
InvalidArgument – The permission overwrite information is not in proper form.
- Parameters:
This function is a coroutine.
Same as
create_text_channel()except makes aCategoryChannelinstead.Note
The
categoryparameter is not supported in this function since categories cannot have categories.- Returns:
The channel that was just created.
- Return type:
CategoryChannel- Raises:
Forbidden – You do not have the proper permissions to create this channel.
HTTPException – Creating the channel failed.
InvalidArgument – The permission overwrite information is not in proper form.
- Parameters:
This function is a coroutine.
Creates a custom
GuildEmojifor the guild.There is currently a limit of 50 static and animated emojis respectively per guild, unless the guild has the
MORE_EMOJIfeature which extends the limit to 200.You must have the
manage_emojispermission to do this.- Parameters:
name (
str) – The emoji name. Must be at least 2 characters.image (
bytes) – The bytes-like object representing the image data to use. Only JPG, PNG and GIF images are supported.roles (List[
Role]) – AlistofRoles that can use this emoji. Leave empty to make it available to everyone.reason (Optional[
str]) – The reason for creating this emoji. Shows up on the audit log.
- Raises:
Forbidden – You are not allowed to create emojis.
HTTPException – An error occurred creating an emoji.
- Returns:
The created emoji.
- Return type:
GuildEmoji
This function is a coroutine.
Creates a
ForumChannelfor the guild.Note that you need the
manage_channelspermission to create the channel.The
overwritesparameter can be used to create a ‘secret’ channel upon creation. This parameter expects adictof overwrites with the target (either aMemberor aRole) as the key and aPermissionOverwriteas the value.Note
Creating a channel of a specified position will not update the position of other channels to follow suit. A follow-up call to
edit()will be required to update the position of the channel in the channel list.- Parameters:
name (
str) – The channel’s name.overwrites (Dict[Union[
Role,Member,Snowflake],PermissionOverwrite]) – The overwrites to apply to the channel. Useful for creating secret channels.category (Optional[
CategoryChannel]) – The category to place the newly created channel under. The permissions will be automatically synced to category if no overwrites are provided.position (
int) – The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0.topic (
str) – The new channel’s topic.slowmode_delay (
int) – Specifies the slowmode rate limit for user in this channel, in seconds. A value of0disables slowmode. The maximum value possible is21600.nsfw (
bool) – Whether the channel is marked as NSFW.reason (Optional[
str]) – The reason for creating this channel. Shows up on the audit log.default_reaction_emoji (Optional[
GuildEmoji|int|str]) –The default reaction emoji. Can be a unicode emoji or a custom emoji in the forms:
GuildEmoji, snowflake ID, string representation (eg. ‘<a:emoji_name:emoji_id>’).Added in version v2.5.
available_tags (List[
ForumTag]) –The set of tags that can be used in a forum channel.
Added in version 2.7.
default_sort_order (Optional[
SortOrder]) –The default sort order type used to order posts in this channel.
Added in version 2.7.
default_thread_slowmode_delay (Optional[
int]) –The initial slowmode delay to set on newly created threads in this channel.
Added in version 2.7.
default_auto_archive_duration (
int) –The default auto archive duration in minutes for threads created in this channel.
Added in version 2.7.
- Returns:
The channel that was just created.
- Return type:
ForumChannel- Raises:
Forbidden – You do not have the proper permissions to create this channel.
HTTPException – Creating the channel failed.
InvalidArgument – The argument is not in proper form.
Examples
Creating a basic channel:
channel = await guild.create_forum_channel("cool-channel")
Creating a “secret” channel:
overwrites = { guild.default_role: discord.PermissionOverwrite(read_messages=False), guild.me: discord.PermissionOverwrite(read_messages=True), } channel = await guild.create_forum_channel("secret", overwrites=overwrites)
This function is a coroutine.
Attaches an integration to the guild.
You must have the
manage_guildpermission to do this.Added in version 1.4.
- Parameters:
- Raises:
Forbidden – You do not have permission to create the integration.
HTTPException – The account could not be found.
- Return type:
This function is a coroutine.
Creates a
Rolefor the guild.All fields are optional.
You must have the
manage_rolespermission to do this.Changed in version 1.6: Can now pass
inttocolourkeyword-only parameter.- Parameters:
name (
str) – The role name. Defaults to ‘new role’.permissions (
Permissions) – The permissions to have. Defaults to no permissions.colour (Union[
Colour,int]) – The colour for the role. Defaults toColour.default(). This is aliased tocoloras well.hoist (
bool) – Indicates if the role should be shown separately in the member list. Defaults toFalse.mentionable (
bool) – Indicates if the role should be mentionable by others. Defaults toFalse.reason (Optional[
str]) – The reason for creating this role. Shows up on the audit log.icon (Optional[
bytes]) – A bytes-like object representing the icon. Only PNG/JPEG/WebP is supported. If this argument is passed,unicode_emojiis set to None. Only available to guilds that containROLE_ICONSinGuild.features.unicode_emoji (Optional[
str]) – The role’s unicode emoji. If this argument is passed,iconis set to None. Only available to guilds that containROLE_ICONSinGuild.features.color (Colour | int | utils.Undefined)
colors (RoleColours | utils.Undefined)
colours (RoleColours | utils.Undefined)
holographic (bool | utils.Undefined)
- Returns:
The newly created role.
- Return type:
Role- Raises:
Forbidden – You do not have permissions to create the role.
HTTPException – Creating the role failed.
InvalidArgument – An invalid keyword argument was given.
This function is a coroutine. Creates a scheduled event.
- Parameters:
name (
str) – The name of the scheduled event.description (Optional[
str]) – The description of the scheduled event.start_time (
datetime.datetime) – A datetime object of when the scheduled event is supposed to start.end_time (Optional[
datetime.datetime]) – A datetime object of when the scheduled event is supposed to end.location (
ScheduledEventLocation) – The location of where the event is happening.privacy_level (
ScheduledEventPrivacyLevel) – The privacy level of the event. Currently, the only possible value isScheduledEventPrivacyLevel.guild_only, which is default, so there is no need to change this parameter.reason (Optional[
str]) – The reason to show in the audit log.image (Optional[
bytes]) – The cover image of the scheduled event
- Returns:
The created scheduled event.
- Return type:
Optional[
ScheduledEvent]- Raises:
Forbidden – You do not have the Manage Events permission.
HTTPException – The operation failed.
This function is a coroutine. Creates a
SoundboardSoundin the guild. You must havePermissions.manage_expressionspermission to use this.Added in version 2.7.
- Parameters:
name (
str) – The name of the sound.sound (
bytes) – The bytes-like object representing the sound data. Only MP3 sound files that are less than 5.2 seconds long are supported.volume (
float) – The volume of the sound. Defaults to 1.0.emoji (Optional[Union[
PartialEmoji,GuildEmoji,str]]) – The emoji of the sound.reason (Optional[
str]) – The reason for creating this sound. Shows up on the audit log.
- Returns:
The created sound.
- Return type:
SoundboardSound- Raises:
HTTPException – Creating the sound failed.
Forbidden – You do not have permissions to create sounds.
This function is a coroutine.
This is similar to
create_text_channel()except makes aStageChannelinstead.Added in version 1.7.
- Parameters:
name (
str) – The channel’s name.topic (
str) – The new channel’s topic.overwrites (Dict[Union[
Role,Member,Snowflake],PermissionOverwrite]) – The overwrites to apply to the channel. Useful for creating secret channels.category (Optional[
CategoryChannel]) – The category to place the newly created channel under. The permissions will be automatically synced to category if no overwrites are provided.position (
int) – The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0.reason (Optional[
str]) – The reason for creating this channel. Shows up on the audit log.bitrate (
int) –The channel’s preferred audio bitrate in bits per second.
Added in version 2.7.
user_limit (
int) –The channel’s limit for number of members that can be in a voice channel.
Added in version 2.7.
rtc_region (Optional[
VoiceRegion]) –The region for the voice channel’s voice communication. A value of
Noneindicates automatic voice region detection.Added in version 2.7.
video_quality_mode (
VideoQualityMode) –The camera video quality for the voice channel’s participants.
Added in version 2.7.
slowmode_delay (
int) –Specifies the slowmode rate limit for user in this channel, in seconds. A value of
0disables slowmode. The maximum value possible is21600.Added in version 2.7.
nsfw (
bool) –Whether the channel is marked as NSFW.
Added in version 2.7.
- Returns:
The channel that was just created.
- Return type:
StageChannel- Raises:
Forbidden – You do not have the proper permissions to create this channel.
HTTPException – Creating the channel failed.
InvalidArgument – The permission overwrite information is not in proper form.
This function is a coroutine.
Creates a
Stickerfor the guild.You must have
manage_emojis_and_stickerspermission to do this.Added in version 2.0.
- Parameters:
name (
str) – The sticker name. Must be 2 to 30 characters.description (Optional[
str]) – The sticker’s description. If used, must be 2 to 100 characters.emoji (
str) – The name of a unicode emoji that represents the sticker’s expression.file (
File) – The file of the sticker to upload.reason (
str) – The reason for creating this sticker. Shows up on the audit log.
- Returns:
The created sticker.
- Return type:
GuildSticker- Raises:
Forbidden – You are not allowed to create stickers.
HTTPException – An error occurred creating a sticker.
TypeError – The parameters for the sticker are not correctly formatted.
This function is a coroutine.
Creates a template for the guild.
You must have the
manage_guildpermission to do this.Added in version 1.7.
This function is a coroutine.
Creates a test entitlement for the guild.
- Parameters:
sku (
Snowflake) – The SKU to create a test entitlement for.- Returns:
The created entitlement.
- Return type:
Entitlement
This function is a coroutine.
Creates a
TextChannelfor the guild.Note that you need the
manage_channelspermission to create the channel.The
overwritesparameter can be used to create a ‘secret’ channel upon creation. This parameter expects adictof overwrites with the target (either aMemberor aRole) as the key and aPermissionOverwriteas the value.Note
Creating a channel of a specified position will not update the position of other channels to follow suit. A follow-up call to
edit()will be required to update the position of the channel in the channel list.- Parameters:
name (
str) – The channel’s name.overwrites (Dict[Union[
Role,Member,Snowflake],PermissionOverwrite]) – The overwrites to apply to the channel. Useful for creating secret channels.category (Optional[
CategoryChannel]) – The category to place the newly created channel under. The permissions will be automatically synced to category if no overwrites are provided.position (
int) – The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0.topic (
str) – The new channel’s topic.slowmode_delay (
int) – Specifies the slowmode rate limit for user in this channel, in seconds. A value of 0 disables slowmode. The maximum value possible is 21600.nsfw (
bool) – Whether the channel is marked as NSFW.reason (Optional[
str]) – The reason for creating this channel. Shows up on the audit log.default_thread_slowmode_delay (Optional[
int]) –The initial slowmode delay to set on newly created threads in this channel.
Added in version 2.7.
default_auto_archive_duration (
int) –The default auto archive duration in minutes for threads created in this channel.
Added in version 2.7.
- Returns:
The channel that was just created.
- Return type:
TextChannel- Raises:
Forbidden – You do not have the proper permissions to create this channel.
HTTPException – Creating the channel failed.
InvalidArgument – The permission overwrite information is not in proper form.
Examples
Creating a basic channel:
channel = await guild.create_text_channel("cool-channel")
Creating a “secret” channel:
overwrites = { guild.default_role: discord.PermissionOverwrite(read_messages=False), guild.me: discord.PermissionOverwrite(read_messages=True), } channel = await guild.create_text_channel("secret", overwrites=overwrites)
This function is a coroutine.
This is similar to
create_text_channel()except makes aVoiceChannelinstead.- Parameters:
name (
str) – The channel’s name.overwrites (Dict[Union[
Role,Member,Snowflake],PermissionOverwrite]) – The overwrites to apply to the channel. Useful for creating secret channels.category (Optional[
CategoryChannel]) – The category to place the newly created channel under. The permissions will be automatically synced to category if no overwrites are provided.position (
int) – The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0.bitrate (
int) – The channel’s preferred audio bitrate in bits per second.user_limit (
int) – The channel’s limit for number of members that can be in a voice channel.rtc_region (Optional[
VoiceRegion]) –The region for the voice channel’s voice communication. A value of
Noneindicates automatic voice region detection.Added in version 1.7.
video_quality_mode (
VideoQualityMode) –The camera video quality for the voice channel’s participants.
Added in version 2.0.
reason (Optional[
str]) – The reason for creating this channel. Shows up on the audit log.slowmode_delay (
int) –Specifies the slowmode rate limit for user in this channel, in seconds. A value of
0disables slowmode. The maximum value possible is21600.Added in version 2.7.
nsfw (
bool) –Whether the channel is marked as NSFW.
Added in version 2.7.
- Returns:
The channel that was just created.
- Return type:
VoiceChannel- Raises:
Forbidden – You do not have the proper permissions to create this channel.
HTTPException – Creating the channel failed.
InvalidArgument – The permission overwrite information is not in proper form.
Returns the guild’s creation time in UTC.
Gets the @everyone role that all members have by default.
This function is a coroutine.
Deletes the guild. You must be the guild owner to delete the guild.
- Raises:
HTTPException – Deleting the guild failed.
Forbidden – You do not have permissions to delete the guild.
- Return type:
Deletes an auto moderation rule.
- Parameters:
- Raises:
HTTPException – Deleting the auto moderation rule failed.
Forbidden – You do not have the Manage Guild permission.
- Return type:
This function is a coroutine.
Deletes the custom
GuildEmojifrom the guild.You must have
manage_emojispermission to do this.- Parameters:
emoji (
abc.Snowflake) – The emoji you are deleting.reason (Optional[
str]) – The reason for deleting this emoji. Shows up on the audit log.
- Raises:
Forbidden – You are not allowed to delete emojis.
HTTPException – An error occurred deleting the emoji.
- Return type:
This function is a coroutine.
Deletes the custom
Stickerfrom the guild.You must have
manage_emojis_and_stickerspermission to do this.Added in version 2.0.
- Parameters:
sticker (
abc.Snowflake) – The sticker you are deleting.reason (Optional[
str]) – The reason for deleting this sticker. Shows up on the audit log.
- Raises:
Forbidden – You are not allowed to delete stickers.
HTTPException – An error occurred deleting the sticker.
- Return type:
Returns the guild’s discovery splash asset, if available.
This function is a coroutine.
Edits the guild.
You must have the
manage_guildpermission to edit the guild.Changed in version 1.4: The rules_channel and public_updates_channel keyword-only parameters were added.
Changed in version 2.0: The discovery_splash and community keyword-only parameters were added.
Changed in version 2.0: The newly updated guild is returned.
- Parameters:
name (
str) – The new name of the guild.description (Optional[
str]) – The new description of the guild. Could beNonefor no description. This is only available to guilds that containPUBLICinGuild.features.icon (
bytes) – A bytes-like object representing the icon. Only PNG/JPEG is supported. GIF is only available to guilds that containANIMATED_ICONinGuild.features. Could beNoneto denote removal of the icon.banner (
bytes) – A bytes-like object representing the banner. Could beNoneto denote removal of the banner. This is only available to guilds that containBANNERinGuild.features.splash (
bytes) – A bytes-like object representing the invite splash. Only PNG/JPEG supported. Could beNoneto denote removing the splash. This is only available to guilds that containINVITE_SPLASHinGuild.features.discovery_splash (
bytes) – A bytes-like object representing the discovery splash. Only PNG/JPEG supported. Could beNoneto denote removing the splash. This is only available to guilds that containDISCOVERABLEinGuild.features.community (
bool) – Whether the guild should be a Community guild. If set toTrue, bothrules_channelandpublic_updates_channelparameters are required.afk_channel (Optional[
VoiceChannel]) – The new channel that is the AFK channel. Could beNonefor no AFK channel.afk_timeout (
int) – The number of seconds until someone is moved to the AFK channel.owner (
Member) – The new owner of the guild to transfer ownership to. Note that you must be owner of the guild to do this.verification_level (
VerificationLevel) – The new verification level for the guild.default_notifications (
NotificationLevel) – The new default notification level for the guild.explicit_content_filter (
ContentFilter) – The new explicit content filter for the guild.system_channel (Optional[
TextChannel]) – The new channel that is used for the system channel. Could beNonefor no system channel.system_channel_flags (
SystemChannelFlags) – The new system channel settings to use with the new system channel.preferred_locale (
str) – The new preferred locale for the guild. Used as the primary language in the guild. If set, this must be an ISO 639 code, e.g.en-USorjaorzh-CN.rules_channel (Optional[
TextChannel]) – The new channel that is used for rules. This is only available to guilds that containPUBLICinGuild.features. Could beNonefor no rules channel.public_updates_channel (Optional[
TextChannel]) – The new channel that is used for public updates from Discord. This is only available to guilds that containPUBLICinGuild.features. Could beNonefor no public updates channel.premium_progress_bar_enabled (
bool) – Whether the guild should have premium progress bar enabled.disable_invites (
bool) – Whether the guild should have server invites enabled or disabled.discoverable (
bool) – Whether the guild should be discoverable in the discover tab.disable_raid_alerts (
bool) – Whether activity alerts for the guild should be disabled.enable_activity_feed (class:bool) – Whether the guild’s user activity feed should be enabled.
reason (Optional[
str]) – The reason for editing this guild. Shows up on the audit log.
- Raises:
Forbidden – You do not have permissions to edit the guild.
HTTPException – Editing the guild failed.
InvalidArgument – The image format passed in to
iconis invalid. It must be PNG or JPG. This is also raised if you are not the owner of the guild and request an ownership transfer.
- Returns:
The newly updated guild. Note that this has the same limitations as mentioned in
Client.fetch_guild()and may not have full data.- Return type:
Guild
This function is a coroutine.
A shorthand for
Onboarding.editwithout fetching the onboarding flow.You must have the
manage_guildandmanage_rolespermissions in the guild to do this.- Parameters:
prompts (Optional[List[
OnboardingPrompt]]) – The new list of prompts for this flow.default_channels (Optional[List[
Snowflake]]) – The new default channels that users are opted into.enabled (Optional[
bool]) – Whether onboarding should be enabled. Setting this toTruerequires the guild to haveCOMMUNITYinfeaturesand at least 7default_channels.mode (Optional[
OnboardingMode]) – The new onboarding mode.reason (Optional[
str]) – The reason that shows up on Audit log.
- Returns:
The updated onboarding flow.
- Return type:
Onboarding- Raises:
HTTPException – Editing the onboarding flow failed somehow.
Forbidden – You don’t have permissions to edit the onboarding flow.
This function is a coroutine.
Bulk edits a list of
Rolein the guild.You must have the
manage_rolespermission to do this.Added in version 1.4.
Example:
positions = { bots_role: 1, # penultimate role tester_role: 2, admin_role: 6, } await guild.edit_role_positions(positions=positions)
- Parameters:
- Returns:
A list of all the roles in the guild.
- Return type:
List[
Role]- Raises:
Forbidden – You do not have permissions to move the roles.
HTTPException – Moving the roles failed.
InvalidArgument – An invalid keyword argument was given.
This function is a coroutine.
A shorthand for
WelcomeScreen.editwithout fetching the welcome screen.You must have the
manage_guildpermission in the guild to do this.The guild must have
COMMUNITYinGuild.features- Parameters:
description (Optional[
str]) – The new description of welcome screen.welcome_channels (Optional[List[
WelcomeScreenChannel]]) – The welcome channels. The order of the channels would be same as the passed list order.enabled (Optional[
bool]) – Whether the welcome screen should be displayed.reason (Optional[
str]) – The reason that shows up on audit log.
- Returns:
The edited welcome screen.
- Return type:
WelcomeScreen- Raises:
HTTPException – Editing the welcome screen failed somehow.
Forbidden – You don’t have permissions to edit the welcome screen.
NotFound – This welcome screen does not exist.
This function is a coroutine.
Edits the widget of the guild.
You must have the
manage_guildpermission to use thisAdded in version 2.0.
- Parameters:
- Raises:
Forbidden – You do not have permission to edit the widget.
HTTPException – Editing the widget failed.
- Return type:
The maximum number of emoji slots this guild has.
Returns an
AsyncIteratorthat enables fetching the guild’s entitlements.This is identical to
Client.entitlements()with theguildparameter.Added in version 2.6.
- Parameters:
skus (list[
abc.Snowflake] | None) – Limit the fetched entitlements to entitlements that are for these SKUs.before (
abc.Snowflake|datetime.datetime| None) – Retrieves guilds before this date or object. If a datetime is provided, it is recommended to use a UTC-aware datetime. If the datetime is naive, it is assumed to be local time.after (
abc.Snowflake|datetime.datetime| None) – Retrieve guilds after this date or object. If a datetime is provided, it is recommended to use a UTC-aware datetime. If the datetime is naive, it is assumed to be local time.limit (Optional[
int]) – The number of entitlements to retrieve. IfNone, retrieves every entitlement, which may be slow. Defaults to100.exclude_ended (
bool) – Whether to limit the fetched entitlements to those that have not ended. Defaults toFalse.
- Yields:
Entitlement– The application’s entitlements.- Raises:
HTTPException – Retrieving the entitlements failed.
- Return type:
EntitlementIterator
This function is a coroutine.
Similar to
prune_members()except instead of actually pruning members, it returns how many members it would prune from the guild had it been called.- Parameters:
days (
int) – The number of days before counting as inactive.roles (List[
abc.Snowflake]) –A list of
abc.Snowflakethat represent roles to include in the estimate. If a member has a role that is not specified, they’ll be excluded.Added in version 1.7.
- Returns:
The number of members estimated to be pruned.
- Return type:
- Raises:
Forbidden – You do not have permissions to prune members.
HTTPException – An error occurred while fetching the prune members estimate.
InvalidArgument – An integer was not passed for
days.
This function is a coroutine.
Retrieves a
AutoModRulefrom rule ID.- Returns:
The requested auto moderation rule.
- Return type:
AutoModRule- Raises:
HTTPException – Getting the auto moderation rule failed.
Forbidden – You do not have the Manage Guild permission.
- Parameters:
id (
int)
This function is a coroutine.
Retrieves a list of auto moderation rules for this guild.
- Returns:
The auto moderation rules for this guild.
- Return type:
List[
AutoModRule]- Raises:
HTTPException – Getting the auto moderation rules failed.
Forbidden – You do not have the Manage Guild permission.
This function is a coroutine.
Retrieves the
BanEntryfor a user.You must have the
ban_memberspermission to get this information.- Parameters:
user (
abc.Snowflake) – The user to get ban information from.- Returns:
The
BanEntryobject for the specified user.- Return type:
BanEntry- Raises:
Forbidden – You do not have proper permissions to get the information.
NotFound – This user is not banned.
HTTPException – An error occurred while fetching the information.
This function is a coroutine.
Retrieves a
abc.GuildChannelorThreadwith the specified ID.Note
This method is an API call. For general usage, consider
get_channel_or_thread()instead.Added in version 2.0.
- Returns:
The channel from the ID.
- Return type:
Union[
abc.GuildChannel,Thread]- Raises:
InvalidData – An unknown channel type was received from Discord or the guild the channel belongs to is not the same as the one in this object points to.
HTTPException – Retrieving the channel failed.
NotFound – Invalid Channel ID.
Forbidden – You do not have permission to fetch this channel.
- Parameters:
channel_id (
int)
This function is a coroutine.
Retrieves all
abc.GuildChannelthat the guild has.Note
This method is an API call. For general usage, consider
channelsinstead.Added in version 1.2.
- Returns:
All channels in the guild.
- Return type:
Sequence[
discord.channel.base.GuildChannel]- Raises:
InvalidData – An unknown channel type was received from Discord.
HTTPException – Retrieving the channels failed.
This function is a coroutine.
Retrieves a custom
GuildEmojifrom the guild.Note
This method is an API call. For general usage, consider iterating over
emojisinstead.- Parameters:
emoji_id (
int) – The emoji’s ID.- Returns:
The retrieved emoji.
- Return type:
GuildEmoji- Raises:
NotFound – The emoji requested could not be found.
HTTPException – An error occurred fetching the emoji.
This function is a coroutine.
Retrieves all custom
GuildEmojis from the guild.Note
This method is an API call. For general usage, consider
emojisinstead.- Raises:
HTTPException – An error occurred fetching the emojis.
- Returns:
The retrieved emojis.
- Return type:
List[
GuildEmoji]
This function is a coroutine.
Retrieves a
Memberfrom a guild ID, and a member ID.Note
This method is an API call. If you have
Intents.membersand member cache enabled, considerget_member()instead.- Parameters:
member_id (
int) – The member’s ID to fetch from.- Returns:
The member from the member ID.
- Return type:
Member- Raises:
Forbidden – You do not have access to the guild.
HTTPException – Fetching the member failed.
Retrieves an
AsyncIteratorthat enables receiving the guild’s members. In order to use this,Intents.members()must be enabled.Note
This method is an API call. For general usage, consider
membersinstead.Added in version 1.3.
All parameters are optional.
- Parameters:
limit (Optional[
int]) – The number of members to retrieve. Defaults to 1000. PassNoneto fetch all members. Note that this is potentially slow.after (Optional[Union[
abc.Snowflake,datetime.datetime]]) – Retrieve members after this date or object. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.
- Yields:
Member– The member with the member data parsed.- Raises:
ClientException – The members intent is not enabled.
HTTPException – Getting the members failed.
- Return type:
MemberIterator
Examples
Usage
async for member in guild.fetch_members(limit=150): print(member.name)
Flattening into a list
members = await guild.fetch_members(limit=150).flatten() # members is now a list of Member...
This function is a coroutine.
Retrieves a
Rolethat the guild has.Note
This method is an API call. For general usage, consider using
get_roleinstead.Added in version 2.7.
- Returns:
The role in the guild with the specified ID.
- Return type:
Role- Raises:
HTTPException – Retrieving the role failed.
- Parameters:
role_id (
int)
This function is a coroutine.
Retrieves all
Rolethat the guild has.Note
This method is an API call. For general usage, consider
rolesinstead.Added in version 1.3.
- Returns:
All roles in the guild.
- Return type:
List[
Role]- Raises:
HTTPException – Retrieving the roles failed.
This function is a coroutine.
Retrieves a
ScheduledEventfrom event ID.Note
This method is an API call. If you have
Intents.scheduled_events, considerget_scheduled_event()instead.- Parameters:
- Returns:
The scheduled event from the event ID.
- Return type:
Optional[
ScheduledEvent]- Raises:
HTTPException – Fetching the event failed.
NotFound – Event not found.
This function is a coroutine.
Returns a list of
ScheduledEventin the guild.Note
This method is an API call. For general usage, consider
scheduled_eventsinstead.- Parameters:
with_user_count (Optional[
bool]) – If the scheduled event should be fetched with the number of users that are interested in the events. Defaults toTrue.- Returns:
The fetched scheduled events.
- Return type:
List[
ScheduledEvent]- Raises:
ClientException – The scheduled events intent is not enabled.
HTTPException – Getting the scheduled events failed.
This function is a coroutine. Fetches a soundboard sound in the guild.
Added in version 2.7.
- Parameters:
sound_id (
int) – The ID of the sound.- Returns:
The sound.
- Return type:
SoundboardSound
This function is a coroutine. Fetches all the soundboard sounds in the guild.
Added in version 2.7.
- Returns:
The sounds in the guild.
- Return type:
List[
SoundboardSound]
This function is a coroutine.
Retrieves a custom
Stickerfrom the guild.Added in version 2.0.
Note
This method is an API call. For general usage, consider iterating over
stickersinstead.- Parameters:
sticker_id (
int) – The sticker’s ID.- Returns:
The retrieved sticker.
- Return type:
GuildSticker- Raises:
NotFound – The sticker requested could not be found.
HTTPException – An error occurred fetching the sticker.
This function is a coroutine.
Retrieves a list of all
Stickers for the guild.Added in version 2.0.
Note
This method is an API call. For general usage, consider
stickersinstead.- Raises:
HTTPException – An error occurred fetching the stickers.
- Returns:
The retrieved stickers.
- Return type:
List[
GuildSticker]
The maximum number of bytes files can have when uploaded to this guild.
A list of forum channels that belong to this guild.
Added in version 2.0.
This is sorted by the position and are in UI order from top to bottom.
Returns a channel with the given ID.
Note
This does not search for threads.
- Parameters:
channel_id (
int) – The ID to search for.- Returns:
The returned channel or
Noneif not found.- Return type:
Optional[
abc.GuildChannel]
Returns a channel or thread with the given ID.
Added in version 2.0.
- Parameters:
channel_id (
int) – The ID to search for.- Returns:
The returned channel or thread or
Noneif not found.- Return type:
Optional[Union[
Thread,abc.GuildChannel]]
Similar to
Client.userexcept an instance ofMember. This is essentially used to get the member version of yourself.- Return type:
Returns a member with the given ID.
- Parameters:
user_id (
int) – The ID to search for.- Returns:
The member or
Noneif not found.- Return type:
Optional[
Member]
Returns the first member found that matches the name provided.
The name can have an optional discriminator argument, e.g. “Jake#0001” or “Jake” will both do the lookup. However, the former will give a more precise result. Note that the discriminator must have all 4 digits for this to work.
If a nickname is passed, then it is looked up via the nickname. Note however, that a nickname + discriminator combo will not look up the nickname but rather the username + discriminator combo due to nickname + discriminator not being unique.
If no member is found,
Noneis returned.- Parameters:
name (
str) – The name of the member to lookup with an optional discriminator.- Returns:
The member in this guild with the associated name. If not found then
Noneis returned.- Return type:
Optional[
Member]
Returns a role with the given ID.
- Parameters:
role_id (
int) – The ID to search for.- Returns:
The role or
Noneif not found.- Return type:
Optional[
Role]
Returns a Scheduled Event with the given ID.
- Parameters:
event_id (
int) – The ID to search for.- Returns:
The scheduled event or
Noneif not found.- Return type:
Optional[
ScheduledEvent]
Returns a sound with the given ID.
Added in version 2.7.
- Parameters:
sound_id (
int) – The ID to search for.- Returns:
The sound or
Noneif not found.- Return type:
Optional[
SoundboardSound]
Returns a stage instance with the given ID.
Added in version 2.0.
- Parameters:
stage_instance_id (
int) – The ID to search for.- Returns:
The stage instance or
Noneif not found.- Return type:
Optional[
StageInstance]
Returns a thread with the given ID.
Added in version 2.0.
- Parameters:
thread_id (
int) – The ID to search for.- Returns:
The returned thread or
Noneif not found.- Return type:
Optional[
Thread]
Returns the guild’s icon asset, if available.
This function is a coroutine.
Returns a list of all integrations attached to the guild.
You must have the
manage_guildpermission to do this.Added in version 1.4.
- Returns:
The list of integrations that are attached to the guild.
- Return type:
List[
Integration]- Raises:
Forbidden – You do not have permission to create the integration.
HTTPException – Fetching the integrations failed.
This function is a coroutine.
Returns a list of all active instant invites from the guild.
You must have the
manage_guildpermission to get this information.- Returns:
The list of invites that are currently active.
- Return type:
List[
Invite]- Raises:
Forbidden – You do not have proper permissions to get the information.
HTTPException – An error occurred while fetching the information.
A boolean indicating whether the guild invites are disabled.
Returns a boolean indicating if the guild is “chunked”.
A chunked guild means that
member_countis equal to the number of members stored in the internalmemberscache.If this value returns
False, then you should request for offline members.- Return type:
Indicates if the guild is a ‘large’ guild.
A large guild is defined as having more than
large_thresholdcount members, which for this library is set to the maximum of 250.- Return type:
Returns a URL that allows the client to jump to the guild.
Added in version 2.0.
This function is a coroutine.
Kicks a user from the guild.
The user must meet the
abc.Snowflakeabc.You must have the
kick_memberspermission to do this.- Parameters:
user (
abc.Snowflake) – The user to kick from their guild.reason (Optional[
str]) – The reason the user got kicked.
- Raises:
Forbidden – You do not have the proper permissions to kick.
HTTPException – Kicking failed.
- Return type:
This function is a coroutine.
Leaves the guild. :rtype:
NoneNote
You cannot leave the guild that you own, you must delete it instead via
delete().- Raises:
HTTPException – Leaving the guild failed.
Returns the true member count regardless of it being loaded fully or not.
Warning
Due to a Discord limitation, in order for this attribute to remain up-to-date and accurate, it requires
Intents.membersto be specified.
This function is a coroutine.
Modify the guild’s incident actions, controlling when invites or DMs are re-enabled after being temporarily disabled. Requires the
manage_guildpermission.- Parameters:
invites_disabled_until (Optional[
datetime.datetime]) – The ISO8601 timestamp indicating when invites will be enabled again, orNoneto enable invites immediately.dms_disabled_until (Optional[
datetime.datetime]) – The ISO8601 timestamp indicating when DMs will be enabled again, orNoneto enable DMs immediately.reason (Optional[
str]) – The reason for this action, used for the audit log.
- Returns:
The updated incidents data for the guild.
- Return type:
IncidentsData
This function is a coroutine.
Returns the
Onboardingflow for the guild.Added in version 2.5.
- Returns:
The onboarding flow for the guild.
- Return type:
Onboarding- Raises:
HTTPException – Retrieving the onboarding flow failed somehow.
Gets the premium subscriber role, AKA “boost” role, in this guild.
Added in version 1.6.
A list of members who have “boosted” this guild.
This function is a coroutine.
Prunes the guild from its inactive members.
The inactive members are denoted if they have not logged on in
daysnumber of days and have no roles.You must have the
kick_memberspermission to use this.To check how many members you would prune without actually pruning, see the
estimate_pruned_members()function.To prune members that have specific roles see the
rolesparameter.Changed in version 1.4: The
roleskeyword-only parameter was added.- Parameters:
days (
int) – The number of days before counting as inactive.reason (Optional[
str]) – The reason for doing this action. Shows up on the audit log.compute_prune_count (
bool) – Whether to compute the prune count. This defaults toTruewhich makes it prone to timeouts in very large guilds. In order to prevent timeouts, you must set this toFalse. If this is set toFalse, then this function will always returnNone.roles (List[
abc.Snowflake]) – A list ofabc.Snowflakethat represent roles to include in the pruning process. If a member has a role that is not specified, they’ll be excluded.
- Raises:
Forbidden – You do not have permissions to prune members.
HTTPException – An error occurred while pruning members.
InvalidArgument – An integer was not passed for
days.
- Returns:
The number of members pruned. If
compute_prune_countisFalsethen this returnsNone.- Return type:
Optional[
int]
Return’s the guild’s channel where admins and moderators of the guilds receive notices from Discord. The guild must be a Community guild.
If no channel is set, then this returns
None.Added in version 1.4.
This function is a coroutine.
Request members that belong to this guild whose username starts with the query given.
This is a websocket operation and can be slow.
Added in version 1.3.
- Parameters:
query (Optional[
str]) – The string that the username’s start with.user_ids (Optional[List[
int]]) –List of user IDs to search for. If the user ID is not in the guild then it won’t be returned.
Added in version 1.4.
limit (Optional[
int]) – The maximum number of members to send back. If no query is passed, passingNonereturns all members. If aqueryoruser_idsis passed, must be between 1 and 100. Defaults to 5.presences (Optional[
bool]) –Whether to request for presences to be provided. This defaults to
False.Added in version 1.6.
cache (
bool) – Whether to cache the members internally. This makes operations such asget_member()work for those that matched. Defaults toTrue.
- Returns:
The list of members that have matched the query.
- Return type:
List[
Member]- Raises:
asyncio.TimeoutError – The query timed out waiting for the members.
ValueError – Invalid parameters were passed to the function
ClientException – The presences intent is not enabled.
Returns a
listof the guild’s roles in hierarchy order.The first element of this list will be the lowest role in the hierarchy.
Return’s the guild’s channel used for the rules. The guild must be a Community guild.
If no channel is set, then this returns
None.Added in version 1.3.
A list of scheduled events in this guild.
Search for guild members whose usernames or nicknames start with the query string. Unlike
fetch_members(), this does not requireIntents.members().Note
This method is an API call. For general usage, consider filtering
membersinstead.Added in version 2.6.
- Parameters:
- Returns:
The list of members that have matched the query.
- Return type:
List[
Member]- Raises:
HTTPException – Getting the members failed.
Gets the role associated with this client’s user, if any.
Added in version 1.6.
This function is a coroutine.
Set whether it is required to have MFA enabled on your account to perform moderation actions. You must be the guild owner to do this.
- Parameters:
- Raises:
HTTPException – The operation failed.
Forbidden – You are not the owner of the guild.
- Return type:
Returns the shard ID for this guild if applicable.
The maximum number of soundboard slots this guild has.
Added in version 2.7.
A list of soundboard sounds that belong to this guild.
Added in version 2.7.
This is sorted by the position and are in UI order from top to bottom.
Returns the guild’s invite splash asset, if available.
A list of stage channels that belong to this guild.
Added in version 1.7.
This is sorted by the position and are in UI order from top to bottom.
Returns a
listof the guild’s stage instances that are currently running.Added in version 2.0.
The maximum number of sticker slots this guild has.
Added in version 2.0.
Returns the guild’s channel used for system messages.
If no channel is set, then this returns
None.
Returns the guild’s system channel settings.
This function is a coroutine.
Gets the list of templates from this guild.
Requires
manage_guildpermissions.Added in version 1.7.
- Returns:
The templates for this guild.
- Return type:
List[
Template]- Raises:
Forbidden – You don’t have permissions to get the templates.
A list of text channels that belong to this guild.
This is sorted by the position and are in UI order from top to bottom.
A list of threads that you have permission to view.
Added in version 2.0.
This function is a coroutine.
Unbans a user from the guild.
The user must meet the
abc.Snowflakeabc.You must have the
ban_memberspermission to do this.- Parameters:
user (
abc.Snowflake) – The user to unban.reason (Optional[
str]) – The reason for doing this action. Shows up on the audit log.
- Raises:
Forbidden – You do not have the proper permissions to unban.
HTTPException – Unbanning failed.
- Return type:
This function is a coroutine.
Returns the guild’s special vanity invite.
The guild must have
VANITY_URLinfeatures.You must have the
manage_guildpermission to use this as well.- Returns:
The special vanity invite. If
Nonethen the guild does not have a vanity invite set.- Return type:
Optional[
Invite]- Raises:
Forbidden – You do not have the proper permissions to get this.
HTTPException – Retrieving the vanity invite failed.
A list of voice channels that belong to this guild.
This is sorted by the position and are in UI order from top to bottom.
Returns the
VoiceClientassociated with this guild, if any.
This function is a coroutine.
Gets the list of webhooks from this guild.
Requires
manage_webhookspermissions.- Returns:
The webhooks for this guild.
- Return type:
List[
Webhook]- Raises:
Forbidden – You don’t have permissions to get the webhooks.
This function is a coroutine.
Returns the
WelcomeScreenof the guild.The guild must have
COMMUNITYinfeatures.You must have the
manage_guildpermission in order to get this.Added in version 2.0.
- Returns:
The welcome screen of guild.
- Return type:
WelcomeScreen- Raises:
Forbidden – You do not have the proper permissions to get this.
HTTPException – Retrieving the welcome screen failed somehow.
NotFound – The guild doesn’t have a welcome screen or community feature is disabled.
This function is a coroutine.
Returns the widget of the guild.
Note
The guild must have the widget enabled to get this information.
- Returns:
The guild’s widget.
- Return type:
Widget- Raises:
Forbidden – The widget for this guild is disabled.
HTTPException – Retrieving the widget failed.
- class discord.events.GuildBanAdd[source]¶
Called when a user gets banned from a guild.
This requires
Intents.moderationto be enabled.This event inherits from
Member.- property accent_color¶
Equivalent to
User.accent_color
- property accent_colour¶
Equivalent to
User.accent_colour
- property activity: Activity | Game | CustomActivity | Streaming | Spotify | None¶
Returns the primary activity the user is currently doing. Could be
Noneif no activity is being done.Note
Due to a Discord API limitation, this may be
Noneif the user is listening to a song on Spotify with a title longer than 128 characters.Note
A user may have multiple activities, these can be accessed under
activities.
- await add_roles(*roles, reason=None, atomic=True)¶
This function is a coroutine.
Gives the member a number of
Roles.You must have the
manage_rolespermission to use this, and the addedRoles must appear lower in the list of roles than the highest role of the member.- Parameters:
*roles (
abc.Snowflake) – An argument list ofabc.Snowflakerepresenting aRoleto give to the member.reason (Optional[
str]) – The reason for adding these roles. Shows up on the audit log.atomic (
bool) – Whether to atomically add roles. This will ensure that multiple operations will always be applied regardless of the current state of the cache.
- Raises:
Forbidden – You do not have permissions to add these roles.
HTTPException – Adding roles failed.
- Return type:
- property avatar¶
Equivalent to
User.avatar
- property avatar_decoration¶
Equivalent to
User.avatar_decoration
- await ban(*, delete_message_seconds=None, reason=None)¶
This function is a coroutine.
Bans this member. Equivalent to
Guild.ban().
- property banner¶
Equivalent to
User.banner
- property bot¶
Equivalent to
User.bot
- can_send(*objects)¶
Returns a
boolindicating whether you have the permissions to send the object(s).
- property color: Colour¶
A property that returns a color denoting the rendered color for the member. If the default color is the one rendered then an instance of
Colour.default()is returned.There is an alias for this named
colour.
- property colour: Colour¶
A property that returns a colour denoting the rendered colour for the member. If the default colour is the one rendered then an instance of
Colour.default()is returned.There is an alias for this named
color.
- await create_dm() DMChannel¶
This function is a coroutine.
Creates a
DMChannelwith this user.This should be rarely called, as this is done transparently for most people.
- Returns:
The channel that was created.
- Return type:
- await create_test_entitlement(sku: discord.abc.Snowflake) Entitlement¶
This function is a coroutine.
Creates a test entitlement for the user.
- Parameters:
sku (
Snowflake) – The SKU to create a test entitlement for.- Returns:
The created entitlement.
- Return type:
Entitlement
- property created_at¶
Equivalent to
User.created_at
- property default_avatar¶
Equivalent to
User.default_avatar
- property desktop_status: Status¶
The member’s status on the desktop client, if applicable.
- property discriminator¶
Equivalent to
User.discriminator
- property display_avatar: Asset¶
Returns the member’s display avatar.
For regular members this is just their avatar, but if they have a guild specific avatar then that is returned instead.
Added in version 2.0.
- property display_banner: Asset | None¶
Returns the member’s display banner.
For regular members this is just their banner, but if they have a guild specific banner then that is returned instead.
Added in version 2.7.
- property display_name: str¶
Returns the user’s display name. This will either be their guild specific nickname, global name or username.
- await edit(*, nick=Undefined.MISSING, mute=Undefined.MISSING, deafen=Undefined.MISSING, suppress=Undefined.MISSING, roles=Undefined.MISSING, voice_channel=Undefined.MISSING, reason=None, communication_disabled_until=Undefined.MISSING, bypass_verification=Undefined.MISSING, banner=Undefined.MISSING, avatar=Undefined.MISSING, bio=Undefined.MISSING)¶
This function is a coroutine.
Edits the member’s data.
Depending on the parameter passed, this requires different permissions listed below:
Parameter
Permission
nick
Permissions.manage_nicknamesmute
Permissions.mute_membersdeafen
Permissions.deafen_membersroles
Permissions.manage_rolesvoice_channel
Permissions.move_memberscommunication_disabled_until
Permissions.moderate_membersbypass_verification
See note below
Note
bypass_verification may be edited under three scenarios:
Client has
Permissions.manage_guildClient has
Permissions.manage_rolesClient has ALL THREE of
Permissions.moderate_members,Permissions.kick_members, andPermissions.ban_members
Note
The following parameters are only available when editing the bot’s own member:
avatarbannerbio
All parameters are optional.
Changed in version 1.1: Can now pass
Nonetovoice_channelto kick a member from voice.Changed in version 2.0: The newly member is now optionally returned, if applicable.
- Parameters:
nick (Optional[
str]) – The member’s new nickname. UseNoneto remove the nickname.mute (
bool) – Indicates if the member should be guild muted or un-muted.deafen (
bool) – Indicates if the member should be guild deafened or un-deafened.suppress (
bool) –Indicates if the member should be suppressed in stage channels.
Added in version 1.7.
roles (List[
Role]) – The member’s new list of roles. This replaces the roles.voice_channel (Optional[Union[
VoiceChannel,StageChannel]]) – The voice channel to move the member to. PassNoneto kick them from voice.reason (Optional[
str]) – The reason for editing this member. Shows up on the audit log.communication_disabled_until (Optional[
datetime.datetime]) –Temporarily puts the member in timeout until this time. If the value is
None, then the user is removed from timeout.Added in version 2.0.
bypass_verification (Optional[
bool]) –Indicates if the member should bypass the guild’s verification requirements.
Added in version 2.6.
banner (Optional[
bytes]) –A bytes-like object representing the banner. Could be
Noneto denote removal of the banner.This is only available when editing the bot’s own member (i.e.
Guild.me).Added in version 2.7.
avatar (Optional[
bytes]) –A bytes-like object representing the avatar. Could be
Noneto denote removal of the avatar.This is only available when editing the bot’s own member (i.e.
Guild.me).Added in version 2.7.
bio (Optional[
str]) –The new bio for the member. Could be
Noneto denote removal of the bio.This is only available when editing the bot’s own member (i.e.
Guild.me).Added in version 2.7.
- Returns:
The newly updated member, if applicable. This is only returned when certain fields are updated.
- Return type:
Optional[
Member]- Raises:
Forbidden – You do not have the proper permissions to the action requested.
HTTPException – The operation failed.
InvalidArgument – You tried to edit the avatar, banner, or bio of a member that is not the bot.
- entitlements(skus: list[Snowflake] | None = None, before: SnowflakeTime | None = None, after: SnowflakeTime | None = None, limit: int | None = 100, exclude_ended: bool = False) EntitlementIterator¶
Returns an
AsyncIteratorthat enables fetching the user’s entitlements.This is identical to
Client.entitlements()with theuserparameter.Added in version 2.6.
- Parameters:
skus (list[
abc.Snowflake] | None) – Limit the fetched entitlements to entitlements that are for these SKUs.before (
abc.Snowflake|datetime.datetime| None) – Retrieves guilds before this date or object. If a datetime is provided, it is recommended to use a UTC-aware datetime. If the datetime is naive, it is assumed to be local time.after (
abc.Snowflake|datetime.datetime| None) – Retrieve guilds after this date or object. If a datetime is provided, it is recommended to use a UTC-aware datetime. If the datetime is naive, it is assumed to be local time.limit (Optional[
int]) – The number of entitlements to retrieve. IfNone, retrieves every entitlement, which may be slow. Defaults to100.exclude_ended (
bool) – Whether to limit the fetched entitlements to those that have not ended. Defaults toFalse.
- Yields:
Entitlement– The application’s entitlements.- Raises:
HTTPException – Retrieving the entitlements failed.
- await fetch_message(id, /)¶
This function is a coroutine.
Retrieves a single
Messagefrom the destination.- Parameters:
id (
int) – The message ID to look for.- Returns:
The message asked for.
- Return type:
- Raises:
NotFound – The specified message was not found.
Forbidden – You do not have the permissions required to get a message.
HTTPException – Retrieving the message failed.
- await get_dm_channel() DMChannel | None¶
Returns the channel associated with this user if it exists.
If this returns
None, you can create a DM channel by calling thecreate_dm()coroutine function.
- await get_mutual_guilds() list[Guild]¶
The guilds that the user shares with the client.
Note
This will only return mutual guilds within the client’s internal cache.
Added in version 1.7.
- get_role(role_id, /)¶
Returns a role with the given ID from roles which the member has.
Added in version 2.0.
- Parameters:
role_id (
int) – The ID to search for.- Returns:
The role or
Noneif not found in the member’s roles.- Return type:
Optional[
Role]
- property guild_avatar: Asset | None¶
Returns an
Assetfor the guild avatar the member has. If unavailable,Noneis returned.Added in version 2.0.
- property guild_banner: Asset | None¶
Returns an
Assetfor the guild banner the member has. If unavailable,Noneis returned.Added in version 2.7.
- property guild_permissions: Permissions¶
Returns the member’s guild permissions.
This only takes into consideration the guild permissions and not most of the implied permissions or any of the channel permission overwrites. For 100% accurate permission calculation, please use
abc.GuildChannel.permissions_for().This does take into consideration guild ownership and the administrator implication.
- history(*, limit=100, before=None, after=None, around=None, oldest_first=None)¶
Returns an
AsyncIteratorthat enables receiving the destination’s message history.You must have
read_message_historypermissions to use this.- Parameters:
limit (Optional[
int]) – The number of messages to retrieve. IfNone, retrieves every message in the channel. Note, however, that this would make it a slow operation.before (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages before this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.after (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages after this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.around (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages around this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time. When using this argument, the maximum limit is 101. Note that if the limit is an even number, then this will return at most limit + 1 messages.oldest_first (Optional[
bool]) – If set toTrue, return messages in oldest->newest order. Defaults toTrueifafteris specified, otherwiseFalse.
- Yields:
Message– The message with the message data parsed.- Raises:
Forbidden – You do not have permissions to get channel message history.
HTTPException – The request to get message history failed.
- Return type:
HistoryIterator
Examples
Usage
counter = 0 async for message in channel.history(limit=200): if message.author == client.user: counter += 1
Flattening into a list:
messages = await channel.history(limit=123).flatten() # messages is now a list of Message...
All parameters are optional.
- property id¶
Equivalent to
User.id
- property is_migrated¶
Equivalent to
User.is_migrated
- is_on_mobile()¶
A helper function that determines if a member is active on a mobile device.
- Return type:
- property jump_url¶
Equivalent to
User.jump_url
- await kick(*, reason=None)¶
This function is a coroutine.
Kicks this member. Equivalent to
Guild.kick().
- mentioned_in(message)¶
Checks if the member is mentioned in the specified message.
- Parameters:
message (
Message) – The message to check if you’re mentioned in.- Returns:
Indicates if the member is mentioned in the message.
- Return type:
- property mobile_status: Status¶
The member’s status on a mobile device, if applicable.
- await move_to(channel, *, reason=None)¶
This function is a coroutine.
Moves a member to a new voice channel (they must be connected first).
You must have the
move_memberspermission to use this.This raises the same exceptions as
edit().Changed in version 1.1: Can now pass
Noneto kick a member from voice.
- property name¶
Equivalent to
User.name
- property nameplate¶
Equivalent to
User.nameplate
- pins(*, limit=50, before=None)¶
Returns a
MessagePinIteratorthat enables receiving the destination’s pinned messages.You must have
read_message_historypermissions to use this.Warning
Starting from version 3.0, await channel.pins() will no longer return a list of
Message. See examples below for new usage instead.- Parameters:
limit (Optional[
int]) – The number of pinned messages to retrieve. IfNone, retrieves every pinned message in the channel.before (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages pinned before this datetime. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.
- Yields:
MessagePin– The pinned message.- Raises:
Forbidden – You do not have permissions to get pinned messages.
HTTPException – The request to get pinned messages failed.
- Return type:
MessagePinIterator
Examples
Usage
counter = 0 async for pin in channel.pins(limit=250): if pin.message.author == client.user: counter += 1
Flattening into a list:
pins = await channel.pins(limit=None).flatten() # pins is now a list of MessagePin...
All parameters are optional.
- property primary_guild¶
Equivalent to
User.primary_guild
- property public_flags¶
Equivalent to
User.public_flags
- await remove_roles(*roles, reason=None, atomic=True)¶
This function is a coroutine.
Removes
Roles from this member.You must have the
manage_rolespermission to use this, and the removedRoles must appear lower in the list of roles than the highest role of the member.- Parameters:
*roles (
abc.Snowflake) – An argument list ofabc.Snowflakerepresenting aRoleto remove from the member.reason (Optional[
str]) – The reason for removing these roles. Shows up on the audit log.atomic (
bool) – Whether to atomically remove roles. This will ensure that multiple operations will always be applied regardless of the current state of the cache.
- Raises:
Forbidden – You do not have permissions to remove these roles.
HTTPException – Removing the roles failed.
- Return type:
- await remove_timeout(*, reason=None)¶
This function is a coroutine.
Removes the timeout from a member.
You must have the
moderate_memberspermission to remove the timeout.This is equivalent to calling
timeout()and passingNoneto theuntilparameter.- Parameters:
reason (Optional[
str]) – The reason for doing this action. Shows up on the audit log.- Raises:
Forbidden – You do not have permissions to remove the timeout.
HTTPException – An error occurred doing the request.
- Return type:
- await request_to_speak()¶
This function is a coroutine.
Request to speak in the connected channel.
Only applies to stage channels. :rtype:
NoneNote
Requesting members that are not the client is equivalent to
editprovidingsuppressasFalse.Added in version 1.7.
- Raises:
Forbidden – You do not have the proper permissions to the action requested.
HTTPException – The operation failed.
- property roles: list[Role]¶
A
listofRolethat the member belongs to. Note that the first element of this list is always the default ‘@everyone’ role.These roles are sorted by their position in the role hierarchy.
- await send(content=None, *, tts=None, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, enforce_nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None, poll=None, suppress=None, silent=None)¶
This function is a coroutine.
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through
str(content). If the content is set toNone(the default), then theembedparameter must be provided.To upload a single file, the
fileparameter should be used with a singleFileobject. To upload multiple files, thefilesparameter should be used with alistofFileobjects. Specifying both parameters will lead to an exception.To upload a single embed, the
embedparameter should be used with a singleEmbedobject. To upload multiple embeds, theembedsparameter should be used with alistofEmbedobjects. Specifying both parameters will lead to an exception.- Parameters:
content (Optional[
str]) – The content of the message to send.tts (
bool) – Indicates if the message should be sent using text-to-speech.embed (
Embed) – The rich embed for the content.file (
File) – The file to upload.files (List[
File]) – A list of files to upload. Must be a maximum of 10.nonce (Union[
str,int]) – The nonce to use for sending this message. If the message was successfully sent, then the message will have a nonce with this value.enforce_nonce (Optional[
bool]) –Whether
nonceis enforced to be validated.Added in version 2.5.
delete_after (
float) – If provided, the number of seconds to wait in the background before deleting the message we just sent. If the deletion fails, then it is silently ignored.allowed_mentions (
AllowedMentions) –Controls the mentions being processed in this message. If this is passed, then the object is merged with
allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set inallowed_mentions. If no object is passed at all then the defaults given byallowed_mentionsare used instead.Added in version 1.4.
reference (Union[
Message,MessageReference,PartialMessage]) –A reference to the
Messagebeing replied to or forwarded. This can be created usingto_reference(). When replying, you can control whether this mentions the author of the referenced message using thereplied_userattribute ofallowed_mentionsor by settingmention_author.Added in version 1.6.
mention_author (Optional[
bool]) –If set, overrides the
replied_userattribute ofallowed_mentions.Added in version 1.6.
view (
discord.ui.View) – A Discord UI View to add to the message.embeds (List[
Embed]) –A list of embeds to upload. Must be a maximum of 10.
Added in version 2.0.
stickers (Sequence[Union[
GuildSticker,StickerItem]]) –A list of stickers to upload. Must be a maximum of 3.
Added in version 2.0.
suppress (
bool) – Whether to suppress embeds for the message.silent (
bool) –Whether to suppress push and desktop notifications for the message.
Added in version 2.4.
poll (
Poll) –The poll to send.
Added in version 2.6.
- Returns:
The message that was sent.
- Return type:
- Raises:
HTTPException – Sending the message failed.
Forbidden – You do not have the proper permissions to send the message.
InvalidArgument – The
fileslist is not of the appropriate size, you specified bothfileandfiles, or you specified bothembedandembeds, or thereferenceobject is not aMessage,MessageReferenceorPartialMessage.
- property status: Status¶
The member’s overall status. If the value is unknown, then it will be a
strinstead.
- property system¶
Equivalent to
User.system
- await timeout(until, *, reason=None)¶
This function is a coroutine.
Applies a timeout to a member in the guild until a set datetime.
You must have the
moderate_memberspermission to timeout a member.- Parameters:
until (
datetime.datetime) – The date and time to timeout the member for. If this isNonethen the member is removed from timeout.reason (Optional[
str]) – The reason for doing this action. Shows up on the audit log.
- Raises:
Forbidden – You do not have permissions to timeout members.
HTTPException – An error occurred doing the request.
- Return type:
- await timeout_for(duration, *, reason=None)¶
This function is a coroutine.
Applies a timeout to a member in the guild for a set duration. A shortcut method for
timeout(), and equivalent totimeout(until=datetime.utcnow() + duration, reason=reason).You must have the
moderate_memberspermission to timeout a member.- Parameters:
duration (
datetime.timedelta) – The duration to timeout the member for.reason (Optional[
str]) – The reason for doing this action. Shows up on the audit log.
- Raises:
Forbidden – You do not have permissions to timeout members.
HTTPException – An error occurred doing the request.
- Return type:
- property top_role: Role¶
Returns the member’s highest role.
This is useful for figuring where a member stands in the role hierarchy chain.
- await trigger_typing()¶
This function is a coroutine.
Triggers a typing indicator to the destination.
Typing indicator will go away after 10 seconds, or after a message is sent.
- Return type:
- typing()¶
Returns a context manager that allows you to type for an indefinite period of time.
This is useful for denoting long computations in your bot. :rtype:
TypingNote
This is both a regular context manager and an async context manager. This means that both
withandasync withwork with this.Example Usage:
async with channel.typing(): # simulate something heavy await asyncio.sleep(10) await channel.send("done!")
- await unban(*, reason=None)¶
This function is a coroutine.
Unbans this member. Equivalent to
Guild.unban().
- property voice: VoiceState | None¶
Returns the member’s current voice state.
- property web_status: Status¶
The member’s status on the web client, if applicable.
- class discord.events.GuildBanRemove[source]¶
Called when a user gets unbanned from a guild.
This requires
Intents.moderationto be enabled.This event inherits from
Member.- property accent_color¶
Equivalent to
User.accent_color
- property accent_colour¶
Equivalent to
User.accent_colour
- property activity: Activity | Game | CustomActivity | Streaming | Spotify | None¶
Returns the primary activity the user is currently doing. Could be
Noneif no activity is being done.Note
Due to a Discord API limitation, this may be
Noneif the user is listening to a song on Spotify with a title longer than 128 characters.Note
A user may have multiple activities, these can be accessed under
activities.
- await add_roles(*roles, reason=None, atomic=True)¶
This function is a coroutine.
Gives the member a number of
Roles.You must have the
manage_rolespermission to use this, and the addedRoles must appear lower in the list of roles than the highest role of the member.- Parameters:
*roles (
abc.Snowflake) – An argument list ofabc.Snowflakerepresenting aRoleto give to the member.reason (Optional[
str]) – The reason for adding these roles. Shows up on the audit log.atomic (
bool) – Whether to atomically add roles. This will ensure that multiple operations will always be applied regardless of the current state of the cache.
- Raises:
Forbidden – You do not have permissions to add these roles.
HTTPException – Adding roles failed.
- Return type:
- property avatar¶
Equivalent to
User.avatar
- property avatar_decoration¶
Equivalent to
User.avatar_decoration
- await ban(*, delete_message_seconds=None, reason=None)¶
This function is a coroutine.
Bans this member. Equivalent to
Guild.ban().
- property banner¶
Equivalent to
User.banner
- property bot¶
Equivalent to
User.bot
- can_send(*objects)¶
Returns a
boolindicating whether you have the permissions to send the object(s).
- property color: Colour¶
A property that returns a color denoting the rendered color for the member. If the default color is the one rendered then an instance of
Colour.default()is returned.There is an alias for this named
colour.
- property colour: Colour¶
A property that returns a colour denoting the rendered colour for the member. If the default colour is the one rendered then an instance of
Colour.default()is returned.There is an alias for this named
color.
- await create_dm() DMChannel¶
This function is a coroutine.
Creates a
DMChannelwith this user.This should be rarely called, as this is done transparently for most people.
- Returns:
The channel that was created.
- Return type:
- await create_test_entitlement(sku: discord.abc.Snowflake) Entitlement¶
This function is a coroutine.
Creates a test entitlement for the user.
- Parameters:
sku (
Snowflake) – The SKU to create a test entitlement for.- Returns:
The created entitlement.
- Return type:
Entitlement
- property created_at¶
Equivalent to
User.created_at
- property default_avatar¶
Equivalent to
User.default_avatar
- property desktop_status: Status¶
The member’s status on the desktop client, if applicable.
- property discriminator¶
Equivalent to
User.discriminator
- property display_avatar: Asset¶
Returns the member’s display avatar.
For regular members this is just their avatar, but if they have a guild specific avatar then that is returned instead.
Added in version 2.0.
- property display_banner: Asset | None¶
Returns the member’s display banner.
For regular members this is just their banner, but if they have a guild specific banner then that is returned instead.
Added in version 2.7.
- property display_name: str¶
Returns the user’s display name. This will either be their guild specific nickname, global name or username.
- await edit(*, nick=Undefined.MISSING, mute=Undefined.MISSING, deafen=Undefined.MISSING, suppress=Undefined.MISSING, roles=Undefined.MISSING, voice_channel=Undefined.MISSING, reason=None, communication_disabled_until=Undefined.MISSING, bypass_verification=Undefined.MISSING, banner=Undefined.MISSING, avatar=Undefined.MISSING, bio=Undefined.MISSING)¶
This function is a coroutine.
Edits the member’s data.
Depending on the parameter passed, this requires different permissions listed below:
Parameter
Permission
nick
Permissions.manage_nicknamesmute
Permissions.mute_membersdeafen
Permissions.deafen_membersroles
Permissions.manage_rolesvoice_channel
Permissions.move_memberscommunication_disabled_until
Permissions.moderate_membersbypass_verification
See note below
Note
bypass_verification may be edited under three scenarios:
Client has
Permissions.manage_guildClient has
Permissions.manage_rolesClient has ALL THREE of
Permissions.moderate_members,Permissions.kick_members, andPermissions.ban_members
Note
The following parameters are only available when editing the bot’s own member:
avatarbannerbio
All parameters are optional.
Changed in version 1.1: Can now pass
Nonetovoice_channelto kick a member from voice.Changed in version 2.0: The newly member is now optionally returned, if applicable.
- Parameters:
nick (Optional[
str]) – The member’s new nickname. UseNoneto remove the nickname.mute (
bool) – Indicates if the member should be guild muted or un-muted.deafen (
bool) – Indicates if the member should be guild deafened or un-deafened.suppress (
bool) –Indicates if the member should be suppressed in stage channels.
Added in version 1.7.
roles (List[
Role]) – The member’s new list of roles. This replaces the roles.voice_channel (Optional[Union[
VoiceChannel,StageChannel]]) – The voice channel to move the member to. PassNoneto kick them from voice.reason (Optional[
str]) – The reason for editing this member. Shows up on the audit log.communication_disabled_until (Optional[
datetime.datetime]) –Temporarily puts the member in timeout until this time. If the value is
None, then the user is removed from timeout.Added in version 2.0.
bypass_verification (Optional[
bool]) –Indicates if the member should bypass the guild’s verification requirements.
Added in version 2.6.
banner (Optional[
bytes]) –A bytes-like object representing the banner. Could be
Noneto denote removal of the banner.This is only available when editing the bot’s own member (i.e.
Guild.me).Added in version 2.7.
avatar (Optional[
bytes]) –A bytes-like object representing the avatar. Could be
Noneto denote removal of the avatar.This is only available when editing the bot’s own member (i.e.
Guild.me).Added in version 2.7.
bio (Optional[
str]) –The new bio for the member. Could be
Noneto denote removal of the bio.This is only available when editing the bot’s own member (i.e.
Guild.me).Added in version 2.7.
- Returns:
The newly updated member, if applicable. This is only returned when certain fields are updated.
- Return type:
Optional[
Member]- Raises:
Forbidden – You do not have the proper permissions to the action requested.
HTTPException – The operation failed.
InvalidArgument – You tried to edit the avatar, banner, or bio of a member that is not the bot.
- entitlements(skus: list[Snowflake] | None = None, before: SnowflakeTime | None = None, after: SnowflakeTime | None = None, limit: int | None = 100, exclude_ended: bool = False) EntitlementIterator¶
Returns an
AsyncIteratorthat enables fetching the user’s entitlements.This is identical to
Client.entitlements()with theuserparameter.Added in version 2.6.
- Parameters:
skus (list[
abc.Snowflake] | None) – Limit the fetched entitlements to entitlements that are for these SKUs.before (
abc.Snowflake|datetime.datetime| None) – Retrieves guilds before this date or object. If a datetime is provided, it is recommended to use a UTC-aware datetime. If the datetime is naive, it is assumed to be local time.after (
abc.Snowflake|datetime.datetime| None) – Retrieve guilds after this date or object. If a datetime is provided, it is recommended to use a UTC-aware datetime. If the datetime is naive, it is assumed to be local time.limit (Optional[
int]) – The number of entitlements to retrieve. IfNone, retrieves every entitlement, which may be slow. Defaults to100.exclude_ended (
bool) – Whether to limit the fetched entitlements to those that have not ended. Defaults toFalse.
- Yields:
Entitlement– The application’s entitlements.- Raises:
HTTPException – Retrieving the entitlements failed.
- await fetch_message(id, /)¶
This function is a coroutine.
Retrieves a single
Messagefrom the destination.- Parameters:
id (
int) – The message ID to look for.- Returns:
The message asked for.
- Return type:
- Raises:
NotFound – The specified message was not found.
Forbidden – You do not have the permissions required to get a message.
HTTPException – Retrieving the message failed.
- await get_dm_channel() DMChannel | None¶
Returns the channel associated with this user if it exists.
If this returns
None, you can create a DM channel by calling thecreate_dm()coroutine function.
- await get_mutual_guilds() list[Guild]¶
The guilds that the user shares with the client.
Note
This will only return mutual guilds within the client’s internal cache.
Added in version 1.7.
- get_role(role_id, /)¶
Returns a role with the given ID from roles which the member has.
Added in version 2.0.
- Parameters:
role_id (
int) – The ID to search for.- Returns:
The role or
Noneif not found in the member’s roles.- Return type:
Optional[
Role]
- property guild_avatar: Asset | None¶
Returns an
Assetfor the guild avatar the member has. If unavailable,Noneis returned.Added in version 2.0.
- property guild_banner: Asset | None¶
Returns an
Assetfor the guild banner the member has. If unavailable,Noneis returned.Added in version 2.7.
- property guild_permissions: Permissions¶
Returns the member’s guild permissions.
This only takes into consideration the guild permissions and not most of the implied permissions or any of the channel permission overwrites. For 100% accurate permission calculation, please use
abc.GuildChannel.permissions_for().This does take into consideration guild ownership and the administrator implication.
- history(*, limit=100, before=None, after=None, around=None, oldest_first=None)¶
Returns an
AsyncIteratorthat enables receiving the destination’s message history.You must have
read_message_historypermissions to use this.- Parameters:
limit (Optional[
int]) – The number of messages to retrieve. IfNone, retrieves every message in the channel. Note, however, that this would make it a slow operation.before (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages before this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.after (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages after this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.around (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages around this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time. When using this argument, the maximum limit is 101. Note that if the limit is an even number, then this will return at most limit + 1 messages.oldest_first (Optional[
bool]) – If set toTrue, return messages in oldest->newest order. Defaults toTrueifafteris specified, otherwiseFalse.
- Yields:
Message– The message with the message data parsed.- Raises:
Forbidden – You do not have permissions to get channel message history.
HTTPException – The request to get message history failed.
- Return type:
HistoryIterator
Examples
Usage
counter = 0 async for message in channel.history(limit=200): if message.author == client.user: counter += 1
Flattening into a list:
messages = await channel.history(limit=123).flatten() # messages is now a list of Message...
All parameters are optional.
- property id¶
Equivalent to
User.id
- property is_migrated¶
Equivalent to
User.is_migrated
- is_on_mobile()¶
A helper function that determines if a member is active on a mobile device.
- Return type:
- property jump_url¶
Equivalent to
User.jump_url
- await kick(*, reason=None)¶
This function is a coroutine.
Kicks this member. Equivalent to
Guild.kick().
- mentioned_in(message)¶
Checks if the member is mentioned in the specified message.
- Parameters:
message (
Message) – The message to check if you’re mentioned in.- Returns:
Indicates if the member is mentioned in the message.
- Return type:
- property mobile_status: Status¶
The member’s status on a mobile device, if applicable.
- await move_to(channel, *, reason=None)¶
This function is a coroutine.
Moves a member to a new voice channel (they must be connected first).
You must have the
move_memberspermission to use this.This raises the same exceptions as
edit().Changed in version 1.1: Can now pass
Noneto kick a member from voice.
- property name¶
Equivalent to
User.name
- property nameplate¶
Equivalent to
User.nameplate
- pins(*, limit=50, before=None)¶
Returns a
MessagePinIteratorthat enables receiving the destination’s pinned messages.You must have
read_message_historypermissions to use this.Warning
Starting from version 3.0, await channel.pins() will no longer return a list of
Message. See examples below for new usage instead.- Parameters:
limit (Optional[
int]) – The number of pinned messages to retrieve. IfNone, retrieves every pinned message in the channel.before (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages pinned before this datetime. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.
- Yields:
MessagePin– The pinned message.- Raises:
Forbidden – You do not have permissions to get pinned messages.
HTTPException – The request to get pinned messages failed.
- Return type:
MessagePinIterator
Examples
Usage
counter = 0 async for pin in channel.pins(limit=250): if pin.message.author == client.user: counter += 1
Flattening into a list:
pins = await channel.pins(limit=None).flatten() # pins is now a list of MessagePin...
All parameters are optional.
- property primary_guild¶
Equivalent to
User.primary_guild
- property public_flags¶
Equivalent to
User.public_flags
- await remove_roles(*roles, reason=None, atomic=True)¶
This function is a coroutine.
Removes
Roles from this member.You must have the
manage_rolespermission to use this, and the removedRoles must appear lower in the list of roles than the highest role of the member.- Parameters:
*roles (
abc.Snowflake) – An argument list ofabc.Snowflakerepresenting aRoleto remove from the member.reason (Optional[
str]) – The reason for removing these roles. Shows up on the audit log.atomic (
bool) – Whether to atomically remove roles. This will ensure that multiple operations will always be applied regardless of the current state of the cache.
- Raises:
Forbidden – You do not have permissions to remove these roles.
HTTPException – Removing the roles failed.
- Return type:
- await remove_timeout(*, reason=None)¶
This function is a coroutine.
Removes the timeout from a member.
You must have the
moderate_memberspermission to remove the timeout.This is equivalent to calling
timeout()and passingNoneto theuntilparameter.- Parameters:
reason (Optional[
str]) – The reason for doing this action. Shows up on the audit log.- Raises:
Forbidden – You do not have permissions to remove the timeout.
HTTPException – An error occurred doing the request.
- Return type:
- await request_to_speak()¶
This function is a coroutine.
Request to speak in the connected channel.
Only applies to stage channels. :rtype:
NoneNote
Requesting members that are not the client is equivalent to
editprovidingsuppressasFalse.Added in version 1.7.
- Raises:
Forbidden – You do not have the proper permissions to the action requested.
HTTPException – The operation failed.
- property roles: list[Role]¶
A
listofRolethat the member belongs to. Note that the first element of this list is always the default ‘@everyone’ role.These roles are sorted by their position in the role hierarchy.
- await send(content=None, *, tts=None, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, enforce_nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None, poll=None, suppress=None, silent=None)¶
This function is a coroutine.
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through
str(content). If the content is set toNone(the default), then theembedparameter must be provided.To upload a single file, the
fileparameter should be used with a singleFileobject. To upload multiple files, thefilesparameter should be used with alistofFileobjects. Specifying both parameters will lead to an exception.To upload a single embed, the
embedparameter should be used with a singleEmbedobject. To upload multiple embeds, theembedsparameter should be used with alistofEmbedobjects. Specifying both parameters will lead to an exception.- Parameters:
content (Optional[
str]) – The content of the message to send.tts (
bool) – Indicates if the message should be sent using text-to-speech.embed (
Embed) – The rich embed for the content.file (
File) – The file to upload.files (List[
File]) – A list of files to upload. Must be a maximum of 10.nonce (Union[
str,int]) – The nonce to use for sending this message. If the message was successfully sent, then the message will have a nonce with this value.enforce_nonce (Optional[
bool]) –Whether
nonceis enforced to be validated.Added in version 2.5.
delete_after (
float) – If provided, the number of seconds to wait in the background before deleting the message we just sent. If the deletion fails, then it is silently ignored.allowed_mentions (
AllowedMentions) –Controls the mentions being processed in this message. If this is passed, then the object is merged with
allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set inallowed_mentions. If no object is passed at all then the defaults given byallowed_mentionsare used instead.Added in version 1.4.
reference (Union[
Message,MessageReference,PartialMessage]) –A reference to the
Messagebeing replied to or forwarded. This can be created usingto_reference(). When replying, you can control whether this mentions the author of the referenced message using thereplied_userattribute ofallowed_mentionsor by settingmention_author.Added in version 1.6.
mention_author (Optional[
bool]) –If set, overrides the
replied_userattribute ofallowed_mentions.Added in version 1.6.
view (
discord.ui.View) – A Discord UI View to add to the message.embeds (List[
Embed]) –A list of embeds to upload. Must be a maximum of 10.
Added in version 2.0.
stickers (Sequence[Union[
GuildSticker,StickerItem]]) –A list of stickers to upload. Must be a maximum of 3.
Added in version 2.0.
suppress (
bool) – Whether to suppress embeds for the message.silent (
bool) –Whether to suppress push and desktop notifications for the message.
Added in version 2.4.
poll (
Poll) –The poll to send.
Added in version 2.6.
- Returns:
The message that was sent.
- Return type:
- Raises:
HTTPException – Sending the message failed.
Forbidden – You do not have the proper permissions to send the message.
InvalidArgument – The
fileslist is not of the appropriate size, you specified bothfileandfiles, or you specified bothembedandembeds, or thereferenceobject is not aMessage,MessageReferenceorPartialMessage.
- property status: Status¶
The member’s overall status. If the value is unknown, then it will be a
strinstead.
- property system¶
Equivalent to
User.system
- await timeout(until, *, reason=None)¶
This function is a coroutine.
Applies a timeout to a member in the guild until a set datetime.
You must have the
moderate_memberspermission to timeout a member.- Parameters:
until (
datetime.datetime) – The date and time to timeout the member for. If this isNonethen the member is removed from timeout.reason (Optional[
str]) – The reason for doing this action. Shows up on the audit log.
- Raises:
Forbidden – You do not have permissions to timeout members.
HTTPException – An error occurred doing the request.
- Return type:
- await timeout_for(duration, *, reason=None)¶
This function is a coroutine.
Applies a timeout to a member in the guild for a set duration. A shortcut method for
timeout(), and equivalent totimeout(until=datetime.utcnow() + duration, reason=reason).You must have the
moderate_memberspermission to timeout a member.- Parameters:
duration (
datetime.timedelta) – The duration to timeout the member for.reason (Optional[
str]) – The reason for doing this action. Shows up on the audit log.
- Raises:
Forbidden – You do not have permissions to timeout members.
HTTPException – An error occurred doing the request.
- Return type:
- property top_role: Role¶
Returns the member’s highest role.
This is useful for figuring where a member stands in the role hierarchy chain.
- await trigger_typing()¶
This function is a coroutine.
Triggers a typing indicator to the destination.
Typing indicator will go away after 10 seconds, or after a message is sent.
- Return type:
- typing()¶
Returns a context manager that allows you to type for an indefinite period of time.
This is useful for denoting long computations in your bot. :rtype:
TypingNote
This is both a regular context manager and an async context manager. This means that both
withandasync withwork with this.Example Usage:
async with channel.typing(): # simulate something heavy await asyncio.sleep(10) await channel.send("done!")
- await unban(*, reason=None)¶
This function is a coroutine.
Unbans this member. Equivalent to
Guild.unban().
- property voice: VoiceState | None¶
Returns the member’s current voice state.
- property web_status: Status¶
The member’s status on the web client, if applicable.
- class discord.events.GuildEmojisUpdate[source]¶
Called when a guild adds or removes emojis.
This requires
Intents.emojis_and_stickersto be enabled.- guild¶
The guild who got their emojis updated.
- Type:
Guild
- emojis¶
The list of emojis after the update.
- Type:
list[
Emoji]
- old_emojis¶
The list of emojis before the update.
- Type:
list[
Emoji]
- class discord.events.GuildStickersUpdate[source]¶
Called when a guild adds or removes stickers.
This requires
Intents.emojis_and_stickersto be enabled.- guild¶
The guild who got their stickers updated.
- Type:
Guild
- stickers¶
The list of stickers after the update.
- Type:
list[
GuildSticker]
- old_stickers¶
The list of stickers before the update.
- Type:
list[
GuildSticker]
Roles¶
- class discord.events.GuildRoleCreate[source]¶
Called when a guild creates a role.
To get the guild it belongs to, use
Role.guild. This requiresIntents.guildsto be enabled.This event inherits from
Role.- property color: Colour¶
Returns the role’s primary color. Equivalent to
colors.primary. An alias exists undercolour.Changed in version 2.7.
- property colors: RoleColours¶
Returns the role’s colours. Equivalent to
colours.Added in version 2.7.
- property colour: Colour¶
Returns the role colour. Equivalent to
colours.primary. An alias exists undercolor.Changed in version 2.7.
- await delete(*, reason=None)¶
This function is a coroutine.
Deletes the role.
You must have the
manage_rolespermission to use this.- Parameters:
reason (Optional[
str]) – The reason for deleting this role. Shows up on the audit log.- Raises:
Forbidden – You do not have permissions to delete the role.
HTTPException – Deleting the role failed.
- Return type:
- await edit(*, name=Undefined.MISSING, permissions=Undefined.MISSING, colour=Undefined.MISSING, color=Undefined.MISSING, colours=Undefined.MISSING, colors=Undefined.MISSING, holographic=Undefined.MISSING, hoist=Undefined.MISSING, mentionable=Undefined.MISSING, position=Undefined.MISSING, reason=Undefined.MISSING, icon=Undefined.MISSING, unicode_emoji=Undefined.MISSING)¶
This function is a coroutine.
Edits the role.
You must have the
manage_rolespermission to use this.All fields are optional.
Changed in version 1.4: Can now pass
inttocolourkeyword-only parameter.Changed in version 2.0: Edits are no longer in-place, the newly edited role is returned instead. Added
iconandunicode_emoji.- Parameters:
name (
str) – The new role name to change to.permissions (
Permissions) – The new permissions to change to.colour (Union[
Colour,int]) – The new colour to change to. (aliased to color as well)hoist (
bool) – Indicates if the role should be shown separately in the member list.mentionable (
bool) – Indicates if the role should be mentionable by others.position (
int) – The new role’s position. This must be below your top role’s position, or it will fail.reason (Optional[
str]) – The reason for editing this role. Shows up on the audit log.icon (Optional[
bytes]) – A bytes-like object representing the icon. Only PNG/JPEG/WebP is supported. If this argument is passed,unicode_emojiis set to None. Only available to guilds that containROLE_ICONSinGuild.features. Could beNoneto denote removal of the icon.unicode_emoji (Optional[
str]) – The role’s unicode emoji. If this argument is passed,iconis set to None. Only available to guilds that containROLE_ICONSinGuild.features.
- Returns:
The newly edited role.
- Return type:
Role- Raises:
Forbidden – You do not have permissions to change the role.
HTTPException – Editing the role failed.
InvalidArgument – An invalid position was given or the default role was asked to be moved.
- is_assignable()¶
Whether the role is able to be assigned or removed by the bot. :rtype:
boolAdded in version 2.0.
- is_available_for_purchase()¶
Whether the role is available for purchase.
Returns
Trueif the role is available for purchase, andFalseif it is not available for purchase or if the role is not linked to a guild subscription. :rtype:boolAdded in version 2.7.
- is_guild_connections_role()¶
Whether the role is a guild connections role. :rtype:
boolAdded in version 2.7.
- is_integration()¶
Whether the guild manages the role through some form of integrations such as Twitch or through guild subscriptions. :rtype:
boolAdded in version 1.6.
Whether the role is the premium subscriber, AKA “boost”, role for the guild. :rtype:
boolAdded in version 1.6.
- property permissions: Permissions¶
Returns the role’s permissions.
- class discord.events.GuildRoleUpdate[source]¶
Called when a role is changed guild-wide.
This requires
Intents.guildsto be enabled.This event inherits from
Role.- old¶
The updated role’s old info.
- Type:
Role
- property color: Colour¶
Returns the role’s primary color. Equivalent to
colors.primary. An alias exists undercolour.Changed in version 2.7.
- property colors: RoleColours¶
Returns the role’s colours. Equivalent to
colours.Added in version 2.7.
- property colour: Colour¶
Returns the role colour. Equivalent to
colours.primary. An alias exists undercolor.Changed in version 2.7.
- await delete(*, reason=None)¶
This function is a coroutine.
Deletes the role.
You must have the
manage_rolespermission to use this.- Parameters:
reason (Optional[
str]) – The reason for deleting this role. Shows up on the audit log.- Raises:
Forbidden – You do not have permissions to delete the role.
HTTPException – Deleting the role failed.
- Return type:
- await edit(*, name=Undefined.MISSING, permissions=Undefined.MISSING, colour=Undefined.MISSING, color=Undefined.MISSING, colours=Undefined.MISSING, colors=Undefined.MISSING, holographic=Undefined.MISSING, hoist=Undefined.MISSING, mentionable=Undefined.MISSING, position=Undefined.MISSING, reason=Undefined.MISSING, icon=Undefined.MISSING, unicode_emoji=Undefined.MISSING)¶
This function is a coroutine.
Edits the role.
You must have the
manage_rolespermission to use this.All fields are optional.
Changed in version 1.4: Can now pass
inttocolourkeyword-only parameter.Changed in version 2.0: Edits are no longer in-place, the newly edited role is returned instead. Added
iconandunicode_emoji.- Parameters:
name (
str) – The new role name to change to.permissions (
Permissions) – The new permissions to change to.colour (Union[
Colour,int]) – The new colour to change to. (aliased to color as well)hoist (
bool) – Indicates if the role should be shown separately in the member list.mentionable (
bool) – Indicates if the role should be mentionable by others.position (
int) – The new role’s position. This must be below your top role’s position, or it will fail.reason (Optional[
str]) – The reason for editing this role. Shows up on the audit log.icon (Optional[
bytes]) – A bytes-like object representing the icon. Only PNG/JPEG/WebP is supported. If this argument is passed,unicode_emojiis set to None. Only available to guilds that containROLE_ICONSinGuild.features. Could beNoneto denote removal of the icon.unicode_emoji (Optional[
str]) – The role’s unicode emoji. If this argument is passed,iconis set to None. Only available to guilds that containROLE_ICONSinGuild.features.
- Returns:
The newly edited role.
- Return type:
Role- Raises:
Forbidden – You do not have permissions to change the role.
HTTPException – Editing the role failed.
InvalidArgument – An invalid position was given or the default role was asked to be moved.
- is_assignable()¶
Whether the role is able to be assigned or removed by the bot. :rtype:
boolAdded in version 2.0.
- is_available_for_purchase()¶
Whether the role is available for purchase.
Returns
Trueif the role is available for purchase, andFalseif it is not available for purchase or if the role is not linked to a guild subscription. :rtype:boolAdded in version 2.7.
- is_guild_connections_role()¶
Whether the role is a guild connections role. :rtype:
boolAdded in version 2.7.
- is_integration()¶
Whether the guild manages the role through some form of integrations such as Twitch or through guild subscriptions. :rtype:
boolAdded in version 1.6.
Whether the role is the premium subscriber, AKA “boost”, role for the guild. :rtype:
boolAdded in version 1.6.
- property permissions: Permissions¶
Returns the role’s permissions.
- class discord.events.GuildRoleDelete[source]¶
Called when a guild deletes a role.
To get the guild it belongs to, use
Role.guild. This requiresIntents.guildsto be enabled.This event inherits from
Role.- property color: Colour¶
Returns the role’s primary color. Equivalent to
colors.primary. An alias exists undercolour.Changed in version 2.7.
- property colors: RoleColours¶
Returns the role’s colours. Equivalent to
colours.Added in version 2.7.
- property colour: Colour¶
Returns the role colour. Equivalent to
colours.primary. An alias exists undercolor.Changed in version 2.7.
- await delete(*, reason=None)¶
This function is a coroutine.
Deletes the role.
You must have the
manage_rolespermission to use this.- Parameters:
reason (Optional[
str]) – The reason for deleting this role. Shows up on the audit log.- Raises:
Forbidden – You do not have permissions to delete the role.
HTTPException – Deleting the role failed.
- Return type:
- await edit(*, name=Undefined.MISSING, permissions=Undefined.MISSING, colour=Undefined.MISSING, color=Undefined.MISSING, colours=Undefined.MISSING, colors=Undefined.MISSING, holographic=Undefined.MISSING, hoist=Undefined.MISSING, mentionable=Undefined.MISSING, position=Undefined.MISSING, reason=Undefined.MISSING, icon=Undefined.MISSING, unicode_emoji=Undefined.MISSING)¶
This function is a coroutine.
Edits the role.
You must have the
manage_rolespermission to use this.All fields are optional.
Changed in version 1.4: Can now pass
inttocolourkeyword-only parameter.Changed in version 2.0: Edits are no longer in-place, the newly edited role is returned instead. Added
iconandunicode_emoji.- Parameters:
name (
str) – The new role name to change to.permissions (
Permissions) – The new permissions to change to.colour (Union[
Colour,int]) – The new colour to change to. (aliased to color as well)hoist (
bool) – Indicates if the role should be shown separately in the member list.mentionable (
bool) – Indicates if the role should be mentionable by others.position (
int) – The new role’s position. This must be below your top role’s position, or it will fail.reason (Optional[
str]) – The reason for editing this role. Shows up on the audit log.icon (Optional[
bytes]) – A bytes-like object representing the icon. Only PNG/JPEG/WebP is supported. If this argument is passed,unicode_emojiis set to None. Only available to guilds that containROLE_ICONSinGuild.features. Could beNoneto denote removal of the icon.unicode_emoji (Optional[
str]) – The role’s unicode emoji. If this argument is passed,iconis set to None. Only available to guilds that containROLE_ICONSinGuild.features.
- Returns:
The newly edited role.
- Return type:
Role- Raises:
Forbidden – You do not have permissions to change the role.
HTTPException – Editing the role failed.
InvalidArgument – An invalid position was given or the default role was asked to be moved.
- is_assignable()¶
Whether the role is able to be assigned or removed by the bot. :rtype:
boolAdded in version 2.0.
- is_available_for_purchase()¶
Whether the role is available for purchase.
Returns
Trueif the role is available for purchase, andFalseif it is not available for purchase or if the role is not linked to a guild subscription. :rtype:boolAdded in version 2.7.
- is_guild_connections_role()¶
Whether the role is a guild connections role. :rtype:
boolAdded in version 2.7.
- is_integration()¶
Whether the guild manages the role through some form of integrations such as Twitch or through guild subscriptions. :rtype:
boolAdded in version 1.6.
Whether the role is the premium subscriber, AKA “boost”, role for the guild. :rtype:
boolAdded in version 1.6.
- property permissions: Permissions¶
Returns the role’s permissions.
Integrations¶
- class discord.events.GuildIntegrationsUpdate[source]¶
Called whenever an integration is created, modified, or removed from a guild.
This requires
Intents.integrationsto be enabled.- guild¶
The guild that had its integrations updated.
- Type:
Guild
- class discord.events.IntegrationCreate[source]¶
Called when an integration is created.
This requires
Intents.integrationsto be enabled.This event inherits from
Integration.- await delete(*, reason=None)¶
This function is a coroutine.
Deletes the integration.
You must have the
manage_guildpermission to do this.- Parameters:
reason (
str) –The reason the integration was deleted. Shows up on the audit log.
Added in version 2.0.
- Raises:
Forbidden – You do not have permission to delete the integration.
HTTPException – Deleting the integration failed.
- Return type:
- class discord.events.IntegrationUpdate[source]¶
Called when an integration is updated.
This requires
Intents.integrationsto be enabled.This event inherits from
Integration.- await delete(*, reason=None)¶
This function is a coroutine.
Deletes the integration.
You must have the
manage_guildpermission to do this.- Parameters:
reason (
str) –The reason the integration was deleted. Shows up on the audit log.
Added in version 2.0.
- Raises:
Forbidden – You do not have permission to delete the integration.
HTTPException – Deleting the integration failed.
- Return type:
Interactions¶
- class discord.events.InteractionCreate[source]¶
Called when an interaction is created.
This currently happens due to application command invocations or components being used.
Warning
This is a low level event that is not generally meant to be used. If you are working with components, consider using the callbacks associated with the
Viewinstead as it provides a nicer user experience.This event inherits from
Interaction.- app_permissions¶
The resolved permissions of the application in the channel, including overwrites.
- cached_channel¶
The cached channel from which the interaction was sent. DM channels are not resolved. These are
PartialMessageableinstead.Deprecated since version 2.7.
- await delete_original_message(**kwargs)¶
An alias for
delete_original_response().- Raises:
HTTPException – Deleting the message failed.
Forbidden – Deleted a message that is not yours.
- await delete_original_response(*, delay=None)¶
This function is a coroutine.
Deletes the original interaction response message.
This is a lower level interface to
InteractionMessage.delete()in case you do not want to fetch the message and save an HTTP request.- Parameters:
delay (Optional[
float]) – If provided, the number of seconds to wait before deleting the message. The waiting is done in the background and deletion failures are ignored.- Raises:
HTTPException – Deleting the message failed.
Forbidden – Deleted a message that is not yours.
- Return type:
- await edit(*args, **kwargs)¶
This function is a coroutine.
Either respond to the interaction with an edit_message or edits the existing response, determined by whether the interaction has been responded to or not.
- Returns:
The response, its type depending on whether it’s an interaction response or a followup.
- Return type:
- await edit_original_message(**kwargs)¶
An alias for
edit_original_response().- Returns:
The newly edited message.
- Return type:
InteractionMessage- Raises:
HTTPException – Editing the message failed.
Forbidden – Edited a message that is not yours.
TypeError – You specified both
embedandembedsorfileandfilesValueError – The length of
embedswas invalid.
- await edit_original_response(*, content=Undefined.MISSING, embeds=Undefined.MISSING, embed=Undefined.MISSING, file=Undefined.MISSING, files=Undefined.MISSING, attachments=Undefined.MISSING, view=Undefined.MISSING, allowed_mentions=None, delete_after=None, suppress=False)¶
This function is a coroutine.
Edits the original interaction response message.
This is a lower level interface to
InteractionMessage.edit()in case you do not want to fetch the message and save an HTTP request.This method is also the only way to edit the original message if the message sent was ephemeral.
- Parameters:
content (Optional[
str]) – The content to edit the message with orNoneto clear it.embeds (List[
Embed]) – A list of embeds to edit the message with.embed (Optional[
Embed]) – The embed to edit the message with.Nonesuppresses the embeds. This should not be mixed with theembedsparameter.file (
File) – The file to upload. This cannot be mixed withfilesparameter.files (List[
File]) – A list of files to send with the content. This cannot be mixed with thefileparameter.attachments (List[
Attachment]) – A list of attachments to keep in the message. If[]is passed then all attachments are removed.allowed_mentions (
AllowedMentions) – Controls the mentions being processed in this message. Seeabc.Messageable.send()for more information.view (Optional[
View]) – The updated view to update this message with. IfNoneis passed then the view is removed.delete_after (Optional[
float]) – If provided, the number of seconds to wait in the background before deleting the message we just edited. If the deletion fails, then it is silently ignored.suppress (
bool) – Whether to suppress embeds for the message.
- Returns:
The newly edited message.
- Return type:
InteractionMessage- Raises:
HTTPException – Editing the message failed.
Forbidden – Edited a message that is not yours.
TypeError – You specified both
embedandembedsorfileandfilesValueError – The length of
embedswas invalid.
- followup¶
Returns the followup webhook for followup interactions.
- is_guild_authorised()¶
bool: Checks if the interaction is guild authorised.There is an alias for this called
is_guild_authorized(). :rtype:boolAdded in version 2.7.
- is_guild_authorized()¶
bool: Checks if the interaction is guild authorized.There is an alias for this called
is_guild_authorised(). :rtype:boolAdded in version 2.7.
- is_user_authorised()¶
bool: Checks if the interaction is user authorised.There is an alias for this called
is_user_authorized(). :rtype:boolAdded in version 2.7.
- is_user_authorized()¶
bool: Checks if the interaction is user authorized.There is an alias for this called
is_user_authorised(). :rtype:boolAdded in version 2.7.
- await original_message()¶
An alias for
original_response().- Returns:
The original interaction response message.
- Return type:
- Raises:
HTTPException – Fetching the original response message failed.
ClientException – The channel for the message could not be resolved.
- await original_response()¶
This function is a coroutine.
Fetches the original interaction response message associated with the interaction.
If the interaction response was
InteractionResponse.send_message()then this would return the message that was sent using that response. Otherwise, this would return the message that triggered the interaction.Repeated calls to this will return a cached value.
- Returns:
The original interaction response message.
- Return type:
- Raises:
HTTPException – Fetching the original response message failed.
ClientException – The channel for the message could not be resolved.
- property permissions: Permissions¶
The resolved permissions of the member in the channel, including overwrites.
In a non-guild context where this doesn’t apply, an empty permissions object is returned.
- await respond(*args, **kwargs)¶
This function is a coroutine.
Sends either a response or a message using the followup webhook determined by whether the interaction has been responded to or not.
- Returns:
The response, its type depending on whether it’s an interaction response or a followup.
- Return type:
Invites¶
- class discord.events.InviteCreate[source]¶
Called when an invite is created.
You must have
manage_channelspermission to receive this.Note
There is a rare possibility that the
Invite.guildandInvite.channelattributes will be ofObjectrather than the respective models.This requires
Intents.invitesto be enabled.This event inherits from
Invite.- await delete(*, reason=None)¶
This function is a coroutine.
Revokes the instant invite.
You must have the
manage_channelspermission to do this.- Parameters:
reason (Optional[
str]) – The reason for deleting this invite. Shows up on the audit log.- Raises:
Forbidden – You do not have permissions to revoke invites.
NotFound – The invite is invalid or expired.
HTTPException – Revoking the invite failed.
- set_scheduled_event(event)¶
Links the given scheduled event to this invite.
Note
Scheduled events aren’t actually associated with invites on the API. Any guild channel invite can have an event attached to it. Using
abc.GuildChannel.create_invite(),Client.fetch_invite(), or this method, you can link scheduled events.Added in version 2.0.
- Parameters:
event (
ScheduledEvent) – The scheduled event object to link.- Return type:
- class discord.events.InviteDelete[source]¶
Called when an invite is deleted.
You must have
manage_channelspermission to receive this.Note
There is a rare possibility that the
Invite.guildandInvite.channelattributes will be ofObjectrather than the respective models.Outside of those two attributes, the only other attribute guaranteed to be filled by the Discord gateway for this event is
Invite.code.This requires
Intents.invitesto be enabled.This event inherits from
Invite.- await delete(*, reason=None)¶
This function is a coroutine.
Revokes the instant invite.
You must have the
manage_channelspermission to do this.- Parameters:
reason (Optional[
str]) – The reason for deleting this invite. Shows up on the audit log.- Raises:
Forbidden – You do not have permissions to revoke invites.
NotFound – The invite is invalid or expired.
HTTPException – Revoking the invite failed.
- set_scheduled_event(event)¶
Links the given scheduled event to this invite.
Note
Scheduled events aren’t actually associated with invites on the API. Any guild channel invite can have an event attached to it. Using
abc.GuildChannel.create_invite(),Client.fetch_invite(), or this method, you can link scheduled events.Added in version 2.0.
- Parameters:
event (
ScheduledEvent) – The scheduled event object to link.- Return type:
Members & Users¶
- class discord.events.GuildMemberJoin[source]¶
Called when a member joins a guild.
This requires
Intents.membersto be enabled.This event inherits from
Member.- property accent_color¶
Equivalent to
User.accent_color
- property accent_colour¶
Equivalent to
User.accent_colour
- property activity: Activity | Game | CustomActivity | Streaming | Spotify | None¶
Returns the primary activity the user is currently doing. Could be
Noneif no activity is being done.Note
Due to a Discord API limitation, this may be
Noneif the user is listening to a song on Spotify with a title longer than 128 characters.Note
A user may have multiple activities, these can be accessed under
activities.
- await add_roles(*roles, reason=None, atomic=True)¶
This function is a coroutine.
Gives the member a number of
Roles.You must have the
manage_rolespermission to use this, and the addedRoles must appear lower in the list of roles than the highest role of the member.- Parameters:
*roles (
abc.Snowflake) – An argument list ofabc.Snowflakerepresenting aRoleto give to the member.reason (Optional[
str]) – The reason for adding these roles. Shows up on the audit log.atomic (
bool) – Whether to atomically add roles. This will ensure that multiple operations will always be applied regardless of the current state of the cache.
- Raises:
Forbidden – You do not have permissions to add these roles.
HTTPException – Adding roles failed.
- Return type:
- property avatar¶
Equivalent to
User.avatar
- property avatar_decoration¶
Equivalent to
User.avatar_decoration
- await ban(*, delete_message_seconds=None, reason=None)¶
This function is a coroutine.
Bans this member. Equivalent to
Guild.ban().
- property banner¶
Equivalent to
User.banner
- property bot¶
Equivalent to
User.bot
- can_send(*objects)¶
Returns a
boolindicating whether you have the permissions to send the object(s).
- property color: Colour¶
A property that returns a color denoting the rendered color for the member. If the default color is the one rendered then an instance of
Colour.default()is returned.There is an alias for this named
colour.
- property colour: Colour¶
A property that returns a colour denoting the rendered colour for the member. If the default colour is the one rendered then an instance of
Colour.default()is returned.There is an alias for this named
color.
- await create_dm() DMChannel¶
This function is a coroutine.
Creates a
DMChannelwith this user.This should be rarely called, as this is done transparently for most people.
- Returns:
The channel that was created.
- Return type:
- await create_test_entitlement(sku: discord.abc.Snowflake) Entitlement¶
This function is a coroutine.
Creates a test entitlement for the user.
- Parameters:
sku (
Snowflake) – The SKU to create a test entitlement for.- Returns:
The created entitlement.
- Return type:
Entitlement
- property created_at¶
Equivalent to
User.created_at
- property default_avatar¶
Equivalent to
User.default_avatar
- property desktop_status: Status¶
The member’s status on the desktop client, if applicable.
- property discriminator¶
Equivalent to
User.discriminator
- property display_avatar: Asset¶
Returns the member’s display avatar.
For regular members this is just their avatar, but if they have a guild specific avatar then that is returned instead.
Added in version 2.0.
- property display_banner: Asset | None¶
Returns the member’s display banner.
For regular members this is just their banner, but if they have a guild specific banner then that is returned instead.
Added in version 2.7.
- property display_name: str¶
Returns the user’s display name. This will either be their guild specific nickname, global name or username.
- await edit(*, nick=Undefined.MISSING, mute=Undefined.MISSING, deafen=Undefined.MISSING, suppress=Undefined.MISSING, roles=Undefined.MISSING, voice_channel=Undefined.MISSING, reason=None, communication_disabled_until=Undefined.MISSING, bypass_verification=Undefined.MISSING, banner=Undefined.MISSING, avatar=Undefined.MISSING, bio=Undefined.MISSING)¶
This function is a coroutine.
Edits the member’s data.
Depending on the parameter passed, this requires different permissions listed below:
Parameter
Permission
nick
Permissions.manage_nicknamesmute
Permissions.mute_membersdeafen
Permissions.deafen_membersroles
Permissions.manage_rolesvoice_channel
Permissions.move_memberscommunication_disabled_until
Permissions.moderate_membersbypass_verification
See note below
Note
bypass_verification may be edited under three scenarios:
Client has
Permissions.manage_guildClient has
Permissions.manage_rolesClient has ALL THREE of
Permissions.moderate_members,Permissions.kick_members, andPermissions.ban_members
Note
The following parameters are only available when editing the bot’s own member:
avatarbannerbio
All parameters are optional.
Changed in version 1.1: Can now pass
Nonetovoice_channelto kick a member from voice.Changed in version 2.0: The newly member is now optionally returned, if applicable.
- Parameters:
nick (Optional[
str]) – The member’s new nickname. UseNoneto remove the nickname.mute (
bool) – Indicates if the member should be guild muted or un-muted.deafen (
bool) – Indicates if the member should be guild deafened or un-deafened.suppress (
bool) –Indicates if the member should be suppressed in stage channels.
Added in version 1.7.
roles (List[
Role]) – The member’s new list of roles. This replaces the roles.voice_channel (Optional[Union[
VoiceChannel,StageChannel]]) – The voice channel to move the member to. PassNoneto kick them from voice.reason (Optional[
str]) – The reason for editing this member. Shows up on the audit log.communication_disabled_until (Optional[
datetime.datetime]) –Temporarily puts the member in timeout until this time. If the value is
None, then the user is removed from timeout.Added in version 2.0.
bypass_verification (Optional[
bool]) –Indicates if the member should bypass the guild’s verification requirements.
Added in version 2.6.
banner (Optional[
bytes]) –A bytes-like object representing the banner. Could be
Noneto denote removal of the banner.This is only available when editing the bot’s own member (i.e.
Guild.me).Added in version 2.7.
avatar (Optional[
bytes]) –A bytes-like object representing the avatar. Could be
Noneto denote removal of the avatar.This is only available when editing the bot’s own member (i.e.
Guild.me).Added in version 2.7.
bio (Optional[
str]) –The new bio for the member. Could be
Noneto denote removal of the bio.This is only available when editing the bot’s own member (i.e.
Guild.me).Added in version 2.7.
- Returns:
The newly updated member, if applicable. This is only returned when certain fields are updated.
- Return type:
Optional[
Member]- Raises:
Forbidden – You do not have the proper permissions to the action requested.
HTTPException – The operation failed.
InvalidArgument – You tried to edit the avatar, banner, or bio of a member that is not the bot.
- entitlements(skus: list[Snowflake] | None = None, before: SnowflakeTime | None = None, after: SnowflakeTime | None = None, limit: int | None = 100, exclude_ended: bool = False) EntitlementIterator¶
Returns an
AsyncIteratorthat enables fetching the user’s entitlements.This is identical to
Client.entitlements()with theuserparameter.Added in version 2.6.
- Parameters:
skus (list[
abc.Snowflake] | None) – Limit the fetched entitlements to entitlements that are for these SKUs.before (
abc.Snowflake|datetime.datetime| None) – Retrieves guilds before this date or object. If a datetime is provided, it is recommended to use a UTC-aware datetime. If the datetime is naive, it is assumed to be local time.after (
abc.Snowflake|datetime.datetime| None) – Retrieve guilds after this date or object. If a datetime is provided, it is recommended to use a UTC-aware datetime. If the datetime is naive, it is assumed to be local time.limit (Optional[
int]) – The number of entitlements to retrieve. IfNone, retrieves every entitlement, which may be slow. Defaults to100.exclude_ended (
bool) – Whether to limit the fetched entitlements to those that have not ended. Defaults toFalse.
- Yields:
Entitlement– The application’s entitlements.- Raises:
HTTPException – Retrieving the entitlements failed.
- await fetch_message(id, /)¶
This function is a coroutine.
Retrieves a single
Messagefrom the destination.- Parameters:
id (
int) – The message ID to look for.- Returns:
The message asked for.
- Return type:
- Raises:
NotFound – The specified message was not found.
Forbidden – You do not have the permissions required to get a message.
HTTPException – Retrieving the message failed.
- await get_dm_channel() DMChannel | None¶
Returns the channel associated with this user if it exists.
If this returns
None, you can create a DM channel by calling thecreate_dm()coroutine function.
- await get_mutual_guilds() list[Guild]¶
The guilds that the user shares with the client.
Note
This will only return mutual guilds within the client’s internal cache.
Added in version 1.7.
- get_role(role_id, /)¶
Returns a role with the given ID from roles which the member has.
Added in version 2.0.
- Parameters:
role_id (
int) – The ID to search for.- Returns:
The role or
Noneif not found in the member’s roles.- Return type:
Optional[
Role]
- property guild_avatar: Asset | None¶
Returns an
Assetfor the guild avatar the member has. If unavailable,Noneis returned.Added in version 2.0.
- property guild_banner: Asset | None¶
Returns an
Assetfor the guild banner the member has. If unavailable,Noneis returned.Added in version 2.7.
- property guild_permissions: Permissions¶
Returns the member’s guild permissions.
This only takes into consideration the guild permissions and not most of the implied permissions or any of the channel permission overwrites. For 100% accurate permission calculation, please use
abc.GuildChannel.permissions_for().This does take into consideration guild ownership and the administrator implication.
- history(*, limit=100, before=None, after=None, around=None, oldest_first=None)¶
Returns an
AsyncIteratorthat enables receiving the destination’s message history.You must have
read_message_historypermissions to use this.- Parameters:
limit (Optional[
int]) – The number of messages to retrieve. IfNone, retrieves every message in the channel. Note, however, that this would make it a slow operation.before (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages before this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.after (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages after this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.around (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages around this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time. When using this argument, the maximum limit is 101. Note that if the limit is an even number, then this will return at most limit + 1 messages.oldest_first (Optional[
bool]) – If set toTrue, return messages in oldest->newest order. Defaults toTrueifafteris specified, otherwiseFalse.
- Yields:
Message– The message with the message data parsed.- Raises:
Forbidden – You do not have permissions to get channel message history.
HTTPException – The request to get message history failed.
- Return type:
HistoryIterator
Examples
Usage
counter = 0 async for message in channel.history(limit=200): if message.author == client.user: counter += 1
Flattening into a list:
messages = await channel.history(limit=123).flatten() # messages is now a list of Message...
All parameters are optional.
- property id¶
Equivalent to
User.id
- property is_migrated¶
Equivalent to
User.is_migrated
- is_on_mobile()¶
A helper function that determines if a member is active on a mobile device.
- Return type:
- property jump_url¶
Equivalent to
User.jump_url
- await kick(*, reason=None)¶
This function is a coroutine.
Kicks this member. Equivalent to
Guild.kick().
- mentioned_in(message)¶
Checks if the member is mentioned in the specified message.
- Parameters:
message (
Message) – The message to check if you’re mentioned in.- Returns:
Indicates if the member is mentioned in the message.
- Return type:
- property mobile_status: Status¶
The member’s status on a mobile device, if applicable.
- await move_to(channel, *, reason=None)¶
This function is a coroutine.
Moves a member to a new voice channel (they must be connected first).
You must have the
move_memberspermission to use this.This raises the same exceptions as
edit().Changed in version 1.1: Can now pass
Noneto kick a member from voice.
- property name¶
Equivalent to
User.name
- property nameplate¶
Equivalent to
User.nameplate
- pins(*, limit=50, before=None)¶
Returns a
MessagePinIteratorthat enables receiving the destination’s pinned messages.You must have
read_message_historypermissions to use this.Warning
Starting from version 3.0, await channel.pins() will no longer return a list of
Message. See examples below for new usage instead.- Parameters:
limit (Optional[
int]) – The number of pinned messages to retrieve. IfNone, retrieves every pinned message in the channel.before (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages pinned before this datetime. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.
- Yields:
MessagePin– The pinned message.- Raises:
Forbidden – You do not have permissions to get pinned messages.
HTTPException – The request to get pinned messages failed.
- Return type:
MessagePinIterator
Examples
Usage
counter = 0 async for pin in channel.pins(limit=250): if pin.message.author == client.user: counter += 1
Flattening into a list:
pins = await channel.pins(limit=None).flatten() # pins is now a list of MessagePin...
All parameters are optional.
- property primary_guild¶
Equivalent to
User.primary_guild
- property public_flags¶
Equivalent to
User.public_flags
- await remove_roles(*roles, reason=None, atomic=True)¶
This function is a coroutine.
Removes
Roles from this member.You must have the
manage_rolespermission to use this, and the removedRoles must appear lower in the list of roles than the highest role of the member.- Parameters:
*roles (
abc.Snowflake) – An argument list ofabc.Snowflakerepresenting aRoleto remove from the member.reason (Optional[
str]) – The reason for removing these roles. Shows up on the audit log.atomic (
bool) – Whether to atomically remove roles. This will ensure that multiple operations will always be applied regardless of the current state of the cache.
- Raises:
Forbidden – You do not have permissions to remove these roles.
HTTPException – Removing the roles failed.
- Return type:
- await remove_timeout(*, reason=None)¶
This function is a coroutine.
Removes the timeout from a member.
You must have the
moderate_memberspermission to remove the timeout.This is equivalent to calling
timeout()and passingNoneto theuntilparameter.- Parameters:
reason (Optional[
str]) – The reason for doing this action. Shows up on the audit log.- Raises:
Forbidden – You do not have permissions to remove the timeout.
HTTPException – An error occurred doing the request.
- Return type:
- await request_to_speak()¶
This function is a coroutine.
Request to speak in the connected channel.
Only applies to stage channels. :rtype:
NoneNote
Requesting members that are not the client is equivalent to
editprovidingsuppressasFalse.Added in version 1.7.
- Raises:
Forbidden – You do not have the proper permissions to the action requested.
HTTPException – The operation failed.
- property roles: list[Role]¶
A
listofRolethat the member belongs to. Note that the first element of this list is always the default ‘@everyone’ role.These roles are sorted by their position in the role hierarchy.
- await send(content=None, *, tts=None, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, enforce_nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None, poll=None, suppress=None, silent=None)¶
This function is a coroutine.
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through
str(content). If the content is set toNone(the default), then theembedparameter must be provided.To upload a single file, the
fileparameter should be used with a singleFileobject. To upload multiple files, thefilesparameter should be used with alistofFileobjects. Specifying both parameters will lead to an exception.To upload a single embed, the
embedparameter should be used with a singleEmbedobject. To upload multiple embeds, theembedsparameter should be used with alistofEmbedobjects. Specifying both parameters will lead to an exception.- Parameters:
content (Optional[
str]) – The content of the message to send.tts (
bool) – Indicates if the message should be sent using text-to-speech.embed (
Embed) – The rich embed for the content.file (
File) – The file to upload.files (List[
File]) – A list of files to upload. Must be a maximum of 10.nonce (Union[
str,int]) – The nonce to use for sending this message. If the message was successfully sent, then the message will have a nonce with this value.enforce_nonce (Optional[
bool]) –Whether
nonceis enforced to be validated.Added in version 2.5.
delete_after (
float) – If provided, the number of seconds to wait in the background before deleting the message we just sent. If the deletion fails, then it is silently ignored.allowed_mentions (
AllowedMentions) –Controls the mentions being processed in this message. If this is passed, then the object is merged with
allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set inallowed_mentions. If no object is passed at all then the defaults given byallowed_mentionsare used instead.Added in version 1.4.
reference (Union[
Message,MessageReference,PartialMessage]) –A reference to the
Messagebeing replied to or forwarded. This can be created usingto_reference(). When replying, you can control whether this mentions the author of the referenced message using thereplied_userattribute ofallowed_mentionsor by settingmention_author.Added in version 1.6.
mention_author (Optional[
bool]) –If set, overrides the
replied_userattribute ofallowed_mentions.Added in version 1.6.
view (
discord.ui.View) – A Discord UI View to add to the message.embeds (List[
Embed]) –A list of embeds to upload. Must be a maximum of 10.
Added in version 2.0.
stickers (Sequence[Union[
GuildSticker,StickerItem]]) –A list of stickers to upload. Must be a maximum of 3.
Added in version 2.0.
suppress (
bool) – Whether to suppress embeds for the message.silent (
bool) –Whether to suppress push and desktop notifications for the message.
Added in version 2.4.
poll (
Poll) –The poll to send.
Added in version 2.6.
- Returns:
The message that was sent.
- Return type:
- Raises:
HTTPException – Sending the message failed.
Forbidden – You do not have the proper permissions to send the message.
InvalidArgument – The
fileslist is not of the appropriate size, you specified bothfileandfiles, or you specified bothembedandembeds, or thereferenceobject is not aMessage,MessageReferenceorPartialMessage.
- property status: Status¶
The member’s overall status. If the value is unknown, then it will be a
strinstead.
- property system¶
Equivalent to
User.system
- await timeout(until, *, reason=None)¶
This function is a coroutine.
Applies a timeout to a member in the guild until a set datetime.
You must have the
moderate_memberspermission to timeout a member.- Parameters:
until (
datetime.datetime) – The date and time to timeout the member for. If this isNonethen the member is removed from timeout.reason (Optional[
str]) – The reason for doing this action. Shows up on the audit log.
- Raises:
Forbidden – You do not have permissions to timeout members.
HTTPException – An error occurred doing the request.
- Return type:
- await timeout_for(duration, *, reason=None)¶
This function is a coroutine.
Applies a timeout to a member in the guild for a set duration. A shortcut method for
timeout(), and equivalent totimeout(until=datetime.utcnow() + duration, reason=reason).You must have the
moderate_memberspermission to timeout a member.- Parameters:
duration (
datetime.timedelta) – The duration to timeout the member for.reason (Optional[
str]) – The reason for doing this action. Shows up on the audit log.
- Raises:
Forbidden – You do not have permissions to timeout members.
HTTPException – An error occurred doing the request.
- Return type:
- property top_role: Role¶
Returns the member’s highest role.
This is useful for figuring where a member stands in the role hierarchy chain.
- await trigger_typing()¶
This function is a coroutine.
Triggers a typing indicator to the destination.
Typing indicator will go away after 10 seconds, or after a message is sent.
- Return type:
- typing()¶
Returns a context manager that allows you to type for an indefinite period of time.
This is useful for denoting long computations in your bot. :rtype:
TypingNote
This is both a regular context manager and an async context manager. This means that both
withandasync withwork with this.Example Usage:
async with channel.typing(): # simulate something heavy await asyncio.sleep(10) await channel.send("done!")
- await unban(*, reason=None)¶
This function is a coroutine.
Unbans this member. Equivalent to
Guild.unban().
- property voice: VoiceState | None¶
Returns the member’s current voice state.
- property web_status: Status¶
The member’s status on the web client, if applicable.
- class discord.events.GuildMemberRemove[source]¶
Called when a member leaves a guild.
This requires
Intents.membersto be enabled.This event inherits from
Member.- property accent_color¶
Equivalent to
User.accent_color
- property accent_colour¶
Equivalent to
User.accent_colour
- property activity: Activity | Game | CustomActivity | Streaming | Spotify | None¶
Returns the primary activity the user is currently doing. Could be
Noneif no activity is being done.Note
Due to a Discord API limitation, this may be
Noneif the user is listening to a song on Spotify with a title longer than 128 characters.Note
A user may have multiple activities, these can be accessed under
activities.
- await add_roles(*roles, reason=None, atomic=True)¶
This function is a coroutine.
Gives the member a number of
Roles.You must have the
manage_rolespermission to use this, and the addedRoles must appear lower in the list of roles than the highest role of the member.- Parameters:
*roles (
abc.Snowflake) – An argument list ofabc.Snowflakerepresenting aRoleto give to the member.reason (Optional[
str]) – The reason for adding these roles. Shows up on the audit log.atomic (
bool) – Whether to atomically add roles. This will ensure that multiple operations will always be applied regardless of the current state of the cache.
- Raises:
Forbidden – You do not have permissions to add these roles.
HTTPException – Adding roles failed.
- Return type:
- property avatar¶
Equivalent to
User.avatar
- property avatar_decoration¶
Equivalent to
User.avatar_decoration
- await ban(*, delete_message_seconds=None, reason=None)¶
This function is a coroutine.
Bans this member. Equivalent to
Guild.ban().
- property banner¶
Equivalent to
User.banner
- property bot¶
Equivalent to
User.bot
- can_send(*objects)¶
Returns a
boolindicating whether you have the permissions to send the object(s).
- property color: Colour¶
A property that returns a color denoting the rendered color for the member. If the default color is the one rendered then an instance of
Colour.default()is returned.There is an alias for this named
colour.
- property colour: Colour¶
A property that returns a colour denoting the rendered colour for the member. If the default colour is the one rendered then an instance of
Colour.default()is returned.There is an alias for this named
color.
- await create_dm() DMChannel¶
This function is a coroutine.
Creates a
DMChannelwith this user.This should be rarely called, as this is done transparently for most people.
- Returns:
The channel that was created.
- Return type:
- await create_test_entitlement(sku: discord.abc.Snowflake) Entitlement¶
This function is a coroutine.
Creates a test entitlement for the user.
- Parameters:
sku (
Snowflake) – The SKU to create a test entitlement for.- Returns:
The created entitlement.
- Return type:
Entitlement
- property created_at¶
Equivalent to
User.created_at
- property default_avatar¶
Equivalent to
User.default_avatar
- property desktop_status: Status¶
The member’s status on the desktop client, if applicable.
- property discriminator¶
Equivalent to
User.discriminator
- property display_avatar: Asset¶
Returns the member’s display avatar.
For regular members this is just their avatar, but if they have a guild specific avatar then that is returned instead.
Added in version 2.0.
- property display_banner: Asset | None¶
Returns the member’s display banner.
For regular members this is just their banner, but if they have a guild specific banner then that is returned instead.
Added in version 2.7.
- property display_name: str¶
Returns the user’s display name. This will either be their guild specific nickname, global name or username.
- await edit(*, nick=Undefined.MISSING, mute=Undefined.MISSING, deafen=Undefined.MISSING, suppress=Undefined.MISSING, roles=Undefined.MISSING, voice_channel=Undefined.MISSING, reason=None, communication_disabled_until=Undefined.MISSING, bypass_verification=Undefined.MISSING, banner=Undefined.MISSING, avatar=Undefined.MISSING, bio=Undefined.MISSING)¶
This function is a coroutine.
Edits the member’s data.
Depending on the parameter passed, this requires different permissions listed below:
Parameter
Permission
nick
Permissions.manage_nicknamesmute
Permissions.mute_membersdeafen
Permissions.deafen_membersroles
Permissions.manage_rolesvoice_channel
Permissions.move_memberscommunication_disabled_until
Permissions.moderate_membersbypass_verification
See note below
Note
bypass_verification may be edited under three scenarios:
Client has
Permissions.manage_guildClient has
Permissions.manage_rolesClient has ALL THREE of
Permissions.moderate_members,Permissions.kick_members, andPermissions.ban_members
Note
The following parameters are only available when editing the bot’s own member:
avatarbannerbio
All parameters are optional.
Changed in version 1.1: Can now pass
Nonetovoice_channelto kick a member from voice.Changed in version 2.0: The newly member is now optionally returned, if applicable.
- Parameters:
nick (Optional[
str]) – The member’s new nickname. UseNoneto remove the nickname.mute (
bool) – Indicates if the member should be guild muted or un-muted.deafen (
bool) – Indicates if the member should be guild deafened or un-deafened.suppress (
bool) –Indicates if the member should be suppressed in stage channels.
Added in version 1.7.
roles (List[
Role]) – The member’s new list of roles. This replaces the roles.voice_channel (Optional[Union[
VoiceChannel,StageChannel]]) – The voice channel to move the member to. PassNoneto kick them from voice.reason (Optional[
str]) – The reason for editing this member. Shows up on the audit log.communication_disabled_until (Optional[
datetime.datetime]) –Temporarily puts the member in timeout until this time. If the value is
None, then the user is removed from timeout.Added in version 2.0.
bypass_verification (Optional[
bool]) –Indicates if the member should bypass the guild’s verification requirements.
Added in version 2.6.
banner (Optional[
bytes]) –A bytes-like object representing the banner. Could be
Noneto denote removal of the banner.This is only available when editing the bot’s own member (i.e.
Guild.me).Added in version 2.7.
avatar (Optional[
bytes]) –A bytes-like object representing the avatar. Could be
Noneto denote removal of the avatar.This is only available when editing the bot’s own member (i.e.
Guild.me).Added in version 2.7.
bio (Optional[
str]) –The new bio for the member. Could be
Noneto denote removal of the bio.This is only available when editing the bot’s own member (i.e.
Guild.me).Added in version 2.7.
- Returns:
The newly updated member, if applicable. This is only returned when certain fields are updated.
- Return type:
Optional[
Member]- Raises:
Forbidden – You do not have the proper permissions to the action requested.
HTTPException – The operation failed.
InvalidArgument – You tried to edit the avatar, banner, or bio of a member that is not the bot.
- entitlements(skus: list[Snowflake] | None = None, before: SnowflakeTime | None = None, after: SnowflakeTime | None = None, limit: int | None = 100, exclude_ended: bool = False) EntitlementIterator¶
Returns an
AsyncIteratorthat enables fetching the user’s entitlements.This is identical to
Client.entitlements()with theuserparameter.Added in version 2.6.
- Parameters:
skus (list[
abc.Snowflake] | None) – Limit the fetched entitlements to entitlements that are for these SKUs.before (
abc.Snowflake|datetime.datetime| None) – Retrieves guilds before this date or object. If a datetime is provided, it is recommended to use a UTC-aware datetime. If the datetime is naive, it is assumed to be local time.after (
abc.Snowflake|datetime.datetime| None) – Retrieve guilds after this date or object. If a datetime is provided, it is recommended to use a UTC-aware datetime. If the datetime is naive, it is assumed to be local time.limit (Optional[
int]) – The number of entitlements to retrieve. IfNone, retrieves every entitlement, which may be slow. Defaults to100.exclude_ended (
bool) – Whether to limit the fetched entitlements to those that have not ended. Defaults toFalse.
- Yields:
Entitlement– The application’s entitlements.- Raises:
HTTPException – Retrieving the entitlements failed.
- await fetch_message(id, /)¶
This function is a coroutine.
Retrieves a single
Messagefrom the destination.- Parameters:
id (
int) – The message ID to look for.- Returns:
The message asked for.
- Return type:
- Raises:
NotFound – The specified message was not found.
Forbidden – You do not have the permissions required to get a message.
HTTPException – Retrieving the message failed.
- await get_dm_channel() DMChannel | None¶
Returns the channel associated with this user if it exists.
If this returns
None, you can create a DM channel by calling thecreate_dm()coroutine function.
- await get_mutual_guilds() list[Guild]¶
The guilds that the user shares with the client.
Note
This will only return mutual guilds within the client’s internal cache.
Added in version 1.7.
- get_role(role_id, /)¶
Returns a role with the given ID from roles which the member has.
Added in version 2.0.
- Parameters:
role_id (
int) – The ID to search for.- Returns:
The role or
Noneif not found in the member’s roles.- Return type:
Optional[
Role]
- property guild_avatar: Asset | None¶
Returns an
Assetfor the guild avatar the member has. If unavailable,Noneis returned.Added in version 2.0.
- property guild_banner: Asset | None¶
Returns an
Assetfor the guild banner the member has. If unavailable,Noneis returned.Added in version 2.7.
- property guild_permissions: Permissions¶
Returns the member’s guild permissions.
This only takes into consideration the guild permissions and not most of the implied permissions or any of the channel permission overwrites. For 100% accurate permission calculation, please use
abc.GuildChannel.permissions_for().This does take into consideration guild ownership and the administrator implication.
- history(*, limit=100, before=None, after=None, around=None, oldest_first=None)¶
Returns an
AsyncIteratorthat enables receiving the destination’s message history.You must have
read_message_historypermissions to use this.- Parameters:
limit (Optional[
int]) – The number of messages to retrieve. IfNone, retrieves every message in the channel. Note, however, that this would make it a slow operation.before (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages before this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.after (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages after this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.around (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages around this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time. When using this argument, the maximum limit is 101. Note that if the limit is an even number, then this will return at most limit + 1 messages.oldest_first (Optional[
bool]) – If set toTrue, return messages in oldest->newest order. Defaults toTrueifafteris specified, otherwiseFalse.
- Yields:
Message– The message with the message data parsed.- Raises:
Forbidden – You do not have permissions to get channel message history.
HTTPException – The request to get message history failed.
- Return type:
HistoryIterator
Examples
Usage
counter = 0 async for message in channel.history(limit=200): if message.author == client.user: counter += 1
Flattening into a list:
messages = await channel.history(limit=123).flatten() # messages is now a list of Message...
All parameters are optional.
- property id¶
Equivalent to
User.id
- property is_migrated¶
Equivalent to
User.is_migrated
- is_on_mobile()¶
A helper function that determines if a member is active on a mobile device.
- Return type:
- property jump_url¶
Equivalent to
User.jump_url
- await kick(*, reason=None)¶
This function is a coroutine.
Kicks this member. Equivalent to
Guild.kick().
- mentioned_in(message)¶
Checks if the member is mentioned in the specified message.
- Parameters:
message (
Message) – The message to check if you’re mentioned in.- Returns:
Indicates if the member is mentioned in the message.
- Return type:
- property mobile_status: Status¶
The member’s status on a mobile device, if applicable.
- await move_to(channel, *, reason=None)¶
This function is a coroutine.
Moves a member to a new voice channel (they must be connected first).
You must have the
move_memberspermission to use this.This raises the same exceptions as
edit().Changed in version 1.1: Can now pass
Noneto kick a member from voice.
- property name¶
Equivalent to
User.name
- property nameplate¶
Equivalent to
User.nameplate
- pins(*, limit=50, before=None)¶
Returns a
MessagePinIteratorthat enables receiving the destination’s pinned messages.You must have
read_message_historypermissions to use this.Warning
Starting from version 3.0, await channel.pins() will no longer return a list of
Message. See examples below for new usage instead.- Parameters:
limit (Optional[
int]) – The number of pinned messages to retrieve. IfNone, retrieves every pinned message in the channel.before (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages pinned before this datetime. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.
- Yields:
MessagePin– The pinned message.- Raises:
Forbidden – You do not have permissions to get pinned messages.
HTTPException – The request to get pinned messages failed.
- Return type:
MessagePinIterator
Examples
Usage
counter = 0 async for pin in channel.pins(limit=250): if pin.message.author == client.user: counter += 1
Flattening into a list:
pins = await channel.pins(limit=None).flatten() # pins is now a list of MessagePin...
All parameters are optional.
- property primary_guild¶
Equivalent to
User.primary_guild
- property public_flags¶
Equivalent to
User.public_flags
- await remove_roles(*roles, reason=None, atomic=True)¶
This function is a coroutine.
Removes
Roles from this member.You must have the
manage_rolespermission to use this, and the removedRoles must appear lower in the list of roles than the highest role of the member.- Parameters:
*roles (
abc.Snowflake) – An argument list ofabc.Snowflakerepresenting aRoleto remove from the member.reason (Optional[
str]) – The reason for removing these roles. Shows up on the audit log.atomic (
bool) – Whether to atomically remove roles. This will ensure that multiple operations will always be applied regardless of the current state of the cache.
- Raises:
Forbidden – You do not have permissions to remove these roles.
HTTPException – Removing the roles failed.
- Return type:
- await remove_timeout(*, reason=None)¶
This function is a coroutine.
Removes the timeout from a member.
You must have the
moderate_memberspermission to remove the timeout.This is equivalent to calling
timeout()and passingNoneto theuntilparameter.- Parameters:
reason (Optional[
str]) – The reason for doing this action. Shows up on the audit log.- Raises:
Forbidden – You do not have permissions to remove the timeout.
HTTPException – An error occurred doing the request.
- Return type:
- await request_to_speak()¶
This function is a coroutine.
Request to speak in the connected channel.
Only applies to stage channels. :rtype:
NoneNote
Requesting members that are not the client is equivalent to
editprovidingsuppressasFalse.Added in version 1.7.
- Raises:
Forbidden – You do not have the proper permissions to the action requested.
HTTPException – The operation failed.
- property roles: list[Role]¶
A
listofRolethat the member belongs to. Note that the first element of this list is always the default ‘@everyone’ role.These roles are sorted by their position in the role hierarchy.
- await send(content=None, *, tts=None, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, enforce_nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None, poll=None, suppress=None, silent=None)¶
This function is a coroutine.
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through
str(content). If the content is set toNone(the default), then theembedparameter must be provided.To upload a single file, the
fileparameter should be used with a singleFileobject. To upload multiple files, thefilesparameter should be used with alistofFileobjects. Specifying both parameters will lead to an exception.To upload a single embed, the
embedparameter should be used with a singleEmbedobject. To upload multiple embeds, theembedsparameter should be used with alistofEmbedobjects. Specifying both parameters will lead to an exception.- Parameters:
content (Optional[
str]) – The content of the message to send.tts (
bool) – Indicates if the message should be sent using text-to-speech.embed (
Embed) – The rich embed for the content.file (
File) – The file to upload.files (List[
File]) – A list of files to upload. Must be a maximum of 10.nonce (Union[
str,int]) – The nonce to use for sending this message. If the message was successfully sent, then the message will have a nonce with this value.enforce_nonce (Optional[
bool]) –Whether
nonceis enforced to be validated.Added in version 2.5.
delete_after (
float) – If provided, the number of seconds to wait in the background before deleting the message we just sent. If the deletion fails, then it is silently ignored.allowed_mentions (
AllowedMentions) –Controls the mentions being processed in this message. If this is passed, then the object is merged with
allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set inallowed_mentions. If no object is passed at all then the defaults given byallowed_mentionsare used instead.Added in version 1.4.
reference (Union[
Message,MessageReference,PartialMessage]) –A reference to the
Messagebeing replied to or forwarded. This can be created usingto_reference(). When replying, you can control whether this mentions the author of the referenced message using thereplied_userattribute ofallowed_mentionsor by settingmention_author.Added in version 1.6.
mention_author (Optional[
bool]) –If set, overrides the
replied_userattribute ofallowed_mentions.Added in version 1.6.
view (
discord.ui.View) – A Discord UI View to add to the message.embeds (List[
Embed]) –A list of embeds to upload. Must be a maximum of 10.
Added in version 2.0.
stickers (Sequence[Union[
GuildSticker,StickerItem]]) –A list of stickers to upload. Must be a maximum of 3.
Added in version 2.0.
suppress (
bool) – Whether to suppress embeds for the message.silent (
bool) –Whether to suppress push and desktop notifications for the message.
Added in version 2.4.
poll (
Poll) –The poll to send.
Added in version 2.6.
- Returns:
The message that was sent.
- Return type:
- Raises:
HTTPException – Sending the message failed.
Forbidden – You do not have the proper permissions to send the message.
InvalidArgument – The
fileslist is not of the appropriate size, you specified bothfileandfiles, or you specified bothembedandembeds, or thereferenceobject is not aMessage,MessageReferenceorPartialMessage.
- property status: Status¶
The member’s overall status. If the value is unknown, then it will be a
strinstead.
- property system¶
Equivalent to
User.system
- await timeout(until, *, reason=None)¶
This function is a coroutine.
Applies a timeout to a member in the guild until a set datetime.
You must have the
moderate_memberspermission to timeout a member.- Parameters:
until (
datetime.datetime) – The date and time to timeout the member for. If this isNonethen the member is removed from timeout.reason (Optional[
str]) – The reason for doing this action. Shows up on the audit log.
- Raises:
Forbidden – You do not have permissions to timeout members.
HTTPException – An error occurred doing the request.
- Return type:
- await timeout_for(duration, *, reason=None)¶
This function is a coroutine.
Applies a timeout to a member in the guild for a set duration. A shortcut method for
timeout(), and equivalent totimeout(until=datetime.utcnow() + duration, reason=reason).You must have the
moderate_memberspermission to timeout a member.- Parameters:
duration (
datetime.timedelta) – The duration to timeout the member for.reason (Optional[
str]) – The reason for doing this action. Shows up on the audit log.
- Raises:
Forbidden – You do not have permissions to timeout members.
HTTPException – An error occurred doing the request.
- Return type:
- property top_role: Role¶
Returns the member’s highest role.
This is useful for figuring where a member stands in the role hierarchy chain.
- await trigger_typing()¶
This function is a coroutine.
Triggers a typing indicator to the destination.
Typing indicator will go away after 10 seconds, or after a message is sent.
- Return type:
- typing()¶
Returns a context manager that allows you to type for an indefinite period of time.
This is useful for denoting long computations in your bot. :rtype:
TypingNote
This is both a regular context manager and an async context manager. This means that both
withandasync withwork with this.Example Usage:
async with channel.typing(): # simulate something heavy await asyncio.sleep(10) await channel.send("done!")
- await unban(*, reason=None)¶
This function is a coroutine.
Unbans this member. Equivalent to
Guild.unban().
- property voice: VoiceState | None¶
Returns the member’s current voice state.
- property web_status: Status¶
The member’s status on the web client, if applicable.
- class discord.events.GuildMemberUpdate[source]¶
Called when a member updates their profile.
This is called when one or more of the following things change: - nickname - roles - pending - communication_disabled_until - timed_out
This requires
Intents.membersto be enabled.This event inherits from
Member.- old¶
The member’s old info before the update.
- Type:
Member
- property accent_color¶
Equivalent to
User.accent_color
- property accent_colour¶
Equivalent to
User.accent_colour
- property activity: Activity | Game | CustomActivity | Streaming | Spotify | None¶
Returns the primary activity the user is currently doing. Could be
Noneif no activity is being done.Note
Due to a Discord API limitation, this may be
Noneif the user is listening to a song on Spotify with a title longer than 128 characters.Note
A user may have multiple activities, these can be accessed under
activities.
- await add_roles(*roles, reason=None, atomic=True)¶
This function is a coroutine.
Gives the member a number of
Roles.You must have the
manage_rolespermission to use this, and the addedRoles must appear lower in the list of roles than the highest role of the member.- Parameters:
*roles (
abc.Snowflake) – An argument list ofabc.Snowflakerepresenting aRoleto give to the member.reason (Optional[
str]) – The reason for adding these roles. Shows up on the audit log.atomic (
bool) – Whether to atomically add roles. This will ensure that multiple operations will always be applied regardless of the current state of the cache.
- Raises:
Forbidden – You do not have permissions to add these roles.
HTTPException – Adding roles failed.
- Return type:
- property avatar¶
Equivalent to
User.avatar
- property avatar_decoration¶
Equivalent to
User.avatar_decoration
- await ban(*, delete_message_seconds=None, reason=None)¶
This function is a coroutine.
Bans this member. Equivalent to
Guild.ban().
- property banner¶
Equivalent to
User.banner
- property bot¶
Equivalent to
User.bot
- can_send(*objects)¶
Returns a
boolindicating whether you have the permissions to send the object(s).
- property color: Colour¶
A property that returns a color denoting the rendered color for the member. If the default color is the one rendered then an instance of
Colour.default()is returned.There is an alias for this named
colour.
- property colour: Colour¶
A property that returns a colour denoting the rendered colour for the member. If the default colour is the one rendered then an instance of
Colour.default()is returned.There is an alias for this named
color.
- await create_dm() DMChannel¶
This function is a coroutine.
Creates a
DMChannelwith this user.This should be rarely called, as this is done transparently for most people.
- Returns:
The channel that was created.
- Return type:
- await create_test_entitlement(sku: discord.abc.Snowflake) Entitlement¶
This function is a coroutine.
Creates a test entitlement for the user.
- Parameters:
sku (
Snowflake) – The SKU to create a test entitlement for.- Returns:
The created entitlement.
- Return type:
Entitlement
- property created_at¶
Equivalent to
User.created_at
- property default_avatar¶
Equivalent to
User.default_avatar
- property desktop_status: Status¶
The member’s status on the desktop client, if applicable.
- property discriminator¶
Equivalent to
User.discriminator
- property display_avatar: Asset¶
Returns the member’s display avatar.
For regular members this is just their avatar, but if they have a guild specific avatar then that is returned instead.
Added in version 2.0.
- property display_banner: Asset | None¶
Returns the member’s display banner.
For regular members this is just their banner, but if they have a guild specific banner then that is returned instead.
Added in version 2.7.
- property display_name: str¶
Returns the user’s display name. This will either be their guild specific nickname, global name or username.
- await edit(*, nick=Undefined.MISSING, mute=Undefined.MISSING, deafen=Undefined.MISSING, suppress=Undefined.MISSING, roles=Undefined.MISSING, voice_channel=Undefined.MISSING, reason=None, communication_disabled_until=Undefined.MISSING, bypass_verification=Undefined.MISSING, banner=Undefined.MISSING, avatar=Undefined.MISSING, bio=Undefined.MISSING)¶
This function is a coroutine.
Edits the member’s data.
Depending on the parameter passed, this requires different permissions listed below:
Parameter
Permission
nick
Permissions.manage_nicknamesmute
Permissions.mute_membersdeafen
Permissions.deafen_membersroles
Permissions.manage_rolesvoice_channel
Permissions.move_memberscommunication_disabled_until
Permissions.moderate_membersbypass_verification
See note below
Note
bypass_verification may be edited under three scenarios:
Client has
Permissions.manage_guildClient has
Permissions.manage_rolesClient has ALL THREE of
Permissions.moderate_members,Permissions.kick_members, andPermissions.ban_members
Note
The following parameters are only available when editing the bot’s own member:
avatarbannerbio
All parameters are optional.
Changed in version 1.1: Can now pass
Nonetovoice_channelto kick a member from voice.Changed in version 2.0: The newly member is now optionally returned, if applicable.
- Parameters:
nick (Optional[
str]) – The member’s new nickname. UseNoneto remove the nickname.mute (
bool) – Indicates if the member should be guild muted or un-muted.deafen (
bool) – Indicates if the member should be guild deafened or un-deafened.suppress (
bool) –Indicates if the member should be suppressed in stage channels.
Added in version 1.7.
roles (List[
Role]) – The member’s new list of roles. This replaces the roles.voice_channel (Optional[Union[
VoiceChannel,StageChannel]]) – The voice channel to move the member to. PassNoneto kick them from voice.reason (Optional[
str]) – The reason for editing this member. Shows up on the audit log.communication_disabled_until (Optional[
datetime.datetime]) –Temporarily puts the member in timeout until this time. If the value is
None, then the user is removed from timeout.Added in version 2.0.
bypass_verification (Optional[
bool]) –Indicates if the member should bypass the guild’s verification requirements.
Added in version 2.6.
banner (Optional[
bytes]) –A bytes-like object representing the banner. Could be
Noneto denote removal of the banner.This is only available when editing the bot’s own member (i.e.
Guild.me).Added in version 2.7.
avatar (Optional[
bytes]) –A bytes-like object representing the avatar. Could be
Noneto denote removal of the avatar.This is only available when editing the bot’s own member (i.e.
Guild.me).Added in version 2.7.
bio (Optional[
str]) –The new bio for the member. Could be
Noneto denote removal of the bio.This is only available when editing the bot’s own member (i.e.
Guild.me).Added in version 2.7.
- Returns:
The newly updated member, if applicable. This is only returned when certain fields are updated.
- Return type:
Optional[
Member]- Raises:
Forbidden – You do not have the proper permissions to the action requested.
HTTPException – The operation failed.
InvalidArgument – You tried to edit the avatar, banner, or bio of a member that is not the bot.
- entitlements(skus: list[Snowflake] | None = None, before: SnowflakeTime | None = None, after: SnowflakeTime | None = None, limit: int | None = 100, exclude_ended: bool = False) EntitlementIterator¶
Returns an
AsyncIteratorthat enables fetching the user’s entitlements.This is identical to
Client.entitlements()with theuserparameter.Added in version 2.6.
- Parameters:
skus (list[
abc.Snowflake] | None) – Limit the fetched entitlements to entitlements that are for these SKUs.before (
abc.Snowflake|datetime.datetime| None) – Retrieves guilds before this date or object. If a datetime is provided, it is recommended to use a UTC-aware datetime. If the datetime is naive, it is assumed to be local time.after (
abc.Snowflake|datetime.datetime| None) – Retrieve guilds after this date or object. If a datetime is provided, it is recommended to use a UTC-aware datetime. If the datetime is naive, it is assumed to be local time.limit (Optional[
int]) – The number of entitlements to retrieve. IfNone, retrieves every entitlement, which may be slow. Defaults to100.exclude_ended (
bool) – Whether to limit the fetched entitlements to those that have not ended. Defaults toFalse.
- Yields:
Entitlement– The application’s entitlements.- Raises:
HTTPException – Retrieving the entitlements failed.
- await fetch_message(id, /)¶
This function is a coroutine.
Retrieves a single
Messagefrom the destination.- Parameters:
id (
int) – The message ID to look for.- Returns:
The message asked for.
- Return type:
- Raises:
NotFound – The specified message was not found.
Forbidden – You do not have the permissions required to get a message.
HTTPException – Retrieving the message failed.
- await get_dm_channel() DMChannel | None¶
Returns the channel associated with this user if it exists.
If this returns
None, you can create a DM channel by calling thecreate_dm()coroutine function.
- await get_mutual_guilds() list[Guild]¶
The guilds that the user shares with the client.
Note
This will only return mutual guilds within the client’s internal cache.
Added in version 1.7.
- get_role(role_id, /)¶
Returns a role with the given ID from roles which the member has.
Added in version 2.0.
- Parameters:
role_id (
int) – The ID to search for.- Returns:
The role or
Noneif not found in the member’s roles.- Return type:
Optional[
Role]
- property guild_avatar: Asset | None¶
Returns an
Assetfor the guild avatar the member has. If unavailable,Noneis returned.Added in version 2.0.
- property guild_banner: Asset | None¶
Returns an
Assetfor the guild banner the member has. If unavailable,Noneis returned.Added in version 2.7.
- property guild_permissions: Permissions¶
Returns the member’s guild permissions.
This only takes into consideration the guild permissions and not most of the implied permissions or any of the channel permission overwrites. For 100% accurate permission calculation, please use
abc.GuildChannel.permissions_for().This does take into consideration guild ownership and the administrator implication.
- history(*, limit=100, before=None, after=None, around=None, oldest_first=None)¶
Returns an
AsyncIteratorthat enables receiving the destination’s message history.You must have
read_message_historypermissions to use this.- Parameters:
limit (Optional[
int]) – The number of messages to retrieve. IfNone, retrieves every message in the channel. Note, however, that this would make it a slow operation.before (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages before this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.after (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages after this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.around (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages around this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time. When using this argument, the maximum limit is 101. Note that if the limit is an even number, then this will return at most limit + 1 messages.oldest_first (Optional[
bool]) – If set toTrue, return messages in oldest->newest order. Defaults toTrueifafteris specified, otherwiseFalse.
- Yields:
Message– The message with the message data parsed.- Raises:
Forbidden – You do not have permissions to get channel message history.
HTTPException – The request to get message history failed.
- Return type:
HistoryIterator
Examples
Usage
counter = 0 async for message in channel.history(limit=200): if message.author == client.user: counter += 1
Flattening into a list:
messages = await channel.history(limit=123).flatten() # messages is now a list of Message...
All parameters are optional.
- property id¶
Equivalent to
User.id
- property is_migrated¶
Equivalent to
User.is_migrated
- is_on_mobile()¶
A helper function that determines if a member is active on a mobile device.
- Return type:
- property jump_url¶
Equivalent to
User.jump_url
- await kick(*, reason=None)¶
This function is a coroutine.
Kicks this member. Equivalent to
Guild.kick().
- mentioned_in(message)¶
Checks if the member is mentioned in the specified message.
- Parameters:
message (
Message) – The message to check if you’re mentioned in.- Returns:
Indicates if the member is mentioned in the message.
- Return type:
- property mobile_status: Status¶
The member’s status on a mobile device, if applicable.
- await move_to(channel, *, reason=None)¶
This function is a coroutine.
Moves a member to a new voice channel (they must be connected first).
You must have the
move_memberspermission to use this.This raises the same exceptions as
edit().Changed in version 1.1: Can now pass
Noneto kick a member from voice.
- property name¶
Equivalent to
User.name
- property nameplate¶
Equivalent to
User.nameplate
- pins(*, limit=50, before=None)¶
Returns a
MessagePinIteratorthat enables receiving the destination’s pinned messages.You must have
read_message_historypermissions to use this.Warning
Starting from version 3.0, await channel.pins() will no longer return a list of
Message. See examples below for new usage instead.- Parameters:
limit (Optional[
int]) – The number of pinned messages to retrieve. IfNone, retrieves every pinned message in the channel.before (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages pinned before this datetime. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.
- Yields:
MessagePin– The pinned message.- Raises:
Forbidden – You do not have permissions to get pinned messages.
HTTPException – The request to get pinned messages failed.
- Return type:
MessagePinIterator
Examples
Usage
counter = 0 async for pin in channel.pins(limit=250): if pin.message.author == client.user: counter += 1
Flattening into a list:
pins = await channel.pins(limit=None).flatten() # pins is now a list of MessagePin...
All parameters are optional.
- property primary_guild¶
Equivalent to
User.primary_guild
- property public_flags¶
Equivalent to
User.public_flags
- await remove_roles(*roles, reason=None, atomic=True)¶
This function is a coroutine.
Removes
Roles from this member.You must have the
manage_rolespermission to use this, and the removedRoles must appear lower in the list of roles than the highest role of the member.- Parameters:
*roles (
abc.Snowflake) – An argument list ofabc.Snowflakerepresenting aRoleto remove from the member.reason (Optional[
str]) – The reason for removing these roles. Shows up on the audit log.atomic (
bool) – Whether to atomically remove roles. This will ensure that multiple operations will always be applied regardless of the current state of the cache.
- Raises:
Forbidden – You do not have permissions to remove these roles.
HTTPException – Removing the roles failed.
- Return type:
- await remove_timeout(*, reason=None)¶
This function is a coroutine.
Removes the timeout from a member.
You must have the
moderate_memberspermission to remove the timeout.This is equivalent to calling
timeout()and passingNoneto theuntilparameter.- Parameters:
reason (Optional[
str]) – The reason for doing this action. Shows up on the audit log.- Raises:
Forbidden – You do not have permissions to remove the timeout.
HTTPException – An error occurred doing the request.
- Return type:
- await request_to_speak()¶
This function is a coroutine.
Request to speak in the connected channel.
Only applies to stage channels. :rtype:
NoneNote
Requesting members that are not the client is equivalent to
editprovidingsuppressasFalse.Added in version 1.7.
- Raises:
Forbidden – You do not have the proper permissions to the action requested.
HTTPException – The operation failed.
- property roles: list[Role]¶
A
listofRolethat the member belongs to. Note that the first element of this list is always the default ‘@everyone’ role.These roles are sorted by their position in the role hierarchy.
- await send(content=None, *, tts=None, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, enforce_nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None, poll=None, suppress=None, silent=None)¶
This function is a coroutine.
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through
str(content). If the content is set toNone(the default), then theembedparameter must be provided.To upload a single file, the
fileparameter should be used with a singleFileobject. To upload multiple files, thefilesparameter should be used with alistofFileobjects. Specifying both parameters will lead to an exception.To upload a single embed, the
embedparameter should be used with a singleEmbedobject. To upload multiple embeds, theembedsparameter should be used with alistofEmbedobjects. Specifying both parameters will lead to an exception.- Parameters:
content (Optional[
str]) – The content of the message to send.tts (
bool) – Indicates if the message should be sent using text-to-speech.embed (
Embed) – The rich embed for the content.file (
File) – The file to upload.files (List[
File]) – A list of files to upload. Must be a maximum of 10.nonce (Union[
str,int]) – The nonce to use for sending this message. If the message was successfully sent, then the message will have a nonce with this value.enforce_nonce (Optional[
bool]) –Whether
nonceis enforced to be validated.Added in version 2.5.
delete_after (
float) – If provided, the number of seconds to wait in the background before deleting the message we just sent. If the deletion fails, then it is silently ignored.allowed_mentions (
AllowedMentions) –Controls the mentions being processed in this message. If this is passed, then the object is merged with
allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set inallowed_mentions. If no object is passed at all then the defaults given byallowed_mentionsare used instead.Added in version 1.4.
reference (Union[
Message,MessageReference,PartialMessage]) –A reference to the
Messagebeing replied to or forwarded. This can be created usingto_reference(). When replying, you can control whether this mentions the author of the referenced message using thereplied_userattribute ofallowed_mentionsor by settingmention_author.Added in version 1.6.
mention_author (Optional[
bool]) –If set, overrides the
replied_userattribute ofallowed_mentions.Added in version 1.6.
view (
discord.ui.View) – A Discord UI View to add to the message.embeds (List[
Embed]) –A list of embeds to upload. Must be a maximum of 10.
Added in version 2.0.
stickers (Sequence[Union[
GuildSticker,StickerItem]]) –A list of stickers to upload. Must be a maximum of 3.
Added in version 2.0.
suppress (
bool) – Whether to suppress embeds for the message.silent (
bool) –Whether to suppress push and desktop notifications for the message.
Added in version 2.4.
poll (
Poll) –The poll to send.
Added in version 2.6.
- Returns:
The message that was sent.
- Return type:
- Raises:
HTTPException – Sending the message failed.
Forbidden – You do not have the proper permissions to send the message.
InvalidArgument – The
fileslist is not of the appropriate size, you specified bothfileandfiles, or you specified bothembedandembeds, or thereferenceobject is not aMessage,MessageReferenceorPartialMessage.
- property status: Status¶
The member’s overall status. If the value is unknown, then it will be a
strinstead.
- property system¶
Equivalent to
User.system
- await timeout(until, *, reason=None)¶
This function is a coroutine.
Applies a timeout to a member in the guild until a set datetime.
You must have the
moderate_memberspermission to timeout a member.- Parameters:
until (
datetime.datetime) – The date and time to timeout the member for. If this isNonethen the member is removed from timeout.reason (Optional[
str]) – The reason for doing this action. Shows up on the audit log.
- Raises:
Forbidden – You do not have permissions to timeout members.
HTTPException – An error occurred doing the request.
- Return type:
- await timeout_for(duration, *, reason=None)¶
This function is a coroutine.
Applies a timeout to a member in the guild for a set duration. A shortcut method for
timeout(), and equivalent totimeout(until=datetime.utcnow() + duration, reason=reason).You must have the
moderate_memberspermission to timeout a member.- Parameters:
duration (
datetime.timedelta) – The duration to timeout the member for.reason (Optional[
str]) – The reason for doing this action. Shows up on the audit log.
- Raises:
Forbidden – You do not have permissions to timeout members.
HTTPException – An error occurred doing the request.
- Return type:
- property top_role: Role¶
Returns the member’s highest role.
This is useful for figuring where a member stands in the role hierarchy chain.
- await trigger_typing()¶
This function is a coroutine.
Triggers a typing indicator to the destination.
Typing indicator will go away after 10 seconds, or after a message is sent.
- Return type:
- typing()¶
Returns a context manager that allows you to type for an indefinite period of time.
This is useful for denoting long computations in your bot. :rtype:
TypingNote
This is both a regular context manager and an async context manager. This means that both
withandasync withwork with this.Example Usage:
async with channel.typing(): # simulate something heavy await asyncio.sleep(10) await channel.send("done!")
- await unban(*, reason=None)¶
This function is a coroutine.
Unbans this member. Equivalent to
Guild.unban().
- property voice: VoiceState | None¶
Returns the member’s current voice state.
- property web_status: Status¶
The member’s status on the web client, if applicable.
- class discord.events.UserUpdate[source]¶
Called when a user updates their profile.
This is called when one or more of the following things change: - avatar - username - discriminator - global_name
This requires
Intents.membersto be enabled.This event inherits from
User.- old¶
The user’s old info before the update.
- Type:
User
- property accent_color: Colour | None¶
Returns the user’s accent color, if applicable.
There is an alias for this named
accent_colour.Added in version 2.0.
Note
This information is only available via
Client.fetch_user().
- property accent_colour: Colour | None¶
Returns the user’s accent colour, if applicable.
There is an alias for this named
accent_color.Added in version 2.0.
Note
This information is only available via
Client.fetch_user().
- property avatar: Asset | None¶
Returns an
Assetfor the avatar the user has.If the user does not have a traditional avatar,
Noneis returned. If you want the avatar that a user has displayed, considerdisplay_avatar.
- property avatar_decoration: Asset | None¶
Returns the user’s avatar decoration, if available.
Added in version 2.5.
- property banner: Asset | None¶
Returns the user’s banner asset, if available.
Added in version 2.0.
Note
This information is only available via
Client.fetch_user().
- can_send(*objects)¶
Returns a
boolindicating whether you have the permissions to send the object(s).
- property color: Colour¶
A property that returns a color denoting the rendered color for the user. This always returns
Colour.default().There is an alias for this named
colour.
- property colour: Colour¶
A property that returns a colour denoting the rendered colour for the user. This always returns
Colour.default().There is an alias for this named
color.
- await create_dm()¶
This function is a coroutine.
Creates a
DMChannelwith this user.This should be rarely called, as this is done transparently for most people.
- Returns:
The channel that was created.
- Return type:
- await create_test_entitlement(sku)¶
This function is a coroutine.
Creates a test entitlement for the user.
- Parameters:
sku (
Snowflake) – The SKU to create a test entitlement for.- Returns:
The created entitlement.
- Return type:
Entitlement
- property created_at: datetime¶
Returns the user’s creation time in UTC.
This is when the user’s Discord account was created.
- property default_avatar: Asset¶
Returns the default avatar for a given user. This is calculated by the user’s ID if they’re on the new username system, otherwise their discriminator.
- property display_avatar: Asset¶
Returns the user’s display avatar.
For regular users this is just their default avatar or uploaded avatar.
Added in version 2.0.
- property display_name: str¶
Returns the user’s display name. This will be their global name if set, otherwise their username.
- entitlements(skus=None, before=None, after=None, limit=100, exclude_ended=False)¶
Returns an
AsyncIteratorthat enables fetching the user’s entitlements.This is identical to
Client.entitlements()with theuserparameter.Added in version 2.6.
- Parameters:
skus (list[
abc.Snowflake] | None) – Limit the fetched entitlements to entitlements that are for these SKUs.before (
abc.Snowflake|datetime.datetime| None) – Retrieves guilds before this date or object. If a datetime is provided, it is recommended to use a UTC-aware datetime. If the datetime is naive, it is assumed to be local time.after (
abc.Snowflake|datetime.datetime| None) – Retrieve guilds after this date or object. If a datetime is provided, it is recommended to use a UTC-aware datetime. If the datetime is naive, it is assumed to be local time.limit (Optional[
int]) – The number of entitlements to retrieve. IfNone, retrieves every entitlement, which may be slow. Defaults to100.exclude_ended (
bool) – Whether to limit the fetched entitlements to those that have not ended. Defaults toFalse.
- Yields:
Entitlement– The application’s entitlements.- Raises:
HTTPException – Retrieving the entitlements failed.
- Return type:
EntitlementIterator
- await fetch_message(id, /)¶
This function is a coroutine.
Retrieves a single
Messagefrom the destination.- Parameters:
id (
int) – The message ID to look for.- Returns:
The message asked for.
- Return type:
- Raises:
NotFound – The specified message was not found.
Forbidden – You do not have the permissions required to get a message.
HTTPException – Retrieving the message failed.
- await get_dm_channel()¶
Returns the channel associated with this user if it exists.
If this returns
None, you can create a DM channel by calling thecreate_dm()coroutine function.- Return type:
DMChannel | None
- await get_mutual_guilds()¶
The guilds that the user shares with the client. :rtype: list[Guild]
Note
This will only return mutual guilds within the client’s internal cache.
Added in version 1.7.
- history(*, limit=100, before=None, after=None, around=None, oldest_first=None)¶
Returns an
AsyncIteratorthat enables receiving the destination’s message history.You must have
read_message_historypermissions to use this.- Parameters:
limit (Optional[
int]) – The number of messages to retrieve. IfNone, retrieves every message in the channel. Note, however, that this would make it a slow operation.before (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages before this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.after (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages after this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.around (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages around this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time. When using this argument, the maximum limit is 101. Note that if the limit is an even number, then this will return at most limit + 1 messages.oldest_first (Optional[
bool]) – If set toTrue, return messages in oldest->newest order. Defaults toTrueifafteris specified, otherwiseFalse.
- Yields:
Message– The message with the message data parsed.- Raises:
Forbidden – You do not have permissions to get channel message history.
HTTPException – The request to get message history failed.
- Return type:
HistoryIterator
Examples
Usage
counter = 0 async for message in channel.history(limit=200): if message.author == client.user: counter += 1
Flattening into a list:
messages = await channel.history(limit=123).flatten() # messages is now a list of Message...
All parameters are optional.
- property jump_url: str¶
Returns a URL that allows the client to jump to the user.
Added in version 2.0.
- mentioned_in(message)¶
Checks if the user is mentioned in the specified message.
- Parameters:
message (
Message) – The message to check if you’re mentioned in.- Returns:
Indicates if the user is mentioned in the message.
- Return type:
- pins(*, limit=50, before=None)¶
Returns a
MessagePinIteratorthat enables receiving the destination’s pinned messages.You must have
read_message_historypermissions to use this.Warning
Starting from version 3.0, await channel.pins() will no longer return a list of
Message. See examples below for new usage instead.- Parameters:
limit (Optional[
int]) – The number of pinned messages to retrieve. IfNone, retrieves every pinned message in the channel.before (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages pinned before this datetime. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.
- Yields:
MessagePin– The pinned message.- Raises:
Forbidden – You do not have permissions to get pinned messages.
HTTPException – The request to get pinned messages failed.
- Return type:
MessagePinIterator
Examples
Usage
counter = 0 async for pin in channel.pins(limit=250): if pin.message.author == client.user: counter += 1
Flattening into a list:
pins = await channel.pins(limit=None).flatten() # pins is now a list of MessagePin...
All parameters are optional.
- property public_flags: PublicUserFlags¶
The publicly available flags the user has.
- await send(content=None, *, tts=None, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, enforce_nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None, poll=None, suppress=None, silent=None)¶
This function is a coroutine.
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through
str(content). If the content is set toNone(the default), then theembedparameter must be provided.To upload a single file, the
fileparameter should be used with a singleFileobject. To upload multiple files, thefilesparameter should be used with alistofFileobjects. Specifying both parameters will lead to an exception.To upload a single embed, the
embedparameter should be used with a singleEmbedobject. To upload multiple embeds, theembedsparameter should be used with alistofEmbedobjects. Specifying both parameters will lead to an exception.- Parameters:
content (Optional[
str]) – The content of the message to send.tts (
bool) – Indicates if the message should be sent using text-to-speech.embed (
Embed) – The rich embed for the content.file (
File) – The file to upload.files (List[
File]) – A list of files to upload. Must be a maximum of 10.nonce (Union[
str,int]) – The nonce to use for sending this message. If the message was successfully sent, then the message will have a nonce with this value.enforce_nonce (Optional[
bool]) –Whether
nonceis enforced to be validated.Added in version 2.5.
delete_after (
float) – If provided, the number of seconds to wait in the background before deleting the message we just sent. If the deletion fails, then it is silently ignored.allowed_mentions (
AllowedMentions) –Controls the mentions being processed in this message. If this is passed, then the object is merged with
allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set inallowed_mentions. If no object is passed at all then the defaults given byallowed_mentionsare used instead.Added in version 1.4.
reference (Union[
Message,MessageReference,PartialMessage]) –A reference to the
Messagebeing replied to or forwarded. This can be created usingto_reference(). When replying, you can control whether this mentions the author of the referenced message using thereplied_userattribute ofallowed_mentionsor by settingmention_author.Added in version 1.6.
mention_author (Optional[
bool]) –If set, overrides the
replied_userattribute ofallowed_mentions.Added in version 1.6.
view (
discord.ui.View) – A Discord UI View to add to the message.embeds (List[
Embed]) –A list of embeds to upload. Must be a maximum of 10.
Added in version 2.0.
stickers (Sequence[Union[
GuildSticker,StickerItem]]) –A list of stickers to upload. Must be a maximum of 3.
Added in version 2.0.
suppress (
bool) – Whether to suppress embeds for the message.silent (
bool) –Whether to suppress push and desktop notifications for the message.
Added in version 2.4.
poll (
Poll) –The poll to send.
Added in version 2.6.
- Returns:
The message that was sent.
- Return type:
- Raises:
HTTPException – Sending the message failed.
Forbidden – You do not have the proper permissions to send the message.
InvalidArgument – The
fileslist is not of the appropriate size, you specified bothfileandfiles, or you specified bothembedandembeds, or thereferenceobject is not aMessage,MessageReferenceorPartialMessage.
- await trigger_typing()¶
This function is a coroutine.
Triggers a typing indicator to the destination.
Typing indicator will go away after 10 seconds, or after a message is sent.
- Return type:
- typing()¶
Returns a context manager that allows you to type for an indefinite period of time.
This is useful for denoting long computations in your bot. :rtype:
TypingNote
This is both a regular context manager and an async context manager. This means that both
withandasync withwork with this.Example Usage:
async with channel.typing(): # simulate something heavy await asyncio.sleep(10) await channel.send("done!")
- class discord.events.PresenceUpdate[source]¶
Called when a member updates their presence.
This is called when one or more of the following things change: - status - activity
This requires
Intents.presencesandIntents.membersto be enabled.- old¶
The member’s old presence info.
- Type:
Member
- new¶
The member’s updated presence info.
- Type:
Member
Messages¶
- class discord.events.MessageCreate[source]¶
Called when a message is created and sent.
This requires
Intents.messagesto be enabled.Warning
Your bot’s own messages and private messages are sent through this event. This can lead to cases of ‘recursion’ depending on how your bot was programmed. If you want the bot to not reply to itself, consider checking if
authorequals the bot user.This event inherits from
Message.- await add_reaction(emoji)¶
This function is a coroutine.
Add a reaction to the message.
The emoji may be a unicode emoji, a custom
GuildEmoji, or anAppEmoji.You must have the
read_message_historypermission to use this. If nobody else has reacted to the message using this emoji, theadd_reactionspermission is required.- Parameters:
emoji (Union[
GuildEmoji,AppEmoji,Reaction,PartialEmoji,str]) – The emoji to react with.- Raises:
HTTPException – Adding the reaction failed.
Forbidden – You do not have the proper permissions to react to the message.
NotFound – The emoji you specified was not found.
InvalidArgument – The emoji parameter is invalid.
- Return type:
- clean_content¶
A property that returns the content in a “cleaned up” manner. This basically means that mentions are transformed into the way the client shows it. e.g.
<#id>will transform into#name.This will also transform @everyone and @here mentions into non-mentions.
Note
This does not affect markdown. If you want to escape or remove markdown then use
utils.escape_markdown()orutils.remove_markdown()respectively, along with this function.
- await clear_reaction(emoji)¶
This function is a coroutine.
Clears a specific reaction from the message.
The emoji may be a unicode emoji, a custom
GuildEmoji, or anAppEmoji.You need the
manage_messagespermission to use this.Added in version 1.3.
- Parameters:
emoji (Union[
GuildEmoji,AppEmoji,Reaction,PartialEmoji,str]) – The emoji to clear.- Raises:
HTTPException – Clearing the reaction failed.
Forbidden – You do not have the proper permissions to clear the reaction.
NotFound – The emoji you specified was not found.
InvalidArgument – The emoji parameter is invalid.
- Return type:
- await clear_reactions()¶
This function is a coroutine.
Removes all the reactions from the message.
You need the
manage_messagespermission to use this.- Raises:
HTTPException – Removing the reactions failed.
Forbidden – You do not have the proper permissions to remove all the reactions.
- Return type:
- await create_thread(*, name, auto_archive_duration=Undefined.MISSING, slowmode_delay=Undefined.MISSING)¶
This function is a coroutine.
Creates a public thread from this message.
You must have
create_public_threadsin order to create a public thread from a message.The channel this message belongs in must be a
TextChannel.Added in version 2.0.
- Parameters:
name (
str) – The name of the thread.auto_archive_duration (Optional[
int]) – The duration in minutes before a thread is automatically archived for inactivity. If not provided, the channel’s default auto archive duration is used.slowmode_delay (Optional[
int]) – Specifies the slowmode rate limit for user in this thread, in seconds. A value of0disables slowmode. The maximum value possible is21600.
- Returns:
The created thread.
- Return type:
- Raises:
Forbidden – You do not have permissions to create a thread.
HTTPException – Creating the thread failed.
InvalidArgument – This message does not have guild info attached.
- await delete(*, delay=None, reason=None)¶
This function is a coroutine.
Deletes the message.
Your own messages could be deleted without any proper permissions. However, to delete other people’s messages, you need the
manage_messagespermission.Changed in version 1.1: Added the new
delaykeyword-only parameter.- Parameters:
- Raises:
Forbidden – You do not have proper permissions to delete the message.
NotFound – The message was deleted already
HTTPException – Deleting the message failed.
- Return type:
- await edit(content=Undefined.MISSING, embed=Undefined.MISSING, embeds=Undefined.MISSING, file=Undefined.MISSING, files=Undefined.MISSING, attachments=Undefined.MISSING, suppress=Undefined.MISSING, delete_after=None, allowed_mentions=Undefined.MISSING, view=Undefined.MISSING)¶
This function is a coroutine.
Edits the message.
The content must be able to be transformed into a string via
str(content).Changed in version 1.3: The
suppresskeyword-only parameter was added.- Parameters:
content (Optional[
str]) – The new content to replace the message with. Could beNoneto remove the content.embed (Optional[
Embed]) – The new embed to replace the original with. Could beNoneto remove the embed.embeds (List[
Embed]) –The new embeds to replace the original with. Must be a maximum of 10. To remove all embeds
[]should be passed.Added in version 2.0.
file (Sequence[
File]) – A new file to add to the message.files (List[Sequence[
File]]) – New files to add to the message.attachments (List[
Attachment]) – A list of attachments to keep in the message. If[]is passed then all attachments are removed.suppress (
bool) – Whether to suppress embeds for the message. This removes all the embeds if set toTrue. If set toFalsethis brings the embeds back if they were suppressed. Using this parameter requiresmanage_messages.delete_after (Optional[
float]) – If provided, the number of seconds to wait in the background before deleting the message we just edited. If the deletion fails, then it is silently ignored.allowed_mentions (Optional[
AllowedMentions]) –Controls the mentions being processed in this message. If this is passed, then the object is merged with
allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set inallowed_mentions. If no object is passed at all then the defaults given byallowed_mentionsare used instead.Added in version 1.4.
view (Optional[
View]) – The updated view to update this message with. IfNoneis passed then the view is removed.
- Raises:
NotFound – The message was not found.
HTTPException – Editing the message failed.
Forbidden – Tried to suppress a message without permissions or edited a message’s content or embed that isn’t yours.
InvalidArgument – You specified both
embedandembeds, specified bothfileandfiles, or either``file`` orfileswere of the wrong type.
- Return type:
- property edited_at: datetime | None¶
An aware UTC datetime object containing the edited time of the message.
- await end_poll()¶
This function is a coroutine.
Immediately ends the poll associated with this message. Only doable by the poll’s owner.
Added in version 2.6.
- Returns:
The updated message.
- Return type:
Message- Raises:
Forbidden – You do not have permissions to end this poll.
HTTPException – Ending this poll failed.
- await forward_to(channel, **kwargs)¶
This function is a coroutine.
A shortcut method to
abc.Messageable.send()to forward theMessageto a channel.Added in version 2.7.
- Parameters:
channel (Union[
TextChannel,Thread,DMChannel,GroupChannel,PartialMessageable]) – The channel to forward this to.- Returns:
The message that was sent.
- Return type:
- Raises:
HTTPException – Sending the message failed.
Forbidden – You do not have the proper permissions to send the message.
InvalidArgument – The
fileslist is not of the appropriate size, or you specified bothfileandfiles.
- is_system()¶
Whether the message is a system message.
A system message is a message that is constructed entirely by the Discord API in response to something. :rtype:
boolAdded in version 1.3.
- await pin(*, reason=None)¶
This function is a coroutine.
Pins the message.
You must have the
pin_messagespermission to do this in a non-private channel context.- Parameters:
reason (Optional[
str]) –The reason for pinning the message. Shows up on the audit log.
Added in version 1.4.
- Raises:
Forbidden – You do not have permissions to pin the message.
NotFound – The message or channel was not found or deleted.
HTTPException – Pinning the message failed, probably due to the channel having more than 50 pinned messages.
- Return type:
- await publish()¶
This function is a coroutine.
Publishes this message to your announcement channel.
You must have the
send_messagespermission to do this.If the message is not your own then the
manage_messagespermission is also needed.- Raises:
Forbidden – You do not have the proper permissions to publish this message.
HTTPException – Publishing the message failed.
- Return type:
- raw_channel_mentions¶
A property that returns an array of channel IDs matched with the syntax of
<#channel_id>in the message content.
- raw_mentions¶
A property that returns an array of user IDs matched with the syntax of
<@user_id>in the message content.This allows you to receive the user IDs of mentioned users even in a private message context.
- raw_role_mentions¶
A property that returns an array of role IDs matched with the syntax of
<@&role_id>in the message content.
- await remove_reaction(emoji, member)¶
This function is a coroutine.
Remove a reaction by the member from the message.
The emoji may be a unicode emoji, a custom
GuildEmoji, or anAppEmoji.If the reaction is not your own (i.e.
memberparameter is not you) then themanage_messagespermission is needed.The
memberparameter must represent a member and meet theabc.Snowflakeabc.- Parameters:
emoji (Union[
GuildEmoji,AppEmoji,Reaction,PartialEmoji,str]) – The emoji to remove.member (
abc.Snowflake) – The member for which to remove the reaction.
- Raises:
HTTPException – Removing the reaction failed.
Forbidden – You do not have the proper permissions to remove the reaction.
NotFound – The member or emoji you specified was not found.
InvalidArgument – The emoji parameter is invalid.
- Return type:
- await reply(content=None, **kwargs)¶
This function is a coroutine.
A shortcut method to
abc.Messageable.send()to reply to theMessage.Added in version 1.6.
- Returns:
The message that was sent.
- Return type:
- Raises:
HTTPException – Sending the message failed.
Forbidden – You do not have the proper permissions to send the message.
InvalidArgument – The
fileslist is not of the appropriate size, or you specified bothfileandfiles.
- Parameters:
- system_content¶
A property that returns the content that is rendered regardless of the
Message.type.In the case of
MessageType.defaultandMessageType.reply, this just returns the regularMessage.content, and forwarded messages will display the original message’s content fromMessage.snapshots. Otherwise, this returns an English message denoting the contents of the system message.
- to_reference(*, fail_if_not_exists=True, type=None)¶
Creates a
MessageReferencefrom the current message.Added in version 1.6.
- Parameters:
fail_if_not_exists (
bool) –Whether replying using the message reference should raise
HTTPExceptionif the message no longer exists or Discord could not fetch the message.Added in version 1.7.
type (Optional[
MessageReferenceType]) –The type of message reference. Defaults to a reply.
Added in version 2.7.
- Returns:
The reference to this message.
- Return type:
- await unpin(*, reason=None)¶
This function is a coroutine.
Unpins the message.
You must have the
pin_messagespermission to do this in a non-private channel context.- Parameters:
reason (Optional[
str]) –The reason for unpinning the message. Shows up on the audit log.
Added in version 1.4.
- Raises:
Forbidden – You do not have permissions to unpin the message.
NotFound – The message or channel was not found or deleted.
HTTPException – Unpinning the message failed.
- Return type:
- class discord.events.MessageUpdate[source]¶
Called when a message receives an update event.
This requires
Intents.messagesto be enabled.The following non-exhaustive cases trigger this event: - A message has been pinned or unpinned. - The message content has been changed. - The message has received an embed. - The message’s embeds were suppressed or unsuppressed. - A call message has received an update to its participants or ending time. - A poll has ended and the results have been finalized.
This event inherits from
Message.- raw¶
The raw event payload data.
- Type:
RawMessageUpdateEvent
- old¶
The previous version of the message (if it was cached).
- Type:
Message|Undefined
- await add_reaction(emoji)¶
This function is a coroutine.
Add a reaction to the message.
The emoji may be a unicode emoji, a custom
GuildEmoji, or anAppEmoji.You must have the
read_message_historypermission to use this. If nobody else has reacted to the message using this emoji, theadd_reactionspermission is required.- Parameters:
emoji (Union[
GuildEmoji,AppEmoji,Reaction,PartialEmoji,str]) – The emoji to react with.- Raises:
HTTPException – Adding the reaction failed.
Forbidden – You do not have the proper permissions to react to the message.
NotFound – The emoji you specified was not found.
InvalidArgument – The emoji parameter is invalid.
- Return type:
- clean_content¶
A property that returns the content in a “cleaned up” manner. This basically means that mentions are transformed into the way the client shows it. e.g.
<#id>will transform into#name.This will also transform @everyone and @here mentions into non-mentions.
Note
This does not affect markdown. If you want to escape or remove markdown then use
utils.escape_markdown()orutils.remove_markdown()respectively, along with this function.
- await clear_reaction(emoji)¶
This function is a coroutine.
Clears a specific reaction from the message.
The emoji may be a unicode emoji, a custom
GuildEmoji, or anAppEmoji.You need the
manage_messagespermission to use this.Added in version 1.3.
- Parameters:
emoji (Union[
GuildEmoji,AppEmoji,Reaction,PartialEmoji,str]) – The emoji to clear.- Raises:
HTTPException – Clearing the reaction failed.
Forbidden – You do not have the proper permissions to clear the reaction.
NotFound – The emoji you specified was not found.
InvalidArgument – The emoji parameter is invalid.
- Return type:
- await clear_reactions()¶
This function is a coroutine.
Removes all the reactions from the message.
You need the
manage_messagespermission to use this.- Raises:
HTTPException – Removing the reactions failed.
Forbidden – You do not have the proper permissions to remove all the reactions.
- Return type:
- await create_thread(*, name, auto_archive_duration=Undefined.MISSING, slowmode_delay=Undefined.MISSING)¶
This function is a coroutine.
Creates a public thread from this message.
You must have
create_public_threadsin order to create a public thread from a message.The channel this message belongs in must be a
TextChannel.Added in version 2.0.
- Parameters:
name (
str) – The name of the thread.auto_archive_duration (Optional[
int]) – The duration in minutes before a thread is automatically archived for inactivity. If not provided, the channel’s default auto archive duration is used.slowmode_delay (Optional[
int]) – Specifies the slowmode rate limit for user in this thread, in seconds. A value of0disables slowmode. The maximum value possible is21600.
- Returns:
The created thread.
- Return type:
- Raises:
Forbidden – You do not have permissions to create a thread.
HTTPException – Creating the thread failed.
InvalidArgument – This message does not have guild info attached.
- await delete(*, delay=None, reason=None)¶
This function is a coroutine.
Deletes the message.
Your own messages could be deleted without any proper permissions. However, to delete other people’s messages, you need the
manage_messagespermission.Changed in version 1.1: Added the new
delaykeyword-only parameter.- Parameters:
- Raises:
Forbidden – You do not have proper permissions to delete the message.
NotFound – The message was deleted already
HTTPException – Deleting the message failed.
- Return type:
- await edit(content=Undefined.MISSING, embed=Undefined.MISSING, embeds=Undefined.MISSING, file=Undefined.MISSING, files=Undefined.MISSING, attachments=Undefined.MISSING, suppress=Undefined.MISSING, delete_after=None, allowed_mentions=Undefined.MISSING, view=Undefined.MISSING)¶
This function is a coroutine.
Edits the message.
The content must be able to be transformed into a string via
str(content).Changed in version 1.3: The
suppresskeyword-only parameter was added.- Parameters:
content (Optional[
str]) – The new content to replace the message with. Could beNoneto remove the content.embed (Optional[
Embed]) – The new embed to replace the original with. Could beNoneto remove the embed.embeds (List[
Embed]) –The new embeds to replace the original with. Must be a maximum of 10. To remove all embeds
[]should be passed.Added in version 2.0.
file (Sequence[
File]) – A new file to add to the message.files (List[Sequence[
File]]) – New files to add to the message.attachments (List[
Attachment]) – A list of attachments to keep in the message. If[]is passed then all attachments are removed.suppress (
bool) – Whether to suppress embeds for the message. This removes all the embeds if set toTrue. If set toFalsethis brings the embeds back if they were suppressed. Using this parameter requiresmanage_messages.delete_after (Optional[
float]) – If provided, the number of seconds to wait in the background before deleting the message we just edited. If the deletion fails, then it is silently ignored.allowed_mentions (Optional[
AllowedMentions]) –Controls the mentions being processed in this message. If this is passed, then the object is merged with
allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set inallowed_mentions. If no object is passed at all then the defaults given byallowed_mentionsare used instead.Added in version 1.4.
view (Optional[
View]) – The updated view to update this message with. IfNoneis passed then the view is removed.
- Raises:
NotFound – The message was not found.
HTTPException – Editing the message failed.
Forbidden – Tried to suppress a message without permissions or edited a message’s content or embed that isn’t yours.
InvalidArgument – You specified both
embedandembeds, specified bothfileandfiles, or either``file`` orfileswere of the wrong type.
- Return type:
- property edited_at: datetime | None¶
An aware UTC datetime object containing the edited time of the message.
- await end_poll()¶
This function is a coroutine.
Immediately ends the poll associated with this message. Only doable by the poll’s owner.
Added in version 2.6.
- Returns:
The updated message.
- Return type:
Message- Raises:
Forbidden – You do not have permissions to end this poll.
HTTPException – Ending this poll failed.
- await forward_to(channel, **kwargs)¶
This function is a coroutine.
A shortcut method to
abc.Messageable.send()to forward theMessageto a channel.Added in version 2.7.
- Parameters:
channel (Union[
TextChannel,Thread,DMChannel,GroupChannel,PartialMessageable]) – The channel to forward this to.- Returns:
The message that was sent.
- Return type:
- Raises:
HTTPException – Sending the message failed.
Forbidden – You do not have the proper permissions to send the message.
InvalidArgument – The
fileslist is not of the appropriate size, or you specified bothfileandfiles.
- is_system()¶
Whether the message is a system message.
A system message is a message that is constructed entirely by the Discord API in response to something. :rtype:
boolAdded in version 1.3.
- await pin(*, reason=None)¶
This function is a coroutine.
Pins the message.
You must have the
pin_messagespermission to do this in a non-private channel context.- Parameters:
reason (Optional[
str]) –The reason for pinning the message. Shows up on the audit log.
Added in version 1.4.
- Raises:
Forbidden – You do not have permissions to pin the message.
NotFound – The message or channel was not found or deleted.
HTTPException – Pinning the message failed, probably due to the channel having more than 50 pinned messages.
- Return type:
- await publish()¶
This function is a coroutine.
Publishes this message to your announcement channel.
You must have the
send_messagespermission to do this.If the message is not your own then the
manage_messagespermission is also needed.- Raises:
Forbidden – You do not have the proper permissions to publish this message.
HTTPException – Publishing the message failed.
- Return type:
- raw_channel_mentions¶
A property that returns an array of channel IDs matched with the syntax of
<#channel_id>in the message content.
- raw_mentions¶
A property that returns an array of user IDs matched with the syntax of
<@user_id>in the message content.This allows you to receive the user IDs of mentioned users even in a private message context.
- raw_role_mentions¶
A property that returns an array of role IDs matched with the syntax of
<@&role_id>in the message content.
- await remove_reaction(emoji, member)¶
This function is a coroutine.
Remove a reaction by the member from the message.
The emoji may be a unicode emoji, a custom
GuildEmoji, or anAppEmoji.If the reaction is not your own (i.e.
memberparameter is not you) then themanage_messagespermission is needed.The
memberparameter must represent a member and meet theabc.Snowflakeabc.- Parameters:
emoji (Union[
GuildEmoji,AppEmoji,Reaction,PartialEmoji,str]) – The emoji to remove.member (
abc.Snowflake) – The member for which to remove the reaction.
- Raises:
HTTPException – Removing the reaction failed.
Forbidden – You do not have the proper permissions to remove the reaction.
NotFound – The member or emoji you specified was not found.
InvalidArgument – The emoji parameter is invalid.
- Return type:
- await reply(content=None, **kwargs)¶
This function is a coroutine.
A shortcut method to
abc.Messageable.send()to reply to theMessage.Added in version 1.6.
- Returns:
The message that was sent.
- Return type:
- Raises:
HTTPException – Sending the message failed.
Forbidden – You do not have the proper permissions to send the message.
InvalidArgument – The
fileslist is not of the appropriate size, or you specified bothfileandfiles.
- Parameters:
- system_content¶
A property that returns the content that is rendered regardless of the
Message.type.In the case of
MessageType.defaultandMessageType.reply, this just returns the regularMessage.content, and forwarded messages will display the original message’s content fromMessage.snapshots. Otherwise, this returns an English message denoting the contents of the system message.
- to_reference(*, fail_if_not_exists=True, type=None)¶
Creates a
MessageReferencefrom the current message.Added in version 1.6.
- Parameters:
fail_if_not_exists (
bool) –Whether replying using the message reference should raise
HTTPExceptionif the message no longer exists or Discord could not fetch the message.Added in version 1.7.
type (Optional[
MessageReferenceType]) –The type of message reference. Defaults to a reply.
Added in version 2.7.
- Returns:
The reference to this message.
- Return type:
- await unpin(*, reason=None)¶
This function is a coroutine.
Unpins the message.
You must have the
pin_messagespermission to do this in a non-private channel context.- Parameters:
reason (Optional[
str]) –The reason for unpinning the message. Shows up on the audit log.
Added in version 1.4.
- Raises:
Forbidden – You do not have permissions to unpin the message.
NotFound – The message or channel was not found or deleted.
HTTPException – Unpinning the message failed.
- Return type:
- class discord.events.MessageDelete[source]¶
Called when a message is deleted.
This requires
Intents.messagesto be enabled.This event inherits from
Message.- raw¶
The raw event payload data.
- Type:
RawMessageDeleteEvent
- await add_reaction(emoji)¶
This function is a coroutine.
Add a reaction to the message.
The emoji may be a unicode emoji, a custom
GuildEmoji, or anAppEmoji.You must have the
read_message_historypermission to use this. If nobody else has reacted to the message using this emoji, theadd_reactionspermission is required.- Parameters:
emoji (Union[
GuildEmoji,AppEmoji,Reaction,PartialEmoji,str]) – The emoji to react with.- Raises:
HTTPException – Adding the reaction failed.
Forbidden – You do not have the proper permissions to react to the message.
NotFound – The emoji you specified was not found.
InvalidArgument – The emoji parameter is invalid.
- Return type:
- clean_content¶
A property that returns the content in a “cleaned up” manner. This basically means that mentions are transformed into the way the client shows it. e.g.
<#id>will transform into#name.This will also transform @everyone and @here mentions into non-mentions.
Note
This does not affect markdown. If you want to escape or remove markdown then use
utils.escape_markdown()orutils.remove_markdown()respectively, along with this function.
- await clear_reaction(emoji)¶
This function is a coroutine.
Clears a specific reaction from the message.
The emoji may be a unicode emoji, a custom
GuildEmoji, or anAppEmoji.You need the
manage_messagespermission to use this.Added in version 1.3.
- Parameters:
emoji (Union[
GuildEmoji,AppEmoji,Reaction,PartialEmoji,str]) – The emoji to clear.- Raises:
HTTPException – Clearing the reaction failed.
Forbidden – You do not have the proper permissions to clear the reaction.
NotFound – The emoji you specified was not found.
InvalidArgument – The emoji parameter is invalid.
- Return type:
- await clear_reactions()¶
This function is a coroutine.
Removes all the reactions from the message.
You need the
manage_messagespermission to use this.- Raises:
HTTPException – Removing the reactions failed.
Forbidden – You do not have the proper permissions to remove all the reactions.
- Return type:
- await create_thread(*, name, auto_archive_duration=Undefined.MISSING, slowmode_delay=Undefined.MISSING)¶
This function is a coroutine.
Creates a public thread from this message.
You must have
create_public_threadsin order to create a public thread from a message.The channel this message belongs in must be a
TextChannel.Added in version 2.0.
- Parameters:
name (
str) – The name of the thread.auto_archive_duration (Optional[
int]) – The duration in minutes before a thread is automatically archived for inactivity. If not provided, the channel’s default auto archive duration is used.slowmode_delay (Optional[
int]) – Specifies the slowmode rate limit for user in this thread, in seconds. A value of0disables slowmode. The maximum value possible is21600.
- Returns:
The created thread.
- Return type:
- Raises:
Forbidden – You do not have permissions to create a thread.
HTTPException – Creating the thread failed.
InvalidArgument – This message does not have guild info attached.
- await delete(*, delay=None, reason=None)¶
This function is a coroutine.
Deletes the message.
Your own messages could be deleted without any proper permissions. However, to delete other people’s messages, you need the
manage_messagespermission.Changed in version 1.1: Added the new
delaykeyword-only parameter.- Parameters:
- Raises:
Forbidden – You do not have proper permissions to delete the message.
NotFound – The message was deleted already
HTTPException – Deleting the message failed.
- Return type:
- await edit(content=Undefined.MISSING, embed=Undefined.MISSING, embeds=Undefined.MISSING, file=Undefined.MISSING, files=Undefined.MISSING, attachments=Undefined.MISSING, suppress=Undefined.MISSING, delete_after=None, allowed_mentions=Undefined.MISSING, view=Undefined.MISSING)¶
This function is a coroutine.
Edits the message.
The content must be able to be transformed into a string via
str(content).Changed in version 1.3: The
suppresskeyword-only parameter was added.- Parameters:
content (Optional[
str]) – The new content to replace the message with. Could beNoneto remove the content.embed (Optional[
Embed]) – The new embed to replace the original with. Could beNoneto remove the embed.embeds (List[
Embed]) –The new embeds to replace the original with. Must be a maximum of 10. To remove all embeds
[]should be passed.Added in version 2.0.
file (Sequence[
File]) – A new file to add to the message.files (List[Sequence[
File]]) – New files to add to the message.attachments (List[
Attachment]) – A list of attachments to keep in the message. If[]is passed then all attachments are removed.suppress (
bool) – Whether to suppress embeds for the message. This removes all the embeds if set toTrue. If set toFalsethis brings the embeds back if they were suppressed. Using this parameter requiresmanage_messages.delete_after (Optional[
float]) – If provided, the number of seconds to wait in the background before deleting the message we just edited. If the deletion fails, then it is silently ignored.allowed_mentions (Optional[
AllowedMentions]) –Controls the mentions being processed in this message. If this is passed, then the object is merged with
allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set inallowed_mentions. If no object is passed at all then the defaults given byallowed_mentionsare used instead.Added in version 1.4.
view (Optional[
View]) – The updated view to update this message with. IfNoneis passed then the view is removed.
- Raises:
NotFound – The message was not found.
HTTPException – Editing the message failed.
Forbidden – Tried to suppress a message without permissions or edited a message’s content or embed that isn’t yours.
InvalidArgument – You specified both
embedandembeds, specified bothfileandfiles, or either``file`` orfileswere of the wrong type.
- Return type:
- property edited_at: datetime | None¶
An aware UTC datetime object containing the edited time of the message.
- await end_poll()¶
This function is a coroutine.
Immediately ends the poll associated with this message. Only doable by the poll’s owner.
Added in version 2.6.
- Returns:
The updated message.
- Return type:
Message- Raises:
Forbidden – You do not have permissions to end this poll.
HTTPException – Ending this poll failed.
- await forward_to(channel, **kwargs)¶
This function is a coroutine.
A shortcut method to
abc.Messageable.send()to forward theMessageto a channel.Added in version 2.7.
- Parameters:
channel (Union[
TextChannel,Thread,DMChannel,GroupChannel,PartialMessageable]) – The channel to forward this to.- Returns:
The message that was sent.
- Return type:
- Raises:
HTTPException – Sending the message failed.
Forbidden – You do not have the proper permissions to send the message.
InvalidArgument – The
fileslist is not of the appropriate size, or you specified bothfileandfiles.
- is_system()¶
Whether the message is a system message.
A system message is a message that is constructed entirely by the Discord API in response to something. :rtype:
boolAdded in version 1.3.
- await pin(*, reason=None)¶
This function is a coroutine.
Pins the message.
You must have the
pin_messagespermission to do this in a non-private channel context.- Parameters:
reason (Optional[
str]) –The reason for pinning the message. Shows up on the audit log.
Added in version 1.4.
- Raises:
Forbidden – You do not have permissions to pin the message.
NotFound – The message or channel was not found or deleted.
HTTPException – Pinning the message failed, probably due to the channel having more than 50 pinned messages.
- Return type:
- await publish()¶
This function is a coroutine.
Publishes this message to your announcement channel.
You must have the
send_messagespermission to do this.If the message is not your own then the
manage_messagespermission is also needed.- Raises:
Forbidden – You do not have the proper permissions to publish this message.
HTTPException – Publishing the message failed.
- Return type:
- raw_channel_mentions¶
A property that returns an array of channel IDs matched with the syntax of
<#channel_id>in the message content.
- raw_mentions¶
A property that returns an array of user IDs matched with the syntax of
<@user_id>in the message content.This allows you to receive the user IDs of mentioned users even in a private message context.
- raw_role_mentions¶
A property that returns an array of role IDs matched with the syntax of
<@&role_id>in the message content.
- await remove_reaction(emoji, member)¶
This function is a coroutine.
Remove a reaction by the member from the message.
The emoji may be a unicode emoji, a custom
GuildEmoji, or anAppEmoji.If the reaction is not your own (i.e.
memberparameter is not you) then themanage_messagespermission is needed.The
memberparameter must represent a member and meet theabc.Snowflakeabc.- Parameters:
emoji (Union[
GuildEmoji,AppEmoji,Reaction,PartialEmoji,str]) – The emoji to remove.member (
abc.Snowflake) – The member for which to remove the reaction.
- Raises:
HTTPException – Removing the reaction failed.
Forbidden – You do not have the proper permissions to remove the reaction.
NotFound – The member or emoji you specified was not found.
InvalidArgument – The emoji parameter is invalid.
- Return type:
- await reply(content=None, **kwargs)¶
This function is a coroutine.
A shortcut method to
abc.Messageable.send()to reply to theMessage.Added in version 1.6.
- Returns:
The message that was sent.
- Return type:
- Raises:
HTTPException – Sending the message failed.
Forbidden – You do not have the proper permissions to send the message.
InvalidArgument – The
fileslist is not of the appropriate size, or you specified bothfileandfiles.
- Parameters:
- system_content¶
A property that returns the content that is rendered regardless of the
Message.type.In the case of
MessageType.defaultandMessageType.reply, this just returns the regularMessage.content, and forwarded messages will display the original message’s content fromMessage.snapshots. Otherwise, this returns an English message denoting the contents of the system message.
- to_reference(*, fail_if_not_exists=True, type=None)¶
Creates a
MessageReferencefrom the current message.Added in version 1.6.
- Parameters:
fail_if_not_exists (
bool) –Whether replying using the message reference should raise
HTTPExceptionif the message no longer exists or Discord could not fetch the message.Added in version 1.7.
type (Optional[
MessageReferenceType]) –The type of message reference. Defaults to a reply.
Added in version 2.7.
- Returns:
The reference to this message.
- Return type:
- await unpin(*, reason=None)¶
This function is a coroutine.
Unpins the message.
You must have the
pin_messagespermission to do this in a non-private channel context.- Parameters:
reason (Optional[
str]) –The reason for unpinning the message. Shows up on the audit log.
Added in version 1.4.
- Raises:
Forbidden – You do not have permissions to unpin the message.
NotFound – The message or channel was not found or deleted.
HTTPException – Unpinning the message failed.
- Return type:
- class discord.events.MessageDeleteBulk[source]¶
Called when messages are bulk deleted.
This requires
Intents.messagesto be enabled.- raw¶
The raw event payload data.
- Type:
RawBulkMessageDeleteEvent
- messages¶
The messages that have been deleted (only includes cached messages).
- Type:
list[
Message]
Reactions¶
- class discord.events.ReactionAdd[source]¶
Called when a message has a reaction added to it.
This requires
Intents.reactionsto be enabled.Note
To get the
Messagebeing reacted to, access it viareaction.message.- raw¶
The raw event payload data.
- Type:
RawReactionActionEvent
- user¶
The user who added the reaction.
- Type:
Member|User|Undefined
- reaction¶
The current state of the reaction.
- Type:
Reaction
- class discord.events.ReactionRemove[source]¶
Called when a message has a reaction removed from it.
This requires
Intents.reactionsto be enabled.Note
To get the
Messagebeing reacted to, access it viareaction.message.- raw¶
The raw event payload data.
- Type:
RawReactionActionEvent
- user¶
The user who removed the reaction.
- Type:
Member|User|Undefined
- reaction¶
The current state of the reaction.
- Type:
Reaction
- class discord.events.ReactionClear[source]¶
Called when a message has all its reactions removed from it.
This requires
Intents.reactionsto be enabled.- raw¶
The raw event payload data.
- Type:
RawReactionClearEvent
- message¶
The message that had its reactions cleared.
- Type:
Message|Undefined
- old_reactions¶
The reactions that were removed.
- Type:
list[
Reaction] |Undefined
- class discord.events.ReactionRemoveEmoji[source]¶
Called when a message has a specific reaction removed from it.
This requires
Intents.reactionsto be enabled.This event inherits from
Reaction.- property burst_colors: list[Colour]¶
Returns a list possible
Colourthis super reaction can be.There is an alias for this named
burst_colours.
- property burst_colours: list[Colour]¶
Returns a list possible
Colourthis super reaction can be.There is an alias for this named
burst_colors.
- await clear()¶
This function is a coroutine.
Clears this reaction from the message.
You need the
manage_messagespermission to use this. :rtype:NoneAdded in version 1.3.
- Raises:
HTTPException – Clearing the reaction failed.
Forbidden – You do not have the proper permissions to clear the reaction.
NotFound – The emoji you specified was not found.
InvalidArgument – The emoji parameter is invalid.
- property count_details¶
Returns
ReactionCountDetailsfor the individual counts of normal and super reactions made.
- await remove(user)¶
This function is a coroutine.
Remove the reaction by the provided
Userfrom the message.If the reaction is not your own (i.e.
userparameter is not you) then themanage_messagespermission is needed.The
userparameter must represent a user or member and meet theabc.Snowflakeabc.- Parameters:
user (
abc.Snowflake) – The user or member from which to remove the reaction.- Raises:
HTTPException – Removing the reaction failed.
Forbidden – You do not have the proper permissions to remove the reaction.
NotFound – The user you specified, or the reaction’s message was not found.
- Return type:
- users(*, limit=None, after=None, type=None)¶
Returns an
AsyncIteratorrepresenting the users that have reacted to the message.The
afterparameter must represent a member and meet theabc.Snowflakeabc.- Parameters:
limit (Optional[
int]) – The maximum number of results to return. If not provided, returns all the users who reacted to the message.after (Optional[
abc.Snowflake]) – For pagination, reactions are sorted by member.type (Optional[
ReactionType]) – The type of reaction to get users for. Defaults to normal.
- Yields:
Union[
User,Member] – The member (if retrievable) or the user that has reacted to this message. The case where it can be aMemberis in a guild message context. Sometimes it can be aUserif the member has left the guild.- Raises:
HTTPException – Getting the users for the reaction failed.
- Return type:
ReactionIterator
Examples
Usage
# I do not actually recommend doing this. async for user in reaction.users(): await channel.send(f"{user} has reacted with {reaction.emoji}!")
Flattening into a list:
users = await reaction.users().flatten() # users is now a list of User... winner = random.choice(users) await channel.send(f"{winner} has won the raffle.")
Getting super reactors:
users = await reaction.users(type=ReactionType.burst).flatten()
Polls¶
- class discord.events.PollVoteAdd[source]¶
Called when a vote is cast on a poll.
This requires
Intents.pollsto be enabled.- raw¶
The raw event payload data.
- Type:
RawMessagePollVoteEvent
- guild¶
The guild where the poll vote occurred, if in a guild.
- Type:
Guild|Undefined
- user¶
The user who added the vote.
- Type:
User|Member| None
- poll¶
The current state of the poll.
- Type:
Poll
- answer¶
The answer that was voted for.
- Type:
PollAnswer
- class discord.events.PollVoteRemove[source]¶
Called when a vote is removed from a poll.
This requires
Intents.pollsto be enabled.- raw¶
The raw event payload data.
- Type:
RawMessagePollVoteEvent
- guild¶
The guild where the poll vote occurred, if in a guild.
- Type:
Guild|Undefined
- user¶
The user who removed the vote.
- Type:
User|Member| None
- poll¶
The current state of the poll.
- Type:
Poll
- answer¶
The answer that had its vote removed.
- Type:
PollAnswer
Scheduled Events¶
- class discord.events.GuildScheduledEventCreate[source]¶
Called when a scheduled event is created.
This requires
Intents.scheduled_eventsto be enabled.This event inherits from
ScheduledEvent.- await cancel(*, reason=None)¶
This function is a coroutine.
Cancels the scheduled event. Shortcut from
edit().Note
This method can only be used if
statusisScheduledEventStatus.scheduled.- Parameters:
reason (Optional[
str]) – The reason to show in the audit log.- Returns:
The newly updated scheduled event object.
- Return type:
Optional[
ScheduledEvent]- Raises:
Forbidden – You do not have the Manage Events permission.
HTTPException – The operation failed.
- await complete(*, reason=None)¶
This function is a coroutine.
Ends/completes the scheduled event. Shortcut from
edit().Note
This method can only be used if
statusisScheduledEventStatus.active.- Parameters:
reason (Optional[
str]) – The reason to show in the audit log.- Returns:
The newly updated scheduled event object.
- Return type:
Optional[
ScheduledEvent]- Raises:
Forbidden – You do not have the Manage Events permission.
HTTPException – The operation failed.
- property cover: Asset | None¶
Returns the scheduled event cover image asset, if available.
Deprecated since version 2.7: Use the
imageproperty instead.
- await delete()¶
This function is a coroutine.
Deletes the scheduled event.
- Raises:
Forbidden – You do not have the Manage Events permission.
HTTPException – The operation failed.
- Return type:
- await edit(*, reason=None, name=Undefined.MISSING, description=Undefined.MISSING, status=Undefined.MISSING, location=Undefined.MISSING, start_time=Undefined.MISSING, end_time=Undefined.MISSING, cover=Undefined.MISSING, image=Undefined.MISSING, privacy_level=ScheduledEventPrivacyLevel.guild_only)¶
This function is a coroutine.
Edits the Scheduled Event’s data
All parameters are optional unless
location.typeisScheduledEventLocationType.external, thenend_timeis required.Will return a new
ScheduledEventobject if applicable.- Parameters:
name (
str) – The new name of the event.description (
str) – The new description of the event.location (
ScheduledEventLocation) – The location of the event.status (
ScheduledEventStatus) – The status of the event. It is recommended, however, to usestart(),complete(), andcancel()to edit statuses instead.start_time (
datetime.datetime) – The new starting time for the event.end_time (
datetime.datetime) – The new ending time of the event.privacy_level (
ScheduledEventPrivacyLevel) – The privacy level of the event. Currently, the only possible value isScheduledEventPrivacyLevel.guild_only, which is default, so there is no need to change this parameter.reason (Optional[
str]) – The reason to show in the audit log.image (Optional[
bytes]) – The cover image of the scheduled event.cover (Optional[
bytes]) –The cover image of the scheduled event.
Deprecated since version 2.7: Use the image argument instead.
- Returns:
The newly updated scheduled event object. This is only returned when certain fields are updated.
- Return type:
Optional[
ScheduledEvent]- Raises:
Forbidden – You do not have the Manage Events permission.
HTTPException – The operation failed.
- property interested: int | None¶
An alias to
subscriber_count
- await start(*, reason=None)¶
This function is a coroutine.
Starts the scheduled event. Shortcut from
edit().Note
This method can only be used if
statusisScheduledEventStatus.scheduled.- Parameters:
reason (Optional[
str]) – The reason to show in the audit log.- Returns:
The newly updated scheduled event object.
- Return type:
Optional[
ScheduledEvent]- Raises:
Forbidden – You do not have the Manage Events permission.
HTTPException – The operation failed.
- subscribers(*, limit=100, as_member=False, before=None, after=None)¶
Returns an
AsyncIteratorrepresenting the users or members subscribed to the event.The
afterandbeforeparameters must represent member or user objects and meet theabc.Snowflakeabc.Note
Even is
as_memberis set toTrue, if the user is outside the guild, it will be aUserobject.- Parameters:
limit (Optional[
int]) – The maximum number of results to return.as_member (Optional[
bool]) – Whether to fetchMemberobjects instead of user objects. There may still beUserobjects if the user is outside the guild.before (Optional[Union[
abc.Snowflake,datetime.datetime]]) – Retrieves users before this date or object. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.after (Optional[Union[
abc.Snowflake,datetime.datetime]]) – Retrieves users after this date or object. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.
- Yields:
Union[
User,Member] – The subscribedMember. Ifas_memberis set toFalseor the user is outside the guild, it will be aUserobject.- Raises:
HTTPException – Fetching the subscribed users failed.
- Return type:
ScheduledEventSubscribersIterator
Examples
Usage
async for user in event.subscribers(limit=100): print(user.name)
Flattening into a list:
users = await event.subscribers(limit=100).flatten() # users is now a list of User...
Getting members instead of user objects:
async for member in event.subscribers(limit=100, as_member=True): print(member.display_name)
- class discord.events.GuildScheduledEventUpdate[source]¶
Called when a scheduled event is updated.
This requires
Intents.scheduled_eventsto be enabled.This event inherits from
ScheduledEvent.- old¶
The old scheduled event before the update.
- Type:
ScheduledEvent
- await cancel(*, reason=None)¶
This function is a coroutine.
Cancels the scheduled event. Shortcut from
edit().Note
This method can only be used if
statusisScheduledEventStatus.scheduled.- Parameters:
reason (Optional[
str]) – The reason to show in the audit log.- Returns:
The newly updated scheduled event object.
- Return type:
Optional[
ScheduledEvent]- Raises:
Forbidden – You do not have the Manage Events permission.
HTTPException – The operation failed.
- await complete(*, reason=None)¶
This function is a coroutine.
Ends/completes the scheduled event. Shortcut from
edit().Note
This method can only be used if
statusisScheduledEventStatus.active.- Parameters:
reason (Optional[
str]) – The reason to show in the audit log.- Returns:
The newly updated scheduled event object.
- Return type:
Optional[
ScheduledEvent]- Raises:
Forbidden – You do not have the Manage Events permission.
HTTPException – The operation failed.
- property cover: Asset | None¶
Returns the scheduled event cover image asset, if available.
Deprecated since version 2.7: Use the
imageproperty instead.
- await delete()¶
This function is a coroutine.
Deletes the scheduled event.
- Raises:
Forbidden – You do not have the Manage Events permission.
HTTPException – The operation failed.
- Return type:
- await edit(*, reason=None, name=Undefined.MISSING, description=Undefined.MISSING, status=Undefined.MISSING, location=Undefined.MISSING, start_time=Undefined.MISSING, end_time=Undefined.MISSING, cover=Undefined.MISSING, image=Undefined.MISSING, privacy_level=ScheduledEventPrivacyLevel.guild_only)¶
This function is a coroutine.
Edits the Scheduled Event’s data
All parameters are optional unless
location.typeisScheduledEventLocationType.external, thenend_timeis required.Will return a new
ScheduledEventobject if applicable.- Parameters:
name (
str) – The new name of the event.description (
str) – The new description of the event.location (
ScheduledEventLocation) – The location of the event.status (
ScheduledEventStatus) – The status of the event. It is recommended, however, to usestart(),complete(), andcancel()to edit statuses instead.start_time (
datetime.datetime) – The new starting time for the event.end_time (
datetime.datetime) – The new ending time of the event.privacy_level (
ScheduledEventPrivacyLevel) – The privacy level of the event. Currently, the only possible value isScheduledEventPrivacyLevel.guild_only, which is default, so there is no need to change this parameter.reason (Optional[
str]) – The reason to show in the audit log.image (Optional[
bytes]) – The cover image of the scheduled event.cover (Optional[
bytes]) –The cover image of the scheduled event.
Deprecated since version 2.7: Use the image argument instead.
- Returns:
The newly updated scheduled event object. This is only returned when certain fields are updated.
- Return type:
Optional[
ScheduledEvent]- Raises:
Forbidden – You do not have the Manage Events permission.
HTTPException – The operation failed.
- property interested: int | None¶
An alias to
subscriber_count
- await start(*, reason=None)¶
This function is a coroutine.
Starts the scheduled event. Shortcut from
edit().Note
This method can only be used if
statusisScheduledEventStatus.scheduled.- Parameters:
reason (Optional[
str]) – The reason to show in the audit log.- Returns:
The newly updated scheduled event object.
- Return type:
Optional[
ScheduledEvent]- Raises:
Forbidden – You do not have the Manage Events permission.
HTTPException – The operation failed.
- subscribers(*, limit=100, as_member=False, before=None, after=None)¶
Returns an
AsyncIteratorrepresenting the users or members subscribed to the event.The
afterandbeforeparameters must represent member or user objects and meet theabc.Snowflakeabc.Note
Even is
as_memberis set toTrue, if the user is outside the guild, it will be aUserobject.- Parameters:
limit (Optional[
int]) – The maximum number of results to return.as_member (Optional[
bool]) – Whether to fetchMemberobjects instead of user objects. There may still beUserobjects if the user is outside the guild.before (Optional[Union[
abc.Snowflake,datetime.datetime]]) – Retrieves users before this date or object. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.after (Optional[Union[
abc.Snowflake,datetime.datetime]]) – Retrieves users after this date or object. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.
- Yields:
Union[
User,Member] – The subscribedMember. Ifas_memberis set toFalseor the user is outside the guild, it will be aUserobject.- Raises:
HTTPException – Fetching the subscribed users failed.
- Return type:
ScheduledEventSubscribersIterator
Examples
Usage
async for user in event.subscribers(limit=100): print(user.name)
Flattening into a list:
users = await event.subscribers(limit=100).flatten() # users is now a list of User...
Getting members instead of user objects:
async for member in event.subscribers(limit=100, as_member=True): print(member.display_name)
- class discord.events.GuildScheduledEventDelete[source]¶
Called when a scheduled event is deleted.
This requires
Intents.scheduled_eventsto be enabled.This event inherits from
ScheduledEvent.- await cancel(*, reason=None)¶
This function is a coroutine.
Cancels the scheduled event. Shortcut from
edit().Note
This method can only be used if
statusisScheduledEventStatus.scheduled.- Parameters:
reason (Optional[
str]) – The reason to show in the audit log.- Returns:
The newly updated scheduled event object.
- Return type:
Optional[
ScheduledEvent]- Raises:
Forbidden – You do not have the Manage Events permission.
HTTPException – The operation failed.
- await complete(*, reason=None)¶
This function is a coroutine.
Ends/completes the scheduled event. Shortcut from
edit().Note
This method can only be used if
statusisScheduledEventStatus.active.- Parameters:
reason (Optional[
str]) – The reason to show in the audit log.- Returns:
The newly updated scheduled event object.
- Return type:
Optional[
ScheduledEvent]- Raises:
Forbidden – You do not have the Manage Events permission.
HTTPException – The operation failed.
- property cover: Asset | None¶
Returns the scheduled event cover image asset, if available.
Deprecated since version 2.7: Use the
imageproperty instead.
- await delete()¶
This function is a coroutine.
Deletes the scheduled event.
- Raises:
Forbidden – You do not have the Manage Events permission.
HTTPException – The operation failed.
- Return type:
- await edit(*, reason=None, name=Undefined.MISSING, description=Undefined.MISSING, status=Undefined.MISSING, location=Undefined.MISSING, start_time=Undefined.MISSING, end_time=Undefined.MISSING, cover=Undefined.MISSING, image=Undefined.MISSING, privacy_level=ScheduledEventPrivacyLevel.guild_only)¶
This function is a coroutine.
Edits the Scheduled Event’s data
All parameters are optional unless
location.typeisScheduledEventLocationType.external, thenend_timeis required.Will return a new
ScheduledEventobject if applicable.- Parameters:
name (
str) – The new name of the event.description (
str) – The new description of the event.location (
ScheduledEventLocation) – The location of the event.status (
ScheduledEventStatus) – The status of the event. It is recommended, however, to usestart(),complete(), andcancel()to edit statuses instead.start_time (
datetime.datetime) – The new starting time for the event.end_time (
datetime.datetime) – The new ending time of the event.privacy_level (
ScheduledEventPrivacyLevel) – The privacy level of the event. Currently, the only possible value isScheduledEventPrivacyLevel.guild_only, which is default, so there is no need to change this parameter.reason (Optional[
str]) – The reason to show in the audit log.image (Optional[
bytes]) – The cover image of the scheduled event.cover (Optional[
bytes]) –The cover image of the scheduled event.
Deprecated since version 2.7: Use the image argument instead.
- Returns:
The newly updated scheduled event object. This is only returned when certain fields are updated.
- Return type:
Optional[
ScheduledEvent]- Raises:
Forbidden – You do not have the Manage Events permission.
HTTPException – The operation failed.
- property interested: int | None¶
An alias to
subscriber_count
- await start(*, reason=None)¶
This function is a coroutine.
Starts the scheduled event. Shortcut from
edit().Note
This method can only be used if
statusisScheduledEventStatus.scheduled.- Parameters:
reason (Optional[
str]) – The reason to show in the audit log.- Returns:
The newly updated scheduled event object.
- Return type:
Optional[
ScheduledEvent]- Raises:
Forbidden – You do not have the Manage Events permission.
HTTPException – The operation failed.
- subscribers(*, limit=100, as_member=False, before=None, after=None)¶
Returns an
AsyncIteratorrepresenting the users or members subscribed to the event.The
afterandbeforeparameters must represent member or user objects and meet theabc.Snowflakeabc.Note
Even is
as_memberis set toTrue, if the user is outside the guild, it will be aUserobject.- Parameters:
limit (Optional[
int]) – The maximum number of results to return.as_member (Optional[
bool]) – Whether to fetchMemberobjects instead of user objects. There may still beUserobjects if the user is outside the guild.before (Optional[Union[
abc.Snowflake,datetime.datetime]]) – Retrieves users before this date or object. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.after (Optional[Union[
abc.Snowflake,datetime.datetime]]) – Retrieves users after this date or object. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.
- Yields:
Union[
User,Member] – The subscribedMember. Ifas_memberis set toFalseor the user is outside the guild, it will be aUserobject.- Raises:
HTTPException – Fetching the subscribed users failed.
- Return type:
ScheduledEventSubscribersIterator
Examples
Usage
async for user in event.subscribers(limit=100): print(user.name)
Flattening into a list:
users = await event.subscribers(limit=100).flatten() # users is now a list of User...
Getting members instead of user objects:
async for member in event.subscribers(limit=100, as_member=True): print(member.display_name)
- class discord.events.GuildScheduledEventUserAdd[source]¶
Called when a user subscribes to a scheduled event.
This requires
Intents.scheduled_eventsto be enabled.- event¶
The scheduled event subscribed to.
- Type:
ScheduledEvent
- member¶
The member who subscribed.
- Type:
Member
- raw¶
The raw event payload data.
- Type:
RawScheduledEventSubscription
- class discord.events.GuildScheduledEventUserRemove[source]¶
Called when a user unsubscribes from a scheduled event.
This requires
Intents.scheduled_eventsto be enabled.- event¶
The scheduled event unsubscribed from.
- Type:
ScheduledEvent
- member¶
The member who unsubscribed.
- Type:
Member
- raw¶
The raw event payload data.
- Type:
RawScheduledEventSubscription
Soundboard¶
- class discord.events.GuildSoundboardSoundCreate(sound)[source]¶
Called when a soundboard sound is created.
This event inherits from
SoundboardSound.- Parameters:
sound (
SoundboardSound)
- class discord.events.GuildSoundboardSoundUpdate(before, after)[source]¶
Called when a soundboard sound is updated.
- old¶
The soundboard sound prior to being updated (if it was cached).
- Type:
SoundboardSound| None
- new¶
The soundboard sound after being updated.
- Type:
SoundboardSound
- Parameters:
before (
SoundboardSound)after (
SoundboardSound)
- class discord.events.GuildSoundboardSoundDelete(sound, raw)[source]¶
Called when a soundboard sound is deleted.
- raw¶
The raw event payload data.
- Type:
RawSoundboardSoundDeleteEvent
- sound¶
The deleted sound (if it was cached).
- Type:
SoundboardSound| None
- Parameters:
sound (
SoundboardSound|None)raw (
RawSoundboardSoundDeleteEvent)
- class discord.events.GuildSoundboardSoundsUpdate(before_sounds, after_sounds)[source]¶
Called when multiple guild soundboard sounds are updated at once.
This is called, for example, when a guild loses a boost level and some sounds become unavailable.
- old_sounds¶
The soundboard sounds prior to being updated (only if all were cached).
- Type:
list[
SoundboardSound] | None
- new_sounds¶
The soundboard sounds after being updated.
- Type:
list[
SoundboardSound]
- Parameters:
before_sounds (
list[SoundboardSound])after_sounds (
list[SoundboardSound])
Stage Instances¶
- class discord.events.StageInstanceCreate[source]¶
Called when a stage instance is created for a stage channel.
This event inherits from
StageInstance.- await delete(*, reason=None)¶
This function is a coroutine.
Deletes the stage instance.
You must have the
manage_channelspermission to use this.- Parameters:
reason (
str) – The reason the stage instance was deleted. Shows up on the audit log.- Raises:
Forbidden – You do not have permissions to delete the stage instance.
HTTPException – Deleting the stage instance failed.
- Return type:
- await edit(*, topic=Undefined.MISSING, privacy_level=Undefined.MISSING, reason=None)¶
This function is a coroutine.
Edits the stage instance.
You must have the
manage_channelspermission to use this.- Parameters:
- Raises:
InvalidArgument – If the
privacy_levelparameter is not the proper type.Forbidden – You do not have permissions to edit the stage instance.
HTTPException – Editing a stage instance failed.
- Return type:
- await get_channel()¶
The channel that stage instance is running in.
- Return type:
- class discord.events.StageInstanceUpdate[source]¶
Called when a stage instance is updated.
The following, but not limited to, examples illustrate when this event is called: - The topic is changed. - The privacy level is changed.
This event inherits from
StageInstance.- old¶
The stage instance before the update.
- Type:
StageInstance
- await delete(*, reason=None)¶
This function is a coroutine.
Deletes the stage instance.
You must have the
manage_channelspermission to use this.- Parameters:
reason (
str) – The reason the stage instance was deleted. Shows up on the audit log.- Raises:
Forbidden – You do not have permissions to delete the stage instance.
HTTPException – Deleting the stage instance failed.
- Return type:
- await edit(*, topic=Undefined.MISSING, privacy_level=Undefined.MISSING, reason=None)¶
This function is a coroutine.
Edits the stage instance.
You must have the
manage_channelspermission to use this.- Parameters:
- Raises:
InvalidArgument – If the
privacy_levelparameter is not the proper type.Forbidden – You do not have permissions to edit the stage instance.
HTTPException – Editing a stage instance failed.
- Return type:
- await get_channel()¶
The channel that stage instance is running in.
- Return type:
- class discord.events.StageInstanceDelete[source]¶
Called when a stage instance is deleted for a stage channel.
This event inherits from
StageInstance.- await delete(*, reason=None)¶
This function is a coroutine.
Deletes the stage instance.
You must have the
manage_channelspermission to use this.- Parameters:
reason (
str) – The reason the stage instance was deleted. Shows up on the audit log.- Raises:
Forbidden – You do not have permissions to delete the stage instance.
HTTPException – Deleting the stage instance failed.
- Return type:
- await edit(*, topic=Undefined.MISSING, privacy_level=Undefined.MISSING, reason=None)¶
This function is a coroutine.
Edits the stage instance.
You must have the
manage_channelspermission to use this.- Parameters:
- Raises:
InvalidArgument – If the
privacy_levelparameter is not the proper type.Forbidden – You do not have permissions to edit the stage instance.
HTTPException – Editing a stage instance failed.
- Return type:
- await get_channel()¶
The channel that stage instance is running in.
- Return type:
Threads¶
- class discord.events.ThreadCreate[source]¶
Called whenever a thread is created.
Note that you can get the guild from
Thread.guild.This requires
Intents.guildsto be enabled.This event inherits from
Thread.- await add_user(user)¶
This function is a coroutine.
Adds a user to this thread.
You must have
send_messages_in_threadsto add a user to a public thread. If the thread is private andinvitableisFalse, thenmanage_threadsis required.- Parameters:
user (
abc.Snowflake) – The user to add to the thread.- Raises:
Forbidden – You do not have permissions to add the user to the thread.
HTTPException – Adding the user to the thread failed.
- property applied_tags: list[ForumTag]¶
A list of tags applied to this thread.
This is only available for threads in forum or media channels.
- Type:
List[
ForumTag]
- await archive(locked=Undefined.MISSING)¶
This function is a coroutine.
Archives the thread. This is a shorthand of
edit().
- can_send(*objects)¶
Returns a
boolindicating whether you have the permissions to send the object(s).
- property category: CategoryChannel | None¶
The category channel the parent channel belongs to, if applicable.
- Returns:
The parent channel’s category.
- Return type:
Optional[
CategoryChannel]- Raises:
ClientException – The parent channel was not cached and returned
None.
- property category_id: int | None¶
The category channel ID the parent channel belongs to, if applicable.
- Returns:
The parent channel’s category ID.
- Return type:
Optional[
int]- Raises:
ClientException – The parent channel was not cached and returned
None.
- await clone(*, name=None, reason=None)¶
This function is a coroutine.
Clones this channel. This creates a channel with the same properties as this channel.
You must have the
manage_channelspermission to do this.Added in version 1.1.
- Parameters:
- Returns:
The channel that was created.
- Return type:
- Raises:
Forbidden – You do not have the proper permissions to create this channel.
HTTPException – Creating the channel failed.
- await create_webhook(*, name, avatar=None, reason=None)¶
This function is a coroutine.
Creates a webhook for this channel.
Requires
manage_webhookspermissions.Changed in version 1.1: Added the
reasonkeyword-only parameter.- Parameters:
name (
str) – The webhook’s name.avatar (Optional[
bytes]) – A bytes-like object representing the webhook’s default avatar. This operates similarly toedit().reason (Optional[
str]) – The reason for creating this webhook. Shows up in the audit logs.
- Returns:
The created webhook.
- Return type:
Webhook- Raises:
HTTPException – Creating the webhook failed.
Forbidden – You do not have permissions to create a webhook.
- created_at¶
- await delete()¶
This function is a coroutine.
Deletes this thread.
You must have
manage_threadsto delete threads.- Raises:
Forbidden – You do not have permissions to delete this thread.
HTTPException – Deleting the thread failed.
- await delete_messages(messages, *, reason=None)¶
This function is a coroutine.
Deletes a list of messages. This is similar to
Message.delete()except it bulk deletes multiple messages.As a special case, if the number of messages is 0, then nothing is done. If the number of messages is 1 then single message delete is done. If it’s more than two, then bulk delete is used.
You cannot bulk delete more than 100 messages or messages that are older than 14 days old.
You must have the
manage_messagespermission to use this.Usable only by bot accounts.
- Parameters:
messages (Iterable[
abc.Snowflake]) – An iterable of messages denoting which ones to bulk delete.reason (Optional[
str]) – The reason for deleting the messages. Shows up on the audit log.
- Raises:
ClientException – The number of messages to delete was more than 100.
Forbidden – You do not have proper permissions to delete the messages, or you’re not using a bot account.
NotFound – If single delete, then the message was already deleted.
HTTPException – Deleting the messages failed.
- Return type:
- await edit(*, name=Undefined.MISSING, archived=Undefined.MISSING, locked=Undefined.MISSING, invitable=Undefined.MISSING, slowmode_delay=Undefined.MISSING, auto_archive_duration=Undefined.MISSING, pinned=Undefined.MISSING, applied_tags=Undefined.MISSING, reason=None)¶
This function is a coroutine.
Edits the thread.
Editing the thread requires
Permissions.manage_threads. The thread creator can also editname,archivedorauto_archive_duration. Note that if the thread is locked then only those withPermissions.manage_threadscan send messages in it or unarchive a thread.The thread must be unarchived to be edited.
- Parameters:
name (
str) – The new name of the thread.archived (
bool) – Whether to archive the thread or not.locked (
bool) – Whether to lock the thread or not.invitable (
bool) – Whether non-moderators can add other non-moderators to this thread. Only available for private threads.auto_archive_duration (
int) – The new duration in minutes before a thread is automatically archived for inactivity. Must be one of60,1440,4320, or10080.ThreadArchiveDurationcan be used alternatively.slowmode_delay (
int) – Specifies the slowmode rate limit for user in this thread, in seconds. A value of0disables slowmode. The maximum value possible is21600.reason (Optional[
str]) – The reason for editing this thread. Shows up on the audit log.pinned (
bool) – Whether to pin the thread or not. This only works if the thread is part of a forum or media channel.applied_tags (List[
ForumTag]) –The set of tags to apply to the thread. Each tag object should have an ID set.
Added in version 2.3.
- Returns:
The newly edited thread.
- Return type:
Thread- Raises:
Forbidden – You do not have permissions to edit the thread.
HTTPException – Editing the thread failed.
- await fetch_members()¶
This function is a coroutine.
Retrieves all
ThreadMemberthat are in this thread.This requires
Intents.membersto get information about members other than yourself.- Returns:
All thread members in the thread.
- Return type:
List[
ThreadMember]- Raises:
HTTPException – Retrieving the members failed.
- await fetch_message(id, /)¶
This function is a coroutine.
Retrieves a single
Messagefrom the destination.- Parameters:
id (
int) – The message ID to look for.- Returns:
The message asked for.
- Return type:
- Raises:
NotFound – The specified message was not found.
Forbidden – You do not have the permissions required to get a message.
HTTPException – Retrieving the message failed.
- await follow(*, destination, reason=None)¶
Follows a channel using a webhook.
Only news channels can be followed.
Note
The webhook returned will not provide a token to do webhook actions, as Discord does not provide it.
Added in version 1.3.
- Parameters:
destination (
TextChannel) – The channel you would like to follow from.reason (Optional[
str]) –The reason for following the channel. Shows up on the destination guild’s audit log.
Added in version 1.4.
- Returns:
The created webhook.
- Return type:
Webhook- Raises:
HTTPException – Following the channel failed.
Forbidden – You do not have the permissions to create a webhook.
- await get_last_message()¶
Returns the last message from this thread in cache.
The message might not be valid or point to an existing message.
Reliable Fetching
For a slightly more reliable method of fetching the last message, consider using either
history()orfetch_message()with thelast_message_idattribute.- Returns:
The last message in this channel or
Noneif not found.- Return type:
Optional[
Message]
- await get_owner()¶
The member this thread belongs to.
- Return type:
Member | None
- get_partial_message(message_id, /)¶
Creates a
PartialMessagefrom the message ID.This is useful if you want to work with a message and only have its ID without doing an unnecessary API call.
Added in version 2.0.
- Parameters:
message_id (
int) – The message ID to create a partial message for.- Returns:
The partial message.
- Return type:
PartialMessage
- await get_starting_message()¶
Returns the message that started this thread.
The message might not be valid or point to an existing message.
Note
The ID for this message is the same as the thread ID.
- Returns:
The message that started this thread or
Noneif not found in the cache.- Return type:
Optional[
Message]
- history(*, limit=100, before=None, after=None, around=None, oldest_first=None)¶
Returns an
AsyncIteratorthat enables receiving the destination’s message history.You must have
read_message_historypermissions to use this.- Parameters:
limit (Optional[
int]) – The number of messages to retrieve. IfNone, retrieves every message in the channel. Note, however, that this would make it a slow operation.before (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages before this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.after (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages after this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.around (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages around this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time. When using this argument, the maximum limit is 101. Note that if the limit is an even number, then this will return at most limit + 1 messages.oldest_first (Optional[
bool]) – If set toTrue, return messages in oldest->newest order. Defaults toTrueifafteris specified, otherwiseFalse.
- Yields:
Message– The message with the message data parsed.- Raises:
Forbidden – You do not have permissions to get channel message history.
HTTPException – The request to get message history failed.
- Return type:
HistoryIterator
Examples
Usage
counter = 0 async for message in channel.history(limit=200): if message.author == client.user: counter += 1
Flattening into a list:
messages = await channel.history(limit=123).flatten() # messages is now a list of Message...
All parameters are optional.
- is_news()¶
Whether the thread is a news thread.
A news thread is a thread that has a parent that is a news channel, i.e.
TextChannel.is_news()isTrue.- Return type:
- is_nsfw()¶
Whether the thread is NSFW or not.
An NSFW thread is a thread that has a parent that is an NSFW channel, i.e.
TextChannel.is_nsfw()isTrue.- Return type:
- is_pinned()¶
Whether the thread is pinned to the top of its parent forum or media channel. :rtype:
boolAdded in version 2.3.
- is_private()¶
Whether the thread is a private thread.
A private thread is only viewable by those that have been explicitly invited or have
manage_threads.- Return type:
- await join()¶
This function is a coroutine.
Joins this thread.
You must have
send_messages_in_threadsto join a thread. If the thread is private,manage_threadsis also needed.- Raises:
Forbidden – You do not have permissions to join the thread.
HTTPException – Joining the thread failed.
- property jump_url: str¶
Returns a URL that allows the client to jump to the thread.
Added in version 2.0.
- await leave()¶
This function is a coroutine.
Leaves this thread.
- Raises:
HTTPException – Leaving the thread failed.
- property members: list[ThreadMember]¶
A list of thread members in this thread, including the bot if it is a member of this thread.
This requires
Intents.membersto be properly filled. Most of the time however, this data is not provided by the gateway and a call tofetch_members()is needed.
- property parent: TextChannel | ForumChannel | None¶
The parent channel this thread belongs to.
- permissions_for(obj, /)¶
Handles permission resolution for the
MemberorRole.Since threads do not have their own permissions, they inherit them from the parent channel. This is a convenience method for calling
permissions_for()on the parent channel.- Parameters:
obj (Union[
Member,Role]) – The object to resolve permissions for. This could be either a member or a role. If it’s a role then member overwrites are not computed.- Returns:
The resolved permissions for the member or role.
- Return type:
- Raises:
ClientException – The parent channel was not cached and returned
None
- pins(*, limit=50, before=None)¶
Returns a
MessagePinIteratorthat enables receiving the destination’s pinned messages.You must have
read_message_historypermissions to use this.Warning
Starting from version 3.0, await channel.pins() will no longer return a list of
Message. See examples below for new usage instead.- Parameters:
limit (Optional[
int]) – The number of pinned messages to retrieve. IfNone, retrieves every pinned message in the channel.before (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages pinned before this datetime. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.
- Yields:
MessagePin– The pinned message.- Raises:
Forbidden – You do not have permissions to get pinned messages.
HTTPException – The request to get pinned messages failed.
- Return type:
MessagePinIterator
Examples
Usage
counter = 0 async for pin in channel.pins(limit=250): if pin.message.author == client.user: counter += 1
Flattening into a list:
pins = await channel.pins(limit=None).flatten() # pins is now a list of MessagePin...
All parameters are optional.
- await purge(*, limit=100, check=Undefined.MISSING, before=None, after=None, around=None, oldest_first=False, bulk=True, reason=None)¶
This function is a coroutine.
Purges a list of messages that meet the criteria given by the predicate
check. If acheckis not provided then all messages are deleted without discrimination.You must have the
manage_messagespermission to delete messages even if they are your own (unless you are a user account). Theread_message_historypermission is also needed to retrieve message history.- Parameters:
limit (Optional[
int]) – The number of messages to search through. This is not the number of messages that will be deleted, though it can be.check (Callable[[
Message],bool]) – The function used to check if a message should be deleted. It must take aMessageas its sole parameter.before (Optional[Union[
abc.Snowflake,datetime.datetime]]) – Same asbeforeinhistory().after (Optional[Union[
abc.Snowflake,datetime.datetime]]) – Same asafterinhistory().around (Optional[Union[
abc.Snowflake,datetime.datetime]]) – Same asaroundinhistory().oldest_first (Optional[
bool]) – Same asoldest_firstinhistory().bulk (
bool) – IfTrue, use bulk delete. Setting this toFalseis useful for mass-deleting a bot’s own messages withoutPermissions.manage_messages. WhenTrue, will fall back to single delete if messages are older than two weeks.reason (Optional[
str]) – The reason for deleting the messages. Shows up on the audit log.
- Returns:
The list of messages that were deleted.
- Return type:
List[
Message]- Raises:
Forbidden – You do not have proper permissions to do the actions required.
HTTPException – Purging the messages failed.
Examples
Deleting bot’s messages
def is_me(m): return m.author == client.user deleted = await thread.purge(limit=100, check=is_me) await thread.send(f"Deleted {len(deleted)} message(s)")
- await remove_user(user)¶
This function is a coroutine.
Removes a user from this thread.
You must have
manage_threadsor be the creator of the thread to remove a user.- Parameters:
user (
abc.Snowflake) – The user to remove from the thread.- Raises:
Forbidden – You do not have permissions to remove the user from the thread.
HTTPException – Removing the user from the thread failed.
- await send(content=None, *, tts=None, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, enforce_nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None, poll=None, suppress=None, silent=None)¶
This function is a coroutine.
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through
str(content). If the content is set toNone(the default), then theembedparameter must be provided.To upload a single file, the
fileparameter should be used with a singleFileobject. To upload multiple files, thefilesparameter should be used with alistofFileobjects. Specifying both parameters will lead to an exception.To upload a single embed, the
embedparameter should be used with a singleEmbedobject. To upload multiple embeds, theembedsparameter should be used with alistofEmbedobjects. Specifying both parameters will lead to an exception.- Parameters:
content (Optional[
str]) – The content of the message to send.tts (
bool) – Indicates if the message should be sent using text-to-speech.embed (
Embed) – The rich embed for the content.file (
File) – The file to upload.files (List[
File]) – A list of files to upload. Must be a maximum of 10.nonce (Union[
str,int]) – The nonce to use for sending this message. If the message was successfully sent, then the message will have a nonce with this value.enforce_nonce (Optional[
bool]) –Whether
nonceis enforced to be validated.Added in version 2.5.
delete_after (
float) – If provided, the number of seconds to wait in the background before deleting the message we just sent. If the deletion fails, then it is silently ignored.allowed_mentions (
AllowedMentions) –Controls the mentions being processed in this message. If this is passed, then the object is merged with
allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set inallowed_mentions. If no object is passed at all then the defaults given byallowed_mentionsare used instead.Added in version 1.4.
reference (Union[
Message,MessageReference,PartialMessage]) –A reference to the
Messagebeing replied to or forwarded. This can be created usingto_reference(). When replying, you can control whether this mentions the author of the referenced message using thereplied_userattribute ofallowed_mentionsor by settingmention_author.Added in version 1.6.
mention_author (Optional[
bool]) –If set, overrides the
replied_userattribute ofallowed_mentions.Added in version 1.6.
view (
discord.ui.View) – A Discord UI View to add to the message.embeds (List[
Embed]) –A list of embeds to upload. Must be a maximum of 10.
Added in version 2.0.
stickers (Sequence[Union[
GuildSticker,StickerItem]]) –A list of stickers to upload. Must be a maximum of 3.
Added in version 2.0.
suppress (
bool) – Whether to suppress embeds for the message.silent (
bool) –Whether to suppress push and desktop notifications for the message.
Added in version 2.4.
poll (
Poll) –The poll to send.
Added in version 2.6.
- Returns:
The message that was sent.
- Return type:
- Raises:
HTTPException – Sending the message failed.
Forbidden – You do not have the proper permissions to send the message.
InvalidArgument – The
fileslist is not of the appropriate size, you specified bothfileandfiles, or you specified bothembedandembeds, or thereferenceobject is not aMessage,MessageReferenceorPartialMessage.
- await trigger_typing()¶
This function is a coroutine.
Triggers a typing indicator to the destination.
Typing indicator will go away after 10 seconds, or after a message is sent.
- Return type:
- property type: ChannelType¶
The channel’s Discord type.
- typing()¶
Returns a context manager that allows you to type for an indefinite period of time.
This is useful for denoting long computations in your bot. :rtype:
TypingNote
This is both a regular context manager and an async context manager. This means that both
withandasync withwork with this.Example Usage:
async with channel.typing(): # simulate something heavy await asyncio.sleep(10) await channel.send("done!")
- await unarchive()¶
This function is a coroutine.
Unarchives the thread. This is a shorthand of
edit().- Returns:
The updated thread.
- Return type:
- await webhooks()¶
This function is a coroutine.
Gets the list of webhooks from this channel.
Requires
manage_webhookspermissions.- Returns:
The webhooks for this channel.
- Return type:
List[
Webhook]- Raises:
Forbidden – You don’t have permissions to get the webhooks.
- class discord.events.ThreadUpdate[source]¶
Called whenever a thread is updated.
This requires
Intents.guildsto be enabled.This event inherits from
Thread.- old¶
The thread’s old info before the update.
- Type:
Thread
- await add_user(user)¶
This function is a coroutine.
Adds a user to this thread.
You must have
send_messages_in_threadsto add a user to a public thread. If the thread is private andinvitableisFalse, thenmanage_threadsis required.- Parameters:
user (
abc.Snowflake) – The user to add to the thread.- Raises:
Forbidden – You do not have permissions to add the user to the thread.
HTTPException – Adding the user to the thread failed.
- property applied_tags: list[ForumTag]¶
A list of tags applied to this thread.
This is only available for threads in forum or media channels.
- Type:
List[
ForumTag]
- await archive(locked=Undefined.MISSING)¶
This function is a coroutine.
Archives the thread. This is a shorthand of
edit().
- can_send(*objects)¶
Returns a
boolindicating whether you have the permissions to send the object(s).
- property category: CategoryChannel | None¶
The category channel the parent channel belongs to, if applicable.
- Returns:
The parent channel’s category.
- Return type:
Optional[
CategoryChannel]- Raises:
ClientException – The parent channel was not cached and returned
None.
- property category_id: int | None¶
The category channel ID the parent channel belongs to, if applicable.
- Returns:
The parent channel’s category ID.
- Return type:
Optional[
int]- Raises:
ClientException – The parent channel was not cached and returned
None.
- await clone(*, name=None, reason=None)¶
This function is a coroutine.
Clones this channel. This creates a channel with the same properties as this channel.
You must have the
manage_channelspermission to do this.Added in version 1.1.
- Parameters:
- Returns:
The channel that was created.
- Return type:
- Raises:
Forbidden – You do not have the proper permissions to create this channel.
HTTPException – Creating the channel failed.
- await create_webhook(*, name, avatar=None, reason=None)¶
This function is a coroutine.
Creates a webhook for this channel.
Requires
manage_webhookspermissions.Changed in version 1.1: Added the
reasonkeyword-only parameter.- Parameters:
name (
str) – The webhook’s name.avatar (Optional[
bytes]) – A bytes-like object representing the webhook’s default avatar. This operates similarly toedit().reason (Optional[
str]) – The reason for creating this webhook. Shows up in the audit logs.
- Returns:
The created webhook.
- Return type:
Webhook- Raises:
HTTPException – Creating the webhook failed.
Forbidden – You do not have permissions to create a webhook.
- await delete()¶
This function is a coroutine.
Deletes this thread.
You must have
manage_threadsto delete threads.- Raises:
Forbidden – You do not have permissions to delete this thread.
HTTPException – Deleting the thread failed.
- await delete_messages(messages, *, reason=None)¶
This function is a coroutine.
Deletes a list of messages. This is similar to
Message.delete()except it bulk deletes multiple messages.As a special case, if the number of messages is 0, then nothing is done. If the number of messages is 1 then single message delete is done. If it’s more than two, then bulk delete is used.
You cannot bulk delete more than 100 messages or messages that are older than 14 days old.
You must have the
manage_messagespermission to use this.Usable only by bot accounts.
- Parameters:
messages (Iterable[
abc.Snowflake]) – An iterable of messages denoting which ones to bulk delete.reason (Optional[
str]) – The reason for deleting the messages. Shows up on the audit log.
- Raises:
ClientException – The number of messages to delete was more than 100.
Forbidden – You do not have proper permissions to delete the messages, or you’re not using a bot account.
NotFound – If single delete, then the message was already deleted.
HTTPException – Deleting the messages failed.
- Return type:
- await edit(*, name=Undefined.MISSING, archived=Undefined.MISSING, locked=Undefined.MISSING, invitable=Undefined.MISSING, slowmode_delay=Undefined.MISSING, auto_archive_duration=Undefined.MISSING, pinned=Undefined.MISSING, applied_tags=Undefined.MISSING, reason=None)¶
This function is a coroutine.
Edits the thread.
Editing the thread requires
Permissions.manage_threads. The thread creator can also editname,archivedorauto_archive_duration. Note that if the thread is locked then only those withPermissions.manage_threadscan send messages in it or unarchive a thread.The thread must be unarchived to be edited.
- Parameters:
name (
str) – The new name of the thread.archived (
bool) – Whether to archive the thread or not.locked (
bool) – Whether to lock the thread or not.invitable (
bool) – Whether non-moderators can add other non-moderators to this thread. Only available for private threads.auto_archive_duration (
int) – The new duration in minutes before a thread is automatically archived for inactivity. Must be one of60,1440,4320, or10080.ThreadArchiveDurationcan be used alternatively.slowmode_delay (
int) – Specifies the slowmode rate limit for user in this thread, in seconds. A value of0disables slowmode. The maximum value possible is21600.reason (Optional[
str]) – The reason for editing this thread. Shows up on the audit log.pinned (
bool) – Whether to pin the thread or not. This only works if the thread is part of a forum or media channel.applied_tags (List[
ForumTag]) –The set of tags to apply to the thread. Each tag object should have an ID set.
Added in version 2.3.
- Returns:
The newly edited thread.
- Return type:
Thread- Raises:
Forbidden – You do not have permissions to edit the thread.
HTTPException – Editing the thread failed.
- await fetch_members()¶
This function is a coroutine.
Retrieves all
ThreadMemberthat are in this thread.This requires
Intents.membersto get information about members other than yourself.- Returns:
All thread members in the thread.
- Return type:
List[
ThreadMember]- Raises:
HTTPException – Retrieving the members failed.
- await fetch_message(id, /)¶
This function is a coroutine.
Retrieves a single
Messagefrom the destination.- Parameters:
id (
int) – The message ID to look for.- Returns:
The message asked for.
- Return type:
- Raises:
NotFound – The specified message was not found.
Forbidden – You do not have the permissions required to get a message.
HTTPException – Retrieving the message failed.
- await follow(*, destination, reason=None)¶
Follows a channel using a webhook.
Only news channels can be followed.
Note
The webhook returned will not provide a token to do webhook actions, as Discord does not provide it.
Added in version 1.3.
- Parameters:
destination (
TextChannel) – The channel you would like to follow from.reason (Optional[
str]) –The reason for following the channel. Shows up on the destination guild’s audit log.
Added in version 1.4.
- Returns:
The created webhook.
- Return type:
Webhook- Raises:
HTTPException – Following the channel failed.
Forbidden – You do not have the permissions to create a webhook.
- await get_last_message()¶
Returns the last message from this thread in cache.
The message might not be valid or point to an existing message.
Reliable Fetching
For a slightly more reliable method of fetching the last message, consider using either
history()orfetch_message()with thelast_message_idattribute.- Returns:
The last message in this channel or
Noneif not found.- Return type:
Optional[
Message]
- await get_owner()¶
The member this thread belongs to.
- Return type:
Member | None
- get_partial_message(message_id, /)¶
Creates a
PartialMessagefrom the message ID.This is useful if you want to work with a message and only have its ID without doing an unnecessary API call.
Added in version 2.0.
- Parameters:
message_id (
int) – The message ID to create a partial message for.- Returns:
The partial message.
- Return type:
PartialMessage
- await get_starting_message()¶
Returns the message that started this thread.
The message might not be valid or point to an existing message.
Note
The ID for this message is the same as the thread ID.
- Returns:
The message that started this thread or
Noneif not found in the cache.- Return type:
Optional[
Message]
- history(*, limit=100, before=None, after=None, around=None, oldest_first=None)¶
Returns an
AsyncIteratorthat enables receiving the destination’s message history.You must have
read_message_historypermissions to use this.- Parameters:
limit (Optional[
int]) – The number of messages to retrieve. IfNone, retrieves every message in the channel. Note, however, that this would make it a slow operation.before (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages before this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.after (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages after this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.around (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages around this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time. When using this argument, the maximum limit is 101. Note that if the limit is an even number, then this will return at most limit + 1 messages.oldest_first (Optional[
bool]) – If set toTrue, return messages in oldest->newest order. Defaults toTrueifafteris specified, otherwiseFalse.
- Yields:
Message– The message with the message data parsed.- Raises:
Forbidden – You do not have permissions to get channel message history.
HTTPException – The request to get message history failed.
- Return type:
HistoryIterator
Examples
Usage
counter = 0 async for message in channel.history(limit=200): if message.author == client.user: counter += 1
Flattening into a list:
messages = await channel.history(limit=123).flatten() # messages is now a list of Message...
All parameters are optional.
- is_news()¶
Whether the thread is a news thread.
A news thread is a thread that has a parent that is a news channel, i.e.
TextChannel.is_news()isTrue.- Return type:
- is_nsfw()¶
Whether the thread is NSFW or not.
An NSFW thread is a thread that has a parent that is an NSFW channel, i.e.
TextChannel.is_nsfw()isTrue.- Return type:
- is_pinned()¶
Whether the thread is pinned to the top of its parent forum or media channel. :rtype:
boolAdded in version 2.3.
- is_private()¶
Whether the thread is a private thread.
A private thread is only viewable by those that have been explicitly invited or have
manage_threads.- Return type:
- await join()¶
This function is a coroutine.
Joins this thread.
You must have
send_messages_in_threadsto join a thread. If the thread is private,manage_threadsis also needed.- Raises:
Forbidden – You do not have permissions to join the thread.
HTTPException – Joining the thread failed.
- property jump_url: str¶
Returns a URL that allows the client to jump to the thread.
Added in version 2.0.
- await leave()¶
This function is a coroutine.
Leaves this thread.
- Raises:
HTTPException – Leaving the thread failed.
- property members: list[ThreadMember]¶
A list of thread members in this thread, including the bot if it is a member of this thread.
This requires
Intents.membersto be properly filled. Most of the time however, this data is not provided by the gateway and a call tofetch_members()is needed.
- property parent: TextChannel | ForumChannel | None¶
The parent channel this thread belongs to.
- permissions_for(obj, /)¶
Handles permission resolution for the
MemberorRole.Since threads do not have their own permissions, they inherit them from the parent channel. This is a convenience method for calling
permissions_for()on the parent channel.- Parameters:
obj (Union[
Member,Role]) – The object to resolve permissions for. This could be either a member or a role. If it’s a role then member overwrites are not computed.- Returns:
The resolved permissions for the member or role.
- Return type:
- Raises:
ClientException – The parent channel was not cached and returned
None
- pins(*, limit=50, before=None)¶
Returns a
MessagePinIteratorthat enables receiving the destination’s pinned messages.You must have
read_message_historypermissions to use this.Warning
Starting from version 3.0, await channel.pins() will no longer return a list of
Message. See examples below for new usage instead.- Parameters:
limit (Optional[
int]) – The number of pinned messages to retrieve. IfNone, retrieves every pinned message in the channel.before (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages pinned before this datetime. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.
- Yields:
MessagePin– The pinned message.- Raises:
Forbidden – You do not have permissions to get pinned messages.
HTTPException – The request to get pinned messages failed.
- Return type:
MessagePinIterator
Examples
Usage
counter = 0 async for pin in channel.pins(limit=250): if pin.message.author == client.user: counter += 1
Flattening into a list:
pins = await channel.pins(limit=None).flatten() # pins is now a list of MessagePin...
All parameters are optional.
- await purge(*, limit=100, check=Undefined.MISSING, before=None, after=None, around=None, oldest_first=False, bulk=True, reason=None)¶
This function is a coroutine.
Purges a list of messages that meet the criteria given by the predicate
check. If acheckis not provided then all messages are deleted without discrimination.You must have the
manage_messagespermission to delete messages even if they are your own (unless you are a user account). Theread_message_historypermission is also needed to retrieve message history.- Parameters:
limit (Optional[
int]) – The number of messages to search through. This is not the number of messages that will be deleted, though it can be.check (Callable[[
Message],bool]) – The function used to check if a message should be deleted. It must take aMessageas its sole parameter.before (Optional[Union[
abc.Snowflake,datetime.datetime]]) – Same asbeforeinhistory().after (Optional[Union[
abc.Snowflake,datetime.datetime]]) – Same asafterinhistory().around (Optional[Union[
abc.Snowflake,datetime.datetime]]) – Same asaroundinhistory().oldest_first (Optional[
bool]) – Same asoldest_firstinhistory().bulk (
bool) – IfTrue, use bulk delete. Setting this toFalseis useful for mass-deleting a bot’s own messages withoutPermissions.manage_messages. WhenTrue, will fall back to single delete if messages are older than two weeks.reason (Optional[
str]) – The reason for deleting the messages. Shows up on the audit log.
- Returns:
The list of messages that were deleted.
- Return type:
List[
Message]- Raises:
Forbidden – You do not have proper permissions to do the actions required.
HTTPException – Purging the messages failed.
Examples
Deleting bot’s messages
def is_me(m): return m.author == client.user deleted = await thread.purge(limit=100, check=is_me) await thread.send(f"Deleted {len(deleted)} message(s)")
- await remove_user(user)¶
This function is a coroutine.
Removes a user from this thread.
You must have
manage_threadsor be the creator of the thread to remove a user.- Parameters:
user (
abc.Snowflake) – The user to remove from the thread.- Raises:
Forbidden – You do not have permissions to remove the user from the thread.
HTTPException – Removing the user from the thread failed.
- await send(content=None, *, tts=None, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, enforce_nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None, poll=None, suppress=None, silent=None)¶
This function is a coroutine.
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through
str(content). If the content is set toNone(the default), then theembedparameter must be provided.To upload a single file, the
fileparameter should be used with a singleFileobject. To upload multiple files, thefilesparameter should be used with alistofFileobjects. Specifying both parameters will lead to an exception.To upload a single embed, the
embedparameter should be used with a singleEmbedobject. To upload multiple embeds, theembedsparameter should be used with alistofEmbedobjects. Specifying both parameters will lead to an exception.- Parameters:
content (Optional[
str]) – The content of the message to send.tts (
bool) – Indicates if the message should be sent using text-to-speech.embed (
Embed) – The rich embed for the content.file (
File) – The file to upload.files (List[
File]) – A list of files to upload. Must be a maximum of 10.nonce (Union[
str,int]) – The nonce to use for sending this message. If the message was successfully sent, then the message will have a nonce with this value.enforce_nonce (Optional[
bool]) –Whether
nonceis enforced to be validated.Added in version 2.5.
delete_after (
float) – If provided, the number of seconds to wait in the background before deleting the message we just sent. If the deletion fails, then it is silently ignored.allowed_mentions (
AllowedMentions) –Controls the mentions being processed in this message. If this is passed, then the object is merged with
allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set inallowed_mentions. If no object is passed at all then the defaults given byallowed_mentionsare used instead.Added in version 1.4.
reference (Union[
Message,MessageReference,PartialMessage]) –A reference to the
Messagebeing replied to or forwarded. This can be created usingto_reference(). When replying, you can control whether this mentions the author of the referenced message using thereplied_userattribute ofallowed_mentionsor by settingmention_author.Added in version 1.6.
mention_author (Optional[
bool]) –If set, overrides the
replied_userattribute ofallowed_mentions.Added in version 1.6.
view (
discord.ui.View) – A Discord UI View to add to the message.embeds (List[
Embed]) –A list of embeds to upload. Must be a maximum of 10.
Added in version 2.0.
stickers (Sequence[Union[
GuildSticker,StickerItem]]) –A list of stickers to upload. Must be a maximum of 3.
Added in version 2.0.
suppress (
bool) – Whether to suppress embeds for the message.silent (
bool) –Whether to suppress push and desktop notifications for the message.
Added in version 2.4.
poll (
Poll) –The poll to send.
Added in version 2.6.
- Returns:
The message that was sent.
- Return type:
- Raises:
HTTPException – Sending the message failed.
Forbidden – You do not have the proper permissions to send the message.
InvalidArgument – The
fileslist is not of the appropriate size, you specified bothfileandfiles, or you specified bothembedandembeds, or thereferenceobject is not aMessage,MessageReferenceorPartialMessage.
- await trigger_typing()¶
This function is a coroutine.
Triggers a typing indicator to the destination.
Typing indicator will go away after 10 seconds, or after a message is sent.
- Return type:
- property type: ChannelType¶
The channel’s Discord type.
- typing()¶
Returns a context manager that allows you to type for an indefinite period of time.
This is useful for denoting long computations in your bot. :rtype:
TypingNote
This is both a regular context manager and an async context manager. This means that both
withandasync withwork with this.Example Usage:
async with channel.typing(): # simulate something heavy await asyncio.sleep(10) await channel.send("done!")
- await unarchive()¶
This function is a coroutine.
Unarchives the thread. This is a shorthand of
edit().- Returns:
The updated thread.
- Return type:
- await webhooks()¶
This function is a coroutine.
Gets the list of webhooks from this channel.
Requires
manage_webhookspermissions.- Returns:
The webhooks for this channel.
- Return type:
List[
Webhook]- Raises:
Forbidden – You don’t have permissions to get the webhooks.
- class discord.events.ThreadDelete[source]¶
Called whenever a thread is deleted.
Note that you can get the guild from
Thread.guild.This requires
Intents.guildsto be enabled.This event inherits from
Thread.- await add_user(user)¶
This function is a coroutine.
Adds a user to this thread.
You must have
send_messages_in_threadsto add a user to a public thread. If the thread is private andinvitableisFalse, thenmanage_threadsis required.- Parameters:
user (
abc.Snowflake) – The user to add to the thread.- Raises:
Forbidden – You do not have permissions to add the user to the thread.
HTTPException – Adding the user to the thread failed.
- property applied_tags: list[ForumTag]¶
A list of tags applied to this thread.
This is only available for threads in forum or media channels.
- Type:
List[
ForumTag]
- await archive(locked=Undefined.MISSING)¶
This function is a coroutine.
Archives the thread. This is a shorthand of
edit().
- can_send(*objects)¶
Returns a
boolindicating whether you have the permissions to send the object(s).
- property category: CategoryChannel | None¶
The category channel the parent channel belongs to, if applicable.
- Returns:
The parent channel’s category.
- Return type:
Optional[
CategoryChannel]- Raises:
ClientException – The parent channel was not cached and returned
None.
- property category_id: int | None¶
The category channel ID the parent channel belongs to, if applicable.
- Returns:
The parent channel’s category ID.
- Return type:
Optional[
int]- Raises:
ClientException – The parent channel was not cached and returned
None.
- await clone(*, name=None, reason=None)¶
This function is a coroutine.
Clones this channel. This creates a channel with the same properties as this channel.
You must have the
manage_channelspermission to do this.Added in version 1.1.
- Parameters:
- Returns:
The channel that was created.
- Return type:
- Raises:
Forbidden – You do not have the proper permissions to create this channel.
HTTPException – Creating the channel failed.
- await create_webhook(*, name, avatar=None, reason=None)¶
This function is a coroutine.
Creates a webhook for this channel.
Requires
manage_webhookspermissions.Changed in version 1.1: Added the
reasonkeyword-only parameter.- Parameters:
name (
str) – The webhook’s name.avatar (Optional[
bytes]) – A bytes-like object representing the webhook’s default avatar. This operates similarly toedit().reason (Optional[
str]) – The reason for creating this webhook. Shows up in the audit logs.
- Returns:
The created webhook.
- Return type:
Webhook- Raises:
HTTPException – Creating the webhook failed.
Forbidden – You do not have permissions to create a webhook.
- await delete()¶
This function is a coroutine.
Deletes this thread.
You must have
manage_threadsto delete threads.- Raises:
Forbidden – You do not have permissions to delete this thread.
HTTPException – Deleting the thread failed.
- await delete_messages(messages, *, reason=None)¶
This function is a coroutine.
Deletes a list of messages. This is similar to
Message.delete()except it bulk deletes multiple messages.As a special case, if the number of messages is 0, then nothing is done. If the number of messages is 1 then single message delete is done. If it’s more than two, then bulk delete is used.
You cannot bulk delete more than 100 messages or messages that are older than 14 days old.
You must have the
manage_messagespermission to use this.Usable only by bot accounts.
- Parameters:
messages (Iterable[
abc.Snowflake]) – An iterable of messages denoting which ones to bulk delete.reason (Optional[
str]) – The reason for deleting the messages. Shows up on the audit log.
- Raises:
ClientException – The number of messages to delete was more than 100.
Forbidden – You do not have proper permissions to delete the messages, or you’re not using a bot account.
NotFound – If single delete, then the message was already deleted.
HTTPException – Deleting the messages failed.
- Return type:
- await edit(*, name=Undefined.MISSING, archived=Undefined.MISSING, locked=Undefined.MISSING, invitable=Undefined.MISSING, slowmode_delay=Undefined.MISSING, auto_archive_duration=Undefined.MISSING, pinned=Undefined.MISSING, applied_tags=Undefined.MISSING, reason=None)¶
This function is a coroutine.
Edits the thread.
Editing the thread requires
Permissions.manage_threads. The thread creator can also editname,archivedorauto_archive_duration. Note that if the thread is locked then only those withPermissions.manage_threadscan send messages in it or unarchive a thread.The thread must be unarchived to be edited.
- Parameters:
name (
str) – The new name of the thread.archived (
bool) – Whether to archive the thread or not.locked (
bool) – Whether to lock the thread or not.invitable (
bool) – Whether non-moderators can add other non-moderators to this thread. Only available for private threads.auto_archive_duration (
int) – The new duration in minutes before a thread is automatically archived for inactivity. Must be one of60,1440,4320, or10080.ThreadArchiveDurationcan be used alternatively.slowmode_delay (
int) – Specifies the slowmode rate limit for user in this thread, in seconds. A value of0disables slowmode. The maximum value possible is21600.reason (Optional[
str]) – The reason for editing this thread. Shows up on the audit log.pinned (
bool) – Whether to pin the thread or not. This only works if the thread is part of a forum or media channel.applied_tags (List[
ForumTag]) –The set of tags to apply to the thread. Each tag object should have an ID set.
Added in version 2.3.
- Returns:
The newly edited thread.
- Return type:
Thread- Raises:
Forbidden – You do not have permissions to edit the thread.
HTTPException – Editing the thread failed.
- await fetch_members()¶
This function is a coroutine.
Retrieves all
ThreadMemberthat are in this thread.This requires
Intents.membersto get information about members other than yourself.- Returns:
All thread members in the thread.
- Return type:
List[
ThreadMember]- Raises:
HTTPException – Retrieving the members failed.
- await fetch_message(id, /)¶
This function is a coroutine.
Retrieves a single
Messagefrom the destination.- Parameters:
id (
int) – The message ID to look for.- Returns:
The message asked for.
- Return type:
- Raises:
NotFound – The specified message was not found.
Forbidden – You do not have the permissions required to get a message.
HTTPException – Retrieving the message failed.
- await follow(*, destination, reason=None)¶
Follows a channel using a webhook.
Only news channels can be followed.
Note
The webhook returned will not provide a token to do webhook actions, as Discord does not provide it.
Added in version 1.3.
- Parameters:
destination (
TextChannel) – The channel you would like to follow from.reason (Optional[
str]) –The reason for following the channel. Shows up on the destination guild’s audit log.
Added in version 1.4.
- Returns:
The created webhook.
- Return type:
Webhook- Raises:
HTTPException – Following the channel failed.
Forbidden – You do not have the permissions to create a webhook.
- await get_last_message()¶
Returns the last message from this thread in cache.
The message might not be valid or point to an existing message.
Reliable Fetching
For a slightly more reliable method of fetching the last message, consider using either
history()orfetch_message()with thelast_message_idattribute.- Returns:
The last message in this channel or
Noneif not found.- Return type:
Optional[
Message]
- await get_owner()¶
The member this thread belongs to.
- Return type:
Member | None
- get_partial_message(message_id, /)¶
Creates a
PartialMessagefrom the message ID.This is useful if you want to work with a message and only have its ID without doing an unnecessary API call.
Added in version 2.0.
- Parameters:
message_id (
int) – The message ID to create a partial message for.- Returns:
The partial message.
- Return type:
PartialMessage
- await get_starting_message()¶
Returns the message that started this thread.
The message might not be valid or point to an existing message.
Note
The ID for this message is the same as the thread ID.
- Returns:
The message that started this thread or
Noneif not found in the cache.- Return type:
Optional[
Message]
- history(*, limit=100, before=None, after=None, around=None, oldest_first=None)¶
Returns an
AsyncIteratorthat enables receiving the destination’s message history.You must have
read_message_historypermissions to use this.- Parameters:
limit (Optional[
int]) – The number of messages to retrieve. IfNone, retrieves every message in the channel. Note, however, that this would make it a slow operation.before (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages before this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.after (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages after this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.around (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages around this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time. When using this argument, the maximum limit is 101. Note that if the limit is an even number, then this will return at most limit + 1 messages.oldest_first (Optional[
bool]) – If set toTrue, return messages in oldest->newest order. Defaults toTrueifafteris specified, otherwiseFalse.
- Yields:
Message– The message with the message data parsed.- Raises:
Forbidden – You do not have permissions to get channel message history.
HTTPException – The request to get message history failed.
- Return type:
HistoryIterator
Examples
Usage
counter = 0 async for message in channel.history(limit=200): if message.author == client.user: counter += 1
Flattening into a list:
messages = await channel.history(limit=123).flatten() # messages is now a list of Message...
All parameters are optional.
- is_news()¶
Whether the thread is a news thread.
A news thread is a thread that has a parent that is a news channel, i.e.
TextChannel.is_news()isTrue.- Return type:
- is_nsfw()¶
Whether the thread is NSFW or not.
An NSFW thread is a thread that has a parent that is an NSFW channel, i.e.
TextChannel.is_nsfw()isTrue.- Return type:
- is_pinned()¶
Whether the thread is pinned to the top of its parent forum or media channel. :rtype:
boolAdded in version 2.3.
- is_private()¶
Whether the thread is a private thread.
A private thread is only viewable by those that have been explicitly invited or have
manage_threads.- Return type:
- await join()¶
This function is a coroutine.
Joins this thread.
You must have
send_messages_in_threadsto join a thread. If the thread is private,manage_threadsis also needed.- Raises:
Forbidden – You do not have permissions to join the thread.
HTTPException – Joining the thread failed.
- property jump_url: str¶
Returns a URL that allows the client to jump to the thread.
Added in version 2.0.
- await leave()¶
This function is a coroutine.
Leaves this thread.
- Raises:
HTTPException – Leaving the thread failed.
- property members: list[ThreadMember]¶
A list of thread members in this thread, including the bot if it is a member of this thread.
This requires
Intents.membersto be properly filled. Most of the time however, this data is not provided by the gateway and a call tofetch_members()is needed.
- property parent: TextChannel | ForumChannel | None¶
The parent channel this thread belongs to.
- permissions_for(obj, /)¶
Handles permission resolution for the
MemberorRole.Since threads do not have their own permissions, they inherit them from the parent channel. This is a convenience method for calling
permissions_for()on the parent channel.- Parameters:
obj (Union[
Member,Role]) – The object to resolve permissions for. This could be either a member or a role. If it’s a role then member overwrites are not computed.- Returns:
The resolved permissions for the member or role.
- Return type:
- Raises:
ClientException – The parent channel was not cached and returned
None
- pins(*, limit=50, before=None)¶
Returns a
MessagePinIteratorthat enables receiving the destination’s pinned messages.You must have
read_message_historypermissions to use this.Warning
Starting from version 3.0, await channel.pins() will no longer return a list of
Message. See examples below for new usage instead.- Parameters:
limit (Optional[
int]) – The number of pinned messages to retrieve. IfNone, retrieves every pinned message in the channel.before (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages pinned before this datetime. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.
- Yields:
MessagePin– The pinned message.- Raises:
Forbidden – You do not have permissions to get pinned messages.
HTTPException – The request to get pinned messages failed.
- Return type:
MessagePinIterator
Examples
Usage
counter = 0 async for pin in channel.pins(limit=250): if pin.message.author == client.user: counter += 1
Flattening into a list:
pins = await channel.pins(limit=None).flatten() # pins is now a list of MessagePin...
All parameters are optional.
- await purge(*, limit=100, check=Undefined.MISSING, before=None, after=None, around=None, oldest_first=False, bulk=True, reason=None)¶
This function is a coroutine.
Purges a list of messages that meet the criteria given by the predicate
check. If acheckis not provided then all messages are deleted without discrimination.You must have the
manage_messagespermission to delete messages even if they are your own (unless you are a user account). Theread_message_historypermission is also needed to retrieve message history.- Parameters:
limit (Optional[
int]) – The number of messages to search through. This is not the number of messages that will be deleted, though it can be.check (Callable[[
Message],bool]) – The function used to check if a message should be deleted. It must take aMessageas its sole parameter.before (Optional[Union[
abc.Snowflake,datetime.datetime]]) – Same asbeforeinhistory().after (Optional[Union[
abc.Snowflake,datetime.datetime]]) – Same asafterinhistory().around (Optional[Union[
abc.Snowflake,datetime.datetime]]) – Same asaroundinhistory().oldest_first (Optional[
bool]) – Same asoldest_firstinhistory().bulk (
bool) – IfTrue, use bulk delete. Setting this toFalseis useful for mass-deleting a bot’s own messages withoutPermissions.manage_messages. WhenTrue, will fall back to single delete if messages are older than two weeks.reason (Optional[
str]) – The reason for deleting the messages. Shows up on the audit log.
- Returns:
The list of messages that were deleted.
- Return type:
List[
Message]- Raises:
Forbidden – You do not have proper permissions to do the actions required.
HTTPException – Purging the messages failed.
Examples
Deleting bot’s messages
def is_me(m): return m.author == client.user deleted = await thread.purge(limit=100, check=is_me) await thread.send(f"Deleted {len(deleted)} message(s)")
- await remove_user(user)¶
This function is a coroutine.
Removes a user from this thread.
You must have
manage_threadsor be the creator of the thread to remove a user.- Parameters:
user (
abc.Snowflake) – The user to remove from the thread.- Raises:
Forbidden – You do not have permissions to remove the user from the thread.
HTTPException – Removing the user from the thread failed.
- await send(content=None, *, tts=None, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, enforce_nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None, poll=None, suppress=None, silent=None)¶
This function is a coroutine.
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through
str(content). If the content is set toNone(the default), then theembedparameter must be provided.To upload a single file, the
fileparameter should be used with a singleFileobject. To upload multiple files, thefilesparameter should be used with alistofFileobjects. Specifying both parameters will lead to an exception.To upload a single embed, the
embedparameter should be used with a singleEmbedobject. To upload multiple embeds, theembedsparameter should be used with alistofEmbedobjects. Specifying both parameters will lead to an exception.- Parameters:
content (Optional[
str]) – The content of the message to send.tts (
bool) – Indicates if the message should be sent using text-to-speech.embed (
Embed) – The rich embed for the content.file (
File) – The file to upload.files (List[
File]) – A list of files to upload. Must be a maximum of 10.nonce (Union[
str,int]) – The nonce to use for sending this message. If the message was successfully sent, then the message will have a nonce with this value.enforce_nonce (Optional[
bool]) –Whether
nonceis enforced to be validated.Added in version 2.5.
delete_after (
float) – If provided, the number of seconds to wait in the background before deleting the message we just sent. If the deletion fails, then it is silently ignored.allowed_mentions (
AllowedMentions) –Controls the mentions being processed in this message. If this is passed, then the object is merged with
allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set inallowed_mentions. If no object is passed at all then the defaults given byallowed_mentionsare used instead.Added in version 1.4.
reference (Union[
Message,MessageReference,PartialMessage]) –A reference to the
Messagebeing replied to or forwarded. This can be created usingto_reference(). When replying, you can control whether this mentions the author of the referenced message using thereplied_userattribute ofallowed_mentionsor by settingmention_author.Added in version 1.6.
mention_author (Optional[
bool]) –If set, overrides the
replied_userattribute ofallowed_mentions.Added in version 1.6.
view (
discord.ui.View) – A Discord UI View to add to the message.embeds (List[
Embed]) –A list of embeds to upload. Must be a maximum of 10.
Added in version 2.0.
stickers (Sequence[Union[
GuildSticker,StickerItem]]) –A list of stickers to upload. Must be a maximum of 3.
Added in version 2.0.
suppress (
bool) – Whether to suppress embeds for the message.silent (
bool) –Whether to suppress push and desktop notifications for the message.
Added in version 2.4.
poll (
Poll) –The poll to send.
Added in version 2.6.
- Returns:
The message that was sent.
- Return type:
- Raises:
HTTPException – Sending the message failed.
Forbidden – You do not have the proper permissions to send the message.
InvalidArgument – The
fileslist is not of the appropriate size, you specified bothfileandfiles, or you specified bothembedandembeds, or thereferenceobject is not aMessage,MessageReferenceorPartialMessage.
- await trigger_typing()¶
This function is a coroutine.
Triggers a typing indicator to the destination.
Typing indicator will go away after 10 seconds, or after a message is sent.
- Return type:
- property type: ChannelType¶
The channel’s Discord type.
- typing()¶
Returns a context manager that allows you to type for an indefinite period of time.
This is useful for denoting long computations in your bot. :rtype:
TypingNote
This is both a regular context manager and an async context manager. This means that both
withandasync withwork with this.Example Usage:
async with channel.typing(): # simulate something heavy await asyncio.sleep(10) await channel.send("done!")
- await unarchive()¶
This function is a coroutine.
Unarchives the thread. This is a shorthand of
edit().- Returns:
The updated thread.
- Return type:
- await webhooks()¶
This function is a coroutine.
Gets the list of webhooks from this channel.
Requires
manage_webhookspermissions.- Returns:
The webhooks for this channel.
- Return type:
List[
Webhook]- Raises:
Forbidden – You don’t have permissions to get the webhooks.
- class discord.events.ThreadJoin[source]¶
Called whenever the bot joins a thread.
Note that you can get the guild from
Thread.guild.This requires
Intents.guildsto be enabled.This event inherits from
Thread.- await add_user(user)¶
This function is a coroutine.
Adds a user to this thread.
You must have
send_messages_in_threadsto add a user to a public thread. If the thread is private andinvitableisFalse, thenmanage_threadsis required.- Parameters:
user (
abc.Snowflake) – The user to add to the thread.- Raises:
Forbidden – You do not have permissions to add the user to the thread.
HTTPException – Adding the user to the thread failed.
- property applied_tags: list[ForumTag]¶
A list of tags applied to this thread.
This is only available for threads in forum or media channels.
- Type:
List[
ForumTag]
- await archive(locked=Undefined.MISSING)¶
This function is a coroutine.
Archives the thread. This is a shorthand of
edit().
- can_send(*objects)¶
Returns a
boolindicating whether you have the permissions to send the object(s).
- property category: CategoryChannel | None¶
The category channel the parent channel belongs to, if applicable.
- Returns:
The parent channel’s category.
- Return type:
Optional[
CategoryChannel]- Raises:
ClientException – The parent channel was not cached and returned
None.
- property category_id: int | None¶
The category channel ID the parent channel belongs to, if applicable.
- Returns:
The parent channel’s category ID.
- Return type:
Optional[
int]- Raises:
ClientException – The parent channel was not cached and returned
None.
- await clone(*, name=None, reason=None)¶
This function is a coroutine.
Clones this channel. This creates a channel with the same properties as this channel.
You must have the
manage_channelspermission to do this.Added in version 1.1.
- Parameters:
- Returns:
The channel that was created.
- Return type:
- Raises:
Forbidden – You do not have the proper permissions to create this channel.
HTTPException – Creating the channel failed.
- await create_webhook(*, name, avatar=None, reason=None)¶
This function is a coroutine.
Creates a webhook for this channel.
Requires
manage_webhookspermissions.Changed in version 1.1: Added the
reasonkeyword-only parameter.- Parameters:
name (
str) – The webhook’s name.avatar (Optional[
bytes]) – A bytes-like object representing the webhook’s default avatar. This operates similarly toedit().reason (Optional[
str]) – The reason for creating this webhook. Shows up in the audit logs.
- Returns:
The created webhook.
- Return type:
Webhook- Raises:
HTTPException – Creating the webhook failed.
Forbidden – You do not have permissions to create a webhook.
- await delete()¶
This function is a coroutine.
Deletes this thread.
You must have
manage_threadsto delete threads.- Raises:
Forbidden – You do not have permissions to delete this thread.
HTTPException – Deleting the thread failed.
- await delete_messages(messages, *, reason=None)¶
This function is a coroutine.
Deletes a list of messages. This is similar to
Message.delete()except it bulk deletes multiple messages.As a special case, if the number of messages is 0, then nothing is done. If the number of messages is 1 then single message delete is done. If it’s more than two, then bulk delete is used.
You cannot bulk delete more than 100 messages or messages that are older than 14 days old.
You must have the
manage_messagespermission to use this.Usable only by bot accounts.
- Parameters:
messages (Iterable[
abc.Snowflake]) – An iterable of messages denoting which ones to bulk delete.reason (Optional[
str]) – The reason for deleting the messages. Shows up on the audit log.
- Raises:
ClientException – The number of messages to delete was more than 100.
Forbidden – You do not have proper permissions to delete the messages, or you’re not using a bot account.
NotFound – If single delete, then the message was already deleted.
HTTPException – Deleting the messages failed.
- Return type:
- await edit(*, name=Undefined.MISSING, archived=Undefined.MISSING, locked=Undefined.MISSING, invitable=Undefined.MISSING, slowmode_delay=Undefined.MISSING, auto_archive_duration=Undefined.MISSING, pinned=Undefined.MISSING, applied_tags=Undefined.MISSING, reason=None)¶
This function is a coroutine.
Edits the thread.
Editing the thread requires
Permissions.manage_threads. The thread creator can also editname,archivedorauto_archive_duration. Note that if the thread is locked then only those withPermissions.manage_threadscan send messages in it or unarchive a thread.The thread must be unarchived to be edited.
- Parameters:
name (
str) – The new name of the thread.archived (
bool) – Whether to archive the thread or not.locked (
bool) – Whether to lock the thread or not.invitable (
bool) – Whether non-moderators can add other non-moderators to this thread. Only available for private threads.auto_archive_duration (
int) – The new duration in minutes before a thread is automatically archived for inactivity. Must be one of60,1440,4320, or10080.ThreadArchiveDurationcan be used alternatively.slowmode_delay (
int) – Specifies the slowmode rate limit for user in this thread, in seconds. A value of0disables slowmode. The maximum value possible is21600.reason (Optional[
str]) – The reason for editing this thread. Shows up on the audit log.pinned (
bool) – Whether to pin the thread or not. This only works if the thread is part of a forum or media channel.applied_tags (List[
ForumTag]) –The set of tags to apply to the thread. Each tag object should have an ID set.
Added in version 2.3.
- Returns:
The newly edited thread.
- Return type:
Thread- Raises:
Forbidden – You do not have permissions to edit the thread.
HTTPException – Editing the thread failed.
- await fetch_members()¶
This function is a coroutine.
Retrieves all
ThreadMemberthat are in this thread.This requires
Intents.membersto get information about members other than yourself.- Returns:
All thread members in the thread.
- Return type:
List[
ThreadMember]- Raises:
HTTPException – Retrieving the members failed.
- await fetch_message(id, /)¶
This function is a coroutine.
Retrieves a single
Messagefrom the destination.- Parameters:
id (
int) – The message ID to look for.- Returns:
The message asked for.
- Return type:
- Raises:
NotFound – The specified message was not found.
Forbidden – You do not have the permissions required to get a message.
HTTPException – Retrieving the message failed.
- await follow(*, destination, reason=None)¶
Follows a channel using a webhook.
Only news channels can be followed.
Note
The webhook returned will not provide a token to do webhook actions, as Discord does not provide it.
Added in version 1.3.
- Parameters:
destination (
TextChannel) – The channel you would like to follow from.reason (Optional[
str]) –The reason for following the channel. Shows up on the destination guild’s audit log.
Added in version 1.4.
- Returns:
The created webhook.
- Return type:
Webhook- Raises:
HTTPException – Following the channel failed.
Forbidden – You do not have the permissions to create a webhook.
- await get_last_message()¶
Returns the last message from this thread in cache.
The message might not be valid or point to an existing message.
Reliable Fetching
For a slightly more reliable method of fetching the last message, consider using either
history()orfetch_message()with thelast_message_idattribute.- Returns:
The last message in this channel or
Noneif not found.- Return type:
Optional[
Message]
- await get_owner()¶
The member this thread belongs to.
- Return type:
Member | None
- get_partial_message(message_id, /)¶
Creates a
PartialMessagefrom the message ID.This is useful if you want to work with a message and only have its ID without doing an unnecessary API call.
Added in version 2.0.
- Parameters:
message_id (
int) – The message ID to create a partial message for.- Returns:
The partial message.
- Return type:
PartialMessage
- await get_starting_message()¶
Returns the message that started this thread.
The message might not be valid or point to an existing message.
Note
The ID for this message is the same as the thread ID.
- Returns:
The message that started this thread or
Noneif not found in the cache.- Return type:
Optional[
Message]
- history(*, limit=100, before=None, after=None, around=None, oldest_first=None)¶
Returns an
AsyncIteratorthat enables receiving the destination’s message history.You must have
read_message_historypermissions to use this.- Parameters:
limit (Optional[
int]) – The number of messages to retrieve. IfNone, retrieves every message in the channel. Note, however, that this would make it a slow operation.before (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages before this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.after (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages after this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.around (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages around this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time. When using this argument, the maximum limit is 101. Note that if the limit is an even number, then this will return at most limit + 1 messages.oldest_first (Optional[
bool]) – If set toTrue, return messages in oldest->newest order. Defaults toTrueifafteris specified, otherwiseFalse.
- Yields:
Message– The message with the message data parsed.- Raises:
Forbidden – You do not have permissions to get channel message history.
HTTPException – The request to get message history failed.
- Return type:
HistoryIterator
Examples
Usage
counter = 0 async for message in channel.history(limit=200): if message.author == client.user: counter += 1
Flattening into a list:
messages = await channel.history(limit=123).flatten() # messages is now a list of Message...
All parameters are optional.
- is_news()¶
Whether the thread is a news thread.
A news thread is a thread that has a parent that is a news channel, i.e.
TextChannel.is_news()isTrue.- Return type:
- is_nsfw()¶
Whether the thread is NSFW or not.
An NSFW thread is a thread that has a parent that is an NSFW channel, i.e.
TextChannel.is_nsfw()isTrue.- Return type:
- is_pinned()¶
Whether the thread is pinned to the top of its parent forum or media channel. :rtype:
boolAdded in version 2.3.
- is_private()¶
Whether the thread is a private thread.
A private thread is only viewable by those that have been explicitly invited or have
manage_threads.- Return type:
- await join()¶
This function is a coroutine.
Joins this thread.
You must have
send_messages_in_threadsto join a thread. If the thread is private,manage_threadsis also needed.- Raises:
Forbidden – You do not have permissions to join the thread.
HTTPException – Joining the thread failed.
- property jump_url: str¶
Returns a URL that allows the client to jump to the thread.
Added in version 2.0.
- await leave()¶
This function is a coroutine.
Leaves this thread.
- Raises:
HTTPException – Leaving the thread failed.
- property members: list[ThreadMember]¶
A list of thread members in this thread, including the bot if it is a member of this thread.
This requires
Intents.membersto be properly filled. Most of the time however, this data is not provided by the gateway and a call tofetch_members()is needed.
- property parent: TextChannel | ForumChannel | None¶
The parent channel this thread belongs to.
- permissions_for(obj, /)¶
Handles permission resolution for the
MemberorRole.Since threads do not have their own permissions, they inherit them from the parent channel. This is a convenience method for calling
permissions_for()on the parent channel.- Parameters:
obj (Union[
Member,Role]) – The object to resolve permissions for. This could be either a member or a role. If it’s a role then member overwrites are not computed.- Returns:
The resolved permissions for the member or role.
- Return type:
- Raises:
ClientException – The parent channel was not cached and returned
None
- pins(*, limit=50, before=None)¶
Returns a
MessagePinIteratorthat enables receiving the destination’s pinned messages.You must have
read_message_historypermissions to use this.Warning
Starting from version 3.0, await channel.pins() will no longer return a list of
Message. See examples below for new usage instead.- Parameters:
limit (Optional[
int]) – The number of pinned messages to retrieve. IfNone, retrieves every pinned message in the channel.before (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages pinned before this datetime. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.
- Yields:
MessagePin– The pinned message.- Raises:
Forbidden – You do not have permissions to get pinned messages.
HTTPException – The request to get pinned messages failed.
- Return type:
MessagePinIterator
Examples
Usage
counter = 0 async for pin in channel.pins(limit=250): if pin.message.author == client.user: counter += 1
Flattening into a list:
pins = await channel.pins(limit=None).flatten() # pins is now a list of MessagePin...
All parameters are optional.
- await purge(*, limit=100, check=Undefined.MISSING, before=None, after=None, around=None, oldest_first=False, bulk=True, reason=None)¶
This function is a coroutine.
Purges a list of messages that meet the criteria given by the predicate
check. If acheckis not provided then all messages are deleted without discrimination.You must have the
manage_messagespermission to delete messages even if they are your own (unless you are a user account). Theread_message_historypermission is also needed to retrieve message history.- Parameters:
limit (Optional[
int]) – The number of messages to search through. This is not the number of messages that will be deleted, though it can be.check (Callable[[
Message],bool]) – The function used to check if a message should be deleted. It must take aMessageas its sole parameter.before (Optional[Union[
abc.Snowflake,datetime.datetime]]) – Same asbeforeinhistory().after (Optional[Union[
abc.Snowflake,datetime.datetime]]) – Same asafterinhistory().around (Optional[Union[
abc.Snowflake,datetime.datetime]]) – Same asaroundinhistory().oldest_first (Optional[
bool]) – Same asoldest_firstinhistory().bulk (
bool) – IfTrue, use bulk delete. Setting this toFalseis useful for mass-deleting a bot’s own messages withoutPermissions.manage_messages. WhenTrue, will fall back to single delete if messages are older than two weeks.reason (Optional[
str]) – The reason for deleting the messages. Shows up on the audit log.
- Returns:
The list of messages that were deleted.
- Return type:
List[
Message]- Raises:
Forbidden – You do not have proper permissions to do the actions required.
HTTPException – Purging the messages failed.
Examples
Deleting bot’s messages
def is_me(m): return m.author == client.user deleted = await thread.purge(limit=100, check=is_me) await thread.send(f"Deleted {len(deleted)} message(s)")
- await remove_user(user)¶
This function is a coroutine.
Removes a user from this thread.
You must have
manage_threadsor be the creator of the thread to remove a user.- Parameters:
user (
abc.Snowflake) – The user to remove from the thread.- Raises:
Forbidden – You do not have permissions to remove the user from the thread.
HTTPException – Removing the user from the thread failed.
- await send(content=None, *, tts=None, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, enforce_nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None, poll=None, suppress=None, silent=None)¶
This function is a coroutine.
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through
str(content). If the content is set toNone(the default), then theembedparameter must be provided.To upload a single file, the
fileparameter should be used with a singleFileobject. To upload multiple files, thefilesparameter should be used with alistofFileobjects. Specifying both parameters will lead to an exception.To upload a single embed, the
embedparameter should be used with a singleEmbedobject. To upload multiple embeds, theembedsparameter should be used with alistofEmbedobjects. Specifying both parameters will lead to an exception.- Parameters:
content (Optional[
str]) – The content of the message to send.tts (
bool) – Indicates if the message should be sent using text-to-speech.embed (
Embed) – The rich embed for the content.file (
File) – The file to upload.files (List[
File]) – A list of files to upload. Must be a maximum of 10.nonce (Union[
str,int]) – The nonce to use for sending this message. If the message was successfully sent, then the message will have a nonce with this value.enforce_nonce (Optional[
bool]) –Whether
nonceis enforced to be validated.Added in version 2.5.
delete_after (
float) – If provided, the number of seconds to wait in the background before deleting the message we just sent. If the deletion fails, then it is silently ignored.allowed_mentions (
AllowedMentions) –Controls the mentions being processed in this message. If this is passed, then the object is merged with
allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set inallowed_mentions. If no object is passed at all then the defaults given byallowed_mentionsare used instead.Added in version 1.4.
reference (Union[
Message,MessageReference,PartialMessage]) –A reference to the
Messagebeing replied to or forwarded. This can be created usingto_reference(). When replying, you can control whether this mentions the author of the referenced message using thereplied_userattribute ofallowed_mentionsor by settingmention_author.Added in version 1.6.
mention_author (Optional[
bool]) –If set, overrides the
replied_userattribute ofallowed_mentions.Added in version 1.6.
view (
discord.ui.View) – A Discord UI View to add to the message.embeds (List[
Embed]) –A list of embeds to upload. Must be a maximum of 10.
Added in version 2.0.
stickers (Sequence[Union[
GuildSticker,StickerItem]]) –A list of stickers to upload. Must be a maximum of 3.
Added in version 2.0.
suppress (
bool) – Whether to suppress embeds for the message.silent (
bool) –Whether to suppress push and desktop notifications for the message.
Added in version 2.4.
poll (
Poll) –The poll to send.
Added in version 2.6.
- Returns:
The message that was sent.
- Return type:
- Raises:
HTTPException – Sending the message failed.
Forbidden – You do not have the proper permissions to send the message.
InvalidArgument – The
fileslist is not of the appropriate size, you specified bothfileandfiles, or you specified bothembedandembeds, or thereferenceobject is not aMessage,MessageReferenceorPartialMessage.
- await trigger_typing()¶
This function is a coroutine.
Triggers a typing indicator to the destination.
Typing indicator will go away after 10 seconds, or after a message is sent.
- Return type:
- property type: ChannelType¶
The channel’s Discord type.
- typing()¶
Returns a context manager that allows you to type for an indefinite period of time.
This is useful for denoting long computations in your bot. :rtype:
TypingNote
This is both a regular context manager and an async context manager. This means that both
withandasync withwork with this.Example Usage:
async with channel.typing(): # simulate something heavy await asyncio.sleep(10) await channel.send("done!")
- await unarchive()¶
This function is a coroutine.
Unarchives the thread. This is a shorthand of
edit().- Returns:
The updated thread.
- Return type:
- await webhooks()¶
This function is a coroutine.
Gets the list of webhooks from this channel.
Requires
manage_webhookspermissions.- Returns:
The webhooks for this channel.
- Return type:
List[
Webhook]- Raises:
Forbidden – You don’t have permissions to get the webhooks.
- class discord.events.ThreadRemove[source]¶
Called whenever a thread is removed.
This is different from a thread being deleted.
Note that you can get the guild from
Thread.guild.This requires
Intents.guildsto be enabled.Warning
Due to technical limitations, this event might not be called as soon as one expects. Since the library tracks thread membership locally, the API only sends updated thread membership status upon being synced by joining a thread.
This event inherits from
Thread.- await add_user(user)¶
This function is a coroutine.
Adds a user to this thread.
You must have
send_messages_in_threadsto add a user to a public thread. If the thread is private andinvitableisFalse, thenmanage_threadsis required.- Parameters:
user (
abc.Snowflake) – The user to add to the thread.- Raises:
Forbidden – You do not have permissions to add the user to the thread.
HTTPException – Adding the user to the thread failed.
- property applied_tags: list[ForumTag]¶
A list of tags applied to this thread.
This is only available for threads in forum or media channels.
- Type:
List[
ForumTag]
- await archive(locked=Undefined.MISSING)¶
This function is a coroutine.
Archives the thread. This is a shorthand of
edit().
- can_send(*objects)¶
Returns a
boolindicating whether you have the permissions to send the object(s).
- property category: CategoryChannel | None¶
The category channel the parent channel belongs to, if applicable.
- Returns:
The parent channel’s category.
- Return type:
Optional[
CategoryChannel]- Raises:
ClientException – The parent channel was not cached and returned
None.
- property category_id: int | None¶
The category channel ID the parent channel belongs to, if applicable.
- Returns:
The parent channel’s category ID.
- Return type:
Optional[
int]- Raises:
ClientException – The parent channel was not cached and returned
None.
- await clone(*, name=None, reason=None)¶
This function is a coroutine.
Clones this channel. This creates a channel with the same properties as this channel.
You must have the
manage_channelspermission to do this.Added in version 1.1.
- Parameters:
- Returns:
The channel that was created.
- Return type:
- Raises:
Forbidden – You do not have the proper permissions to create this channel.
HTTPException – Creating the channel failed.
- await create_webhook(*, name, avatar=None, reason=None)¶
This function is a coroutine.
Creates a webhook for this channel.
Requires
manage_webhookspermissions.Changed in version 1.1: Added the
reasonkeyword-only parameter.- Parameters:
name (
str) – The webhook’s name.avatar (Optional[
bytes]) – A bytes-like object representing the webhook’s default avatar. This operates similarly toedit().reason (Optional[
str]) – The reason for creating this webhook. Shows up in the audit logs.
- Returns:
The created webhook.
- Return type:
Webhook- Raises:
HTTPException – Creating the webhook failed.
Forbidden – You do not have permissions to create a webhook.
- await delete()¶
This function is a coroutine.
Deletes this thread.
You must have
manage_threadsto delete threads.- Raises:
Forbidden – You do not have permissions to delete this thread.
HTTPException – Deleting the thread failed.
- await delete_messages(messages, *, reason=None)¶
This function is a coroutine.
Deletes a list of messages. This is similar to
Message.delete()except it bulk deletes multiple messages.As a special case, if the number of messages is 0, then nothing is done. If the number of messages is 1 then single message delete is done. If it’s more than two, then bulk delete is used.
You cannot bulk delete more than 100 messages or messages that are older than 14 days old.
You must have the
manage_messagespermission to use this.Usable only by bot accounts.
- Parameters:
messages (Iterable[
abc.Snowflake]) – An iterable of messages denoting which ones to bulk delete.reason (Optional[
str]) – The reason for deleting the messages. Shows up on the audit log.
- Raises:
ClientException – The number of messages to delete was more than 100.
Forbidden – You do not have proper permissions to delete the messages, or you’re not using a bot account.
NotFound – If single delete, then the message was already deleted.
HTTPException – Deleting the messages failed.
- Return type:
- await edit(*, name=Undefined.MISSING, archived=Undefined.MISSING, locked=Undefined.MISSING, invitable=Undefined.MISSING, slowmode_delay=Undefined.MISSING, auto_archive_duration=Undefined.MISSING, pinned=Undefined.MISSING, applied_tags=Undefined.MISSING, reason=None)¶
This function is a coroutine.
Edits the thread.
Editing the thread requires
Permissions.manage_threads. The thread creator can also editname,archivedorauto_archive_duration. Note that if the thread is locked then only those withPermissions.manage_threadscan send messages in it or unarchive a thread.The thread must be unarchived to be edited.
- Parameters:
name (
str) – The new name of the thread.archived (
bool) – Whether to archive the thread or not.locked (
bool) – Whether to lock the thread or not.invitable (
bool) – Whether non-moderators can add other non-moderators to this thread. Only available for private threads.auto_archive_duration (
int) – The new duration in minutes before a thread is automatically archived for inactivity. Must be one of60,1440,4320, or10080.ThreadArchiveDurationcan be used alternatively.slowmode_delay (
int) – Specifies the slowmode rate limit for user in this thread, in seconds. A value of0disables slowmode. The maximum value possible is21600.reason (Optional[
str]) – The reason for editing this thread. Shows up on the audit log.pinned (
bool) – Whether to pin the thread or not. This only works if the thread is part of a forum or media channel.applied_tags (List[
ForumTag]) –The set of tags to apply to the thread. Each tag object should have an ID set.
Added in version 2.3.
- Returns:
The newly edited thread.
- Return type:
Thread- Raises:
Forbidden – You do not have permissions to edit the thread.
HTTPException – Editing the thread failed.
- await fetch_members()¶
This function is a coroutine.
Retrieves all
ThreadMemberthat are in this thread.This requires
Intents.membersto get information about members other than yourself.- Returns:
All thread members in the thread.
- Return type:
List[
ThreadMember]- Raises:
HTTPException – Retrieving the members failed.
- await fetch_message(id, /)¶
This function is a coroutine.
Retrieves a single
Messagefrom the destination.- Parameters:
id (
int) – The message ID to look for.- Returns:
The message asked for.
- Return type:
- Raises:
NotFound – The specified message was not found.
Forbidden – You do not have the permissions required to get a message.
HTTPException – Retrieving the message failed.
- await follow(*, destination, reason=None)¶
Follows a channel using a webhook.
Only news channels can be followed.
Note
The webhook returned will not provide a token to do webhook actions, as Discord does not provide it.
Added in version 1.3.
- Parameters:
destination (
TextChannel) – The channel you would like to follow from.reason (Optional[
str]) –The reason for following the channel. Shows up on the destination guild’s audit log.
Added in version 1.4.
- Returns:
The created webhook.
- Return type:
Webhook- Raises:
HTTPException – Following the channel failed.
Forbidden – You do not have the permissions to create a webhook.
- await get_last_message()¶
Returns the last message from this thread in cache.
The message might not be valid or point to an existing message.
Reliable Fetching
For a slightly more reliable method of fetching the last message, consider using either
history()orfetch_message()with thelast_message_idattribute.- Returns:
The last message in this channel or
Noneif not found.- Return type:
Optional[
Message]
- await get_owner()¶
The member this thread belongs to.
- Return type:
Member | None
- get_partial_message(message_id, /)¶
Creates a
PartialMessagefrom the message ID.This is useful if you want to work with a message and only have its ID without doing an unnecessary API call.
Added in version 2.0.
- Parameters:
message_id (
int) – The message ID to create a partial message for.- Returns:
The partial message.
- Return type:
PartialMessage
- await get_starting_message()¶
Returns the message that started this thread.
The message might not be valid or point to an existing message.
Note
The ID for this message is the same as the thread ID.
- Returns:
The message that started this thread or
Noneif not found in the cache.- Return type:
Optional[
Message]
- history(*, limit=100, before=None, after=None, around=None, oldest_first=None)¶
Returns an
AsyncIteratorthat enables receiving the destination’s message history.You must have
read_message_historypermissions to use this.- Parameters:
limit (Optional[
int]) – The number of messages to retrieve. IfNone, retrieves every message in the channel. Note, however, that this would make it a slow operation.before (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages before this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.after (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages after this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.around (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages around this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time. When using this argument, the maximum limit is 101. Note that if the limit is an even number, then this will return at most limit + 1 messages.oldest_first (Optional[
bool]) – If set toTrue, return messages in oldest->newest order. Defaults toTrueifafteris specified, otherwiseFalse.
- Yields:
Message– The message with the message data parsed.- Raises:
Forbidden – You do not have permissions to get channel message history.
HTTPException – The request to get message history failed.
- Return type:
HistoryIterator
Examples
Usage
counter = 0 async for message in channel.history(limit=200): if message.author == client.user: counter += 1
Flattening into a list:
messages = await channel.history(limit=123).flatten() # messages is now a list of Message...
All parameters are optional.
- is_news()¶
Whether the thread is a news thread.
A news thread is a thread that has a parent that is a news channel, i.e.
TextChannel.is_news()isTrue.- Return type:
- is_nsfw()¶
Whether the thread is NSFW or not.
An NSFW thread is a thread that has a parent that is an NSFW channel, i.e.
TextChannel.is_nsfw()isTrue.- Return type:
- is_pinned()¶
Whether the thread is pinned to the top of its parent forum or media channel. :rtype:
boolAdded in version 2.3.
- is_private()¶
Whether the thread is a private thread.
A private thread is only viewable by those that have been explicitly invited or have
manage_threads.- Return type:
- await join()¶
This function is a coroutine.
Joins this thread.
You must have
send_messages_in_threadsto join a thread. If the thread is private,manage_threadsis also needed.- Raises:
Forbidden – You do not have permissions to join the thread.
HTTPException – Joining the thread failed.
- property jump_url: str¶
Returns a URL that allows the client to jump to the thread.
Added in version 2.0.
- await leave()¶
This function is a coroutine.
Leaves this thread.
- Raises:
HTTPException – Leaving the thread failed.
- property members: list[ThreadMember]¶
A list of thread members in this thread, including the bot if it is a member of this thread.
This requires
Intents.membersto be properly filled. Most of the time however, this data is not provided by the gateway and a call tofetch_members()is needed.
- property parent: TextChannel | ForumChannel | None¶
The parent channel this thread belongs to.
- permissions_for(obj, /)¶
Handles permission resolution for the
MemberorRole.Since threads do not have their own permissions, they inherit them from the parent channel. This is a convenience method for calling
permissions_for()on the parent channel.- Parameters:
obj (Union[
Member,Role]) – The object to resolve permissions for. This could be either a member or a role. If it’s a role then member overwrites are not computed.- Returns:
The resolved permissions for the member or role.
- Return type:
- Raises:
ClientException – The parent channel was not cached and returned
None
- pins(*, limit=50, before=None)¶
Returns a
MessagePinIteratorthat enables receiving the destination’s pinned messages.You must have
read_message_historypermissions to use this.Warning
Starting from version 3.0, await channel.pins() will no longer return a list of
Message. See examples below for new usage instead.- Parameters:
limit (Optional[
int]) – The number of pinned messages to retrieve. IfNone, retrieves every pinned message in the channel.before (Optional[Union[
Snowflake,datetime.datetime]]) – Retrieve messages pinned before this datetime. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.
- Yields:
MessagePin– The pinned message.- Raises:
Forbidden – You do not have permissions to get pinned messages.
HTTPException – The request to get pinned messages failed.
- Return type:
MessagePinIterator
Examples
Usage
counter = 0 async for pin in channel.pins(limit=250): if pin.message.author == client.user: counter += 1
Flattening into a list:
pins = await channel.pins(limit=None).flatten() # pins is now a list of MessagePin...
All parameters are optional.
- await purge(*, limit=100, check=Undefined.MISSING, before=None, after=None, around=None, oldest_first=False, bulk=True, reason=None)¶
This function is a coroutine.
Purges a list of messages that meet the criteria given by the predicate
check. If acheckis not provided then all messages are deleted without discrimination.You must have the
manage_messagespermission to delete messages even if they are your own (unless you are a user account). Theread_message_historypermission is also needed to retrieve message history.- Parameters:
limit (Optional[
int]) – The number of messages to search through. This is not the number of messages that will be deleted, though it can be.check (Callable[[
Message],bool]) – The function used to check if a message should be deleted. It must take aMessageas its sole parameter.before (Optional[Union[
abc.Snowflake,datetime.datetime]]) – Same asbeforeinhistory().after (Optional[Union[
abc.Snowflake,datetime.datetime]]) – Same asafterinhistory().around (Optional[Union[
abc.Snowflake,datetime.datetime]]) – Same asaroundinhistory().oldest_first (Optional[
bool]) – Same asoldest_firstinhistory().bulk (
bool) – IfTrue, use bulk delete. Setting this toFalseis useful for mass-deleting a bot’s own messages withoutPermissions.manage_messages. WhenTrue, will fall back to single delete if messages are older than two weeks.reason (Optional[
str]) – The reason for deleting the messages. Shows up on the audit log.
- Returns:
The list of messages that were deleted.
- Return type:
List[
Message]- Raises:
Forbidden – You do not have proper permissions to do the actions required.
HTTPException – Purging the messages failed.
Examples
Deleting bot’s messages
def is_me(m): return m.author == client.user deleted = await thread.purge(limit=100, check=is_me) await thread.send(f"Deleted {len(deleted)} message(s)")
- await remove_user(user)¶
This function is a coroutine.
Removes a user from this thread.
You must have
manage_threadsor be the creator of the thread to remove a user.- Parameters:
user (
abc.Snowflake) – The user to remove from the thread.- Raises:
Forbidden – You do not have permissions to remove the user from the thread.
HTTPException – Removing the user from the thread failed.
- await send(content=None, *, tts=None, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, enforce_nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None, poll=None, suppress=None, silent=None)¶
This function is a coroutine.
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through
str(content). If the content is set toNone(the default), then theembedparameter must be provided.To upload a single file, the
fileparameter should be used with a singleFileobject. To upload multiple files, thefilesparameter should be used with alistofFileobjects. Specifying both parameters will lead to an exception.To upload a single embed, the
embedparameter should be used with a singleEmbedobject. To upload multiple embeds, theembedsparameter should be used with alistofEmbedobjects. Specifying both parameters will lead to an exception.- Parameters:
content (Optional[
str]) – The content of the message to send.tts (
bool) – Indicates if the message should be sent using text-to-speech.embed (
Embed) – The rich embed for the content.file (
File) – The file to upload.files (List[
File]) – A list of files to upload. Must be a maximum of 10.nonce (Union[
str,int]) – The nonce to use for sending this message. If the message was successfully sent, then the message will have a nonce with this value.enforce_nonce (Optional[
bool]) –Whether
nonceis enforced to be validated.Added in version 2.5.
delete_after (
float) – If provided, the number of seconds to wait in the background before deleting the message we just sent. If the deletion fails, then it is silently ignored.allowed_mentions (
AllowedMentions) –Controls the mentions being processed in this message. If this is passed, then the object is merged with
allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set inallowed_mentions. If no object is passed at all then the defaults given byallowed_mentionsare used instead.Added in version 1.4.
reference (Union[
Message,MessageReference,PartialMessage]) –A reference to the
Messagebeing replied to or forwarded. This can be created usingto_reference(). When replying, you can control whether this mentions the author of the referenced message using thereplied_userattribute ofallowed_mentionsor by settingmention_author.Added in version 1.6.
mention_author (Optional[
bool]) –If set, overrides the
replied_userattribute ofallowed_mentions.Added in version 1.6.
view (
discord.ui.View) – A Discord UI View to add to the message.embeds (List[
Embed]) –A list of embeds to upload. Must be a maximum of 10.
Added in version 2.0.
stickers (Sequence[Union[
GuildSticker,StickerItem]]) –A list of stickers to upload. Must be a maximum of 3.
Added in version 2.0.
suppress (
bool) – Whether to suppress embeds for the message.silent (
bool) –Whether to suppress push and desktop notifications for the message.
Added in version 2.4.
poll (
Poll) –The poll to send.
Added in version 2.6.
- Returns:
The message that was sent.
- Return type:
- Raises:
HTTPException – Sending the message failed.
Forbidden – You do not have the proper permissions to send the message.
InvalidArgument – The
fileslist is not of the appropriate size, you specified bothfileandfiles, or you specified bothembedandembeds, or thereferenceobject is not aMessage,MessageReferenceorPartialMessage.
- await trigger_typing()¶
This function is a coroutine.
Triggers a typing indicator to the destination.
Typing indicator will go away after 10 seconds, or after a message is sent.
- Return type:
- property type: ChannelType¶
The channel’s Discord type.
- typing()¶
Returns a context manager that allows you to type for an indefinite period of time.
This is useful for denoting long computations in your bot. :rtype:
TypingNote
This is both a regular context manager and an async context manager. This means that both
withandasync withwork with this.Example Usage:
async with channel.typing(): # simulate something heavy await asyncio.sleep(10) await channel.send("done!")
- await unarchive()¶
This function is a coroutine.
Unarchives the thread. This is a shorthand of
edit().- Returns:
The updated thread.
- Return type:
- await webhooks()¶
This function is a coroutine.
Gets the list of webhooks from this channel.
Requires
manage_webhookspermissions.- Returns:
The webhooks for this channel.
- Return type:
List[
Webhook]- Raises:
Forbidden – You don’t have permissions to get the webhooks.
- class discord.events.ThreadMemberJoin[source]¶
Called when a thread member joins a thread.
You can get the thread a member belongs in by accessing
ThreadMember.thread.This requires
Intents.membersto be enabled.This event inherits from
ThreadMember.
Typing¶
- class discord.events.TypingStart[source]¶
Called when someone begins typing a message.
The
channelcan be aabc.Messageableinstance, which could beTextChannel,GroupChannel, orDMChannel.If the
channelis aTextChannelthen theuseris aMember, otherwise it is aUser.This requires
Intents.typingto be enabled.- raw¶
The raw event payload data.
- Type:
RawTypingEvent
- channel¶
The location where the typing originated from.
- Type:
abc.Messageable
- user¶
The user that started typing.
- Type:
User|Member
- when¶
When the typing started as an aware datetime in UTC.
- Type:
Voice¶
- class discord.events.VoiceStateUpdate[source]¶
Called when a member changes their voice state.
The following, but not limited to, examples illustrate when this event is called: - A member joins a voice or stage channel. - A member leaves a voice or stage channel. - A member is muted or deafened by their own accord. - A member is muted or deafened by a guild administrator.
This requires
Intents.voice_statesto be enabled.- member¶
The member whose voice states changed.
- Type:
Member
- before¶
The voice state prior to the changes.
- Type:
VoiceState
- after¶
The voice state after the changes.
- Type:
VoiceState
- class discord.events.VoiceServerUpdate[source]¶
Called when the voice server is updated.
Note
This is an internal event used by the voice protocol. It is not dispatched to user code.
- class discord.events.VoiceChannelStatusUpdate[source]¶
Called when someone updates a voice channel status.
- raw¶
The raw voice channel status update payload.
- Type:
RawVoiceChannelStatusUpdateEvent
- channel¶
The channel where the voice channel status update originated from.
- Type:
VoiceChannel|StageChannel
- class discord.events.VoiceChannelEffectSend(*, animation_type, animation_id, sound, guild, user, channel, emoji)[source]¶
Called when a voice channel effect is sent.
- animation_type¶
The type of animation that is being sent.
- Type:
VoiceChannelEffectAnimationType
- sound¶
The sound that is being sent, could be
Noneif the effect is not a sound effect.- Type:
SoundboardSound|PartialSoundboardSound| None
- guild¶
The guild in which the sound is being sent.
- Type:
Guild
- user¶
The member that sent the sound.
- Type:
Member
- channel¶
The voice channel in which the sound is being sent.
- Type:
VoiceChannel|StageChannel
- emoji¶
The emoji associated with the effect, if any.
- Type:
PartialEmoji| None