Channels¶
This section documents everything related to channels and threads.
Discord Models¶
TextChannel¶
- defarchived_threads
- asyncclone
- asynccreate_invite
- asynccreate_thread
- asynccreate_webhook
- asyncdelete
- asyncdelete_messages
- asyncedit
- asyncfetch_message
- asyncfollow
- defget_partial_message
- defget_thread
- defhistory
- asyncinvites
- defis_news
- defis_nsfw
- asyncmove
- defoverwrites_for
- defpermissions_for
- defpins
- asyncpurge
- asyncsend
- asyncset_permissions
- asynctrigger_typing
- deftyping
- asyncwebhooks
- class disnake.TextChannel[source]¶
Represents a Discord guild text channel.
- x == y
Checks if two channels are equal.
- x != y
Checks if two channels are not equal.
- hash(x)
Returns the channel’s hash.
- str(x)
Returns the channel’s name.
- position¶
The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0.
- Type:
- last_message_id¶
The last message ID of the message sent to this channel. It may not point to an existing or valid message.
- slowmode_delay¶
The number of seconds a member must wait between sending messages in this channel.
A value of 0 denotes that it is disabled. Bots, and users with
manage_channelsormanage_messagespermissions, bypass slowmode.See also
default_thread_slowmode_delay.- Type:
- default_thread_slowmode_delay¶
The default number of seconds a member must wait between sending messages in newly created threads in this channel.
A value of
0denotes that it is disabled. Bots, and users withmanage_channelsormanage_messages, bypass slowmode.New in version 2.8.
- Type:
- nsfw¶
Whether the channel is marked as “not safe for work”.
Note
To check if the channel or the guild of that channel are marked as NSFW, consider
is_nsfw()instead.- Type:
- default_auto_archive_duration¶
The default auto archive duration in minutes for threads created in this channel.
New in version 2.0.
- Type:
- last_pin_timestamp¶
The time the most recent message was pinned, or
Noneif no message is currently pinned.New in version 2.5.
- Type:
- async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)[source]¶
Returns an
AsyncIteratorthat enables receiving the destination’s message history.You must have
Permissions.read_message_historypermission to use this.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.
- Parameters:
limit (
int|None) – The number of messages to retrieve. IfNone, retrieves every message in the channel. Note, however, that this would make it a slow operation.before (
abc.Snowflake|datetime.datetime|None) – 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 (
abc.Snowflake|datetime.datetime|None) – 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 (
abc.Snowflake|datetime.datetime|None) – 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 (
bool|None) – If set toTrue, return messages in oldest->newest order. Defaults toTrueifafteris specified, otherwiseFalse.
- Raises:
Forbidden – You do not have permissions to get channel message history.
HTTPException – The request to get message history failed.
- Yields:
Message– The message with the message data parsed.
- async with typing()[source]¶
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.
Note
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!')
- property type[source]¶
The channel’s Discord type.
This always returns
ChannelType.textorChannelType.news.- Type:
- permissions_for(obj, /, *, ignore_timeout=...)[source]¶
Handles permission resolution for the
MemberorRole.This function takes into consideration the following cases:
Guild owner
Guild roles
Channel overrides
Member overrides
Timeouts
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
Note
If the channel originated from an
Interactionand theguildattribute is unavailable, such as with user-installed applications in guilds, this method will not work due to an API limitation. Consider usingInteraction.permissionsorapp_permissionsinstead.Changed in version 2.0: The object passed in can now be a role object.
- Parameters:
obj (
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.ignore_timeout (
bool) –Whether or not to ignore the user’s timeout. Defaults to
False.New in version 2.4.
Note
This only applies to
Memberobjects.Changed in version 2.6: The default was changed to
False.
- Raises:
TypeError –
ignore_timeoutis only supported forMemberobjects.- Returns:
The resolved permissions for the member or role.
- Return type:
- property last_message[source]¶
Gets the last message in this channel from the 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.
- await edit(*, name=..., topic=..., position=..., nsfw=..., sync_permissions=..., category=..., slowmode_delay=..., default_thread_slowmode_delay=..., default_auto_archive_duration=..., type=..., overwrites=..., flags=..., reason=None, **kwargs)[source]¶
This function is a coroutine.
Edits the channel.
You must have
manage_channelspermission to do this.Changed in version 1.3: The
overwriteskeyword-only parameter was added.Changed in version 1.4: The
typekeyword-only parameter was added.Changed in version 2.0: Edits are no longer in-place, the newly edited channel is returned instead.
Changed in version 2.6: Raises
TypeErrororValueErrorinstead ofInvalidArgument.- Parameters:
name (
str) – The new channel’s name.position (
int) – The new channel’s position.nsfw (
bool) – Whether to mark the channel as NSFW.sync_permissions (
bool) – Whether to sync permissions with the channel’s new or pre-existing category. Defaults toFalse.category (
abc.Snowflake|None) – The new category for this channel. Can beNoneto remove the category.slowmode_delay (
int|None) – Specifies the slowmode rate limit for users in this channel, in seconds. A value of0disables slowmode. The maximum value possible is21600.default_thread_slowmode_delay (
int|None) –Specifies the slowmode rate limit at which users can send messages in newly created threads in this channel, in seconds. This does not apply retroactively to existing threads. A value of
0orNonedisables slowmode. The maximum value possible is21600.New in version 2.8.
type (
ChannelType) – The new type of this text channel. Currently, only conversion betweenChannelType.textandChannelType.newsis supported. This is only available to guilds that containNEWSinGuild.features.overwrites (
Mapping[Member|Role,PermissionOverwrite]) – AMappingof target (either a role or a member) toPermissionOverwriteto apply to the channel.default_auto_archive_duration (
int|ThreadArchiveDuration|None) – The new default auto archive duration in minutes for threads created in this channel. Must be one of60,1440,4320, or10080.flags (
ChannelFlags) –The new flags to set for this channel. This will overwrite any existing flags set on this channel.
New in version 2.6.
reason (
str|None) – The reason for editing this channel. Shows up on the audit log.
- Raises:
Forbidden – You do not have permissions to edit the channel.
HTTPException – Editing the channel failed.
TypeError – The permission overwrite information is not in proper form.
ValueError – The position is less than 0.
- Returns:
The newly edited text channel. If the edit was only positional then
Noneis returned instead.- Return type:
- await clone(*, name=None, topic=..., position=..., nsfw=..., category=..., slowmode_delay=..., default_thread_slowmode_delay=..., default_auto_archive_duration=..., overwrites=..., news=..., reason=None)[source]¶
This function is a coroutine.
Clones this channel. This creates a channel with the same properties as this channel.
You must have
Permissions.manage_channelspermission to do this.Changed in version 2.9: Added
topic,position,nsfw,category,slowmode_delay,default_thread_slowmode_delay,default_auto_archive_duration,newsandoverwriteskeyword-only parameters.Note
The current
TextChannel.flagsvalue won’t be cloned. This is a Discord limitation.- Parameters:
name (
str|None) – The name of the new channel. If not provided, defaults to this channel’s name.topic (
str|None) – The topic of the new channel. If not provided, defaults to this channel’s topic.position (
int) – The position of the new channel. If not provided, defaults to this channel’s position.nsfw (
bool) – Whether the new channel should be marked as NSFW. If not provided, defaults to this channel’s NSFW value.category (
abc.Snowflake|None) – The category where the new channel should be grouped. If not provided, defaults to this channel’s category.slowmode_delay (
int) – The slowmode of the new channel. If not provided, defaults to this channel’s slowmode.default_thread_slowmode_delay (
int|None) – Specifies the slowmode rate limit at which users can send messages in newly created threads in this channel, in seconds. This does not apply retroactively to existing threads. A value of0orNonedisables slowmode. The maximum value possible is21600. If not provided, defaults to this channel’s default thread slowmode delay.default_auto_archive_duration (
int|ThreadArchiveDuration) – The default auto archive duration of the new channel. If not provided, defaults to this channel’s default auto archive duration.overwrites (
Mapping[Member|Role,PermissionOverwrite]) – AMappingof target (either a role or a member) toPermissionOverwriteto apply to the channel. If not provided, defaults to this channel’s overwrites.news (
bool) – Whether the new channel should be a news channel. News channels are text channels that can be followed. This is only available to guilds that containNEWSinGuild.features. If not provided, defaults to the current type of this channel.reason (
str|None) – The reason for cloning this channel. Shows up on the audit log.
- Raises:
Forbidden – You do not have the proper permissions to create this channel.
HTTPException – Creating the channel failed.
- Returns:
The newly created text channel.
- Return type:
- await delete_messages(messages)[source]¶
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.
You must have
manage_messagespermission to do this.- Parameters:
messages (
Iterable[abc.Snowflake]) – An iterable of messages denoting which ones to bulk delete.- Raises:
ClientException – The number of messages to delete was more than 100.
Forbidden – You do not have proper permissions to delete the messages.
NotFound – If single delete, then the message was already deleted.
HTTPException – Deleting the messages failed.
- await purge(*, limit=100, check=..., before=None, after=None, around=None, oldest_first=False, bulk=True)[source]¶
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
manage_messagespermission to delete messages even if they are your own.read_message_historypermission is also needed to retrieve message history.Examples
Deleting bot’s messages
def is_me(m): return m.author == client.user deleted = await channel.purge(limit=100, check=is_me) await channel.send(f'Deleted {len(deleted)} message(s)')
- Parameters:
limit (
int|None) – 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 (
abc.Snowflake|datetime.datetime|None) – Same asbeforeinhistory().after (
abc.Snowflake|datetime.datetime|None) – Same asafterinhistory().around (
abc.Snowflake|datetime.datetime|None) – Same asaroundinhistory().oldest_first (
bool|None) – 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.
- Raises:
Forbidden – You do not have proper permissions to do the actions required.
HTTPException – Purging the messages failed.
- Returns:
A list of messages that were deleted.
- Return type:
- await webhooks()[source]¶
This function is a coroutine.
Retrieves the list of webhooks this channel has.
You must have
manage_webhookspermission to use this.
- await create_webhook(*, name, avatar=None, reason=None)[source]¶
This function is a coroutine.
Creates a webhook for this channel.
You must have
manage_webhookspermission to do this.Changed in version 1.1: The
reasonkeyword-only parameter was added.- Parameters:
name (
str) – The webhook’s name.avatar (
bytes|Asset|Emoji|PartialEmoji|StickerItem|Sticker|None) –The webhook’s default avatar. This operates similarly to
edit().Changed in version 2.5: Now accepts various resource types in addition to
bytes.reason (
str|None) – The reason for creating this webhook. Shows up in the audit logs.
- Raises:
NotFound – The
avatarasset couldn’t be found.Forbidden – You do not have permissions to create a webhook.
HTTPException – Creating the webhook failed.
TypeError – The
avatarasset is a lottie sticker (seeSticker.read()).
- Returns:
The newly created webhook.
- Return type:
- await follow(*, destination, reason=None)[source]¶
This function is a coroutine.
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.
New in version 1.3.
Changed in version 2.6: Raises
TypeErrorinstead ofInvalidArgument.- Parameters:
destination (
TextChannel) – The channel you would like to follow from.The reason for following the channel. Shows up on the destination guild’s audit log.
New in version 1.4.
- Raises:
HTTPException – Following the channel failed.
Forbidden – You do not have the permissions to create a webhook.
TypeError – The current or provided channel is not of the correct type.
- Returns:
The newly created webhook.
- Return type:
- get_partial_message(message_id, /)[source]¶
Creates a
PartialMessagefrom the given message ID.This is useful if you want to work with a message and only have its ID without doing an unnecessary API call.
New in version 1.6.
- Parameters:
message_id (
int) – The message ID to create a partial message for.- Returns:
The partial message object.
- Return type:
- await create_thread(*, name, message=None, auto_archive_duration=None, type=None, invitable=None, slowmode_delay=None, reason=None)[source]¶
This function is a coroutine.
Creates a thread in this text channel.
To create a public thread, you must have
create_public_threadspermission. For a private thread,create_private_threadspermission is needed instead.New in version 2.0.
Changed in version 2.5:
Only one of
messageandtypemay be provided.typeis now required ifmessageis not provided.
- Parameters:
name (
str) – The name of the thread.message (
abc.Snowflake) –A snowflake representing the message to create the thread with.
Changed in version 2.5: Cannot be provided with
type.type (
ChannelType) –The type of thread to create.
Changed in version 2.5: Cannot be provided with
message. Now required if message is not provided.auto_archive_duration (
int|ThreadArchiveDuration) – The duration in minutes before a thread is automatically archived for inactivity. If not provided, the channel’s default auto archive duration is used. Must be one of60,1440,4320, or10080.invitable (
bool) –Whether non-moderators can add other non-moderators to this thread. Only available for private threads. If a
messageis passed then this parameter is ignored, as a thread created with a message is always a public thread. Defaults toTrue.New in version 2.3.
Specifies the slowmode rate limit for users in this thread, in seconds. A value of
0disables slowmode. The maximum value possible is21600. If set toNoneor not provided, slowmode is inherited from the parent’sdefault_thread_slowmode_delay.New in version 2.3.
reason (
str|None) – The reason for creating the thread. Shows up on the audit log.
- Raises:
Forbidden – You do not have permissions to create a thread.
HTTPException – Starting the thread failed.
- Returns:
The newly created thread
- Return type:
- archived_threads(*, private=False, joined=False, limit=50, before=None)[source]¶
Returns an
AsyncIteratorthat iterates over all archived threads in the channel.You must have
read_message_historypermission to use this. If iterating over private threads thenmanage_threadspermission is also required.New in version 2.0.
- Parameters:
limit (
int|None) – The number of threads to retrieve. IfNone, retrieves every archived thread in the channel. Note, however, that this would make it a slow operation.before (
abc.Snowflake|datetime.datetime|None) – Retrieve archived channels before the given date or ID.private (
bool) – Whether to retrieve private archived threads.joined (
bool) – Whether to retrieve private archived threads that you’ve joined. You cannot setjoinedtoTrueandprivatetoFalse.
- Raises:
Forbidden – You do not have permissions to get archived threads.
HTTPException – The request to get the archived threads failed.
- Yields:
Thread– The archived threads.
- property category[source]¶
The category this channel belongs to.
If there is no category then this is
None.- Type:
- property changed_roles[source]¶
Returns a list of roles that have been overridden from their default values in the
Guild.rolesattribute.
- await create_invite(*, reason=None, max_age=0, max_uses=0, temporary=False, unique=True, target_type=None, target_user=None, target_application=None, guild_scheduled_event=None)[source]¶
This function is a coroutine.
Creates an instant invite from a text or voice channel.
You must have
Permissions.create_instant_invitepermission to do this.- Parameters:
max_age (
int) – How long the invite should last in seconds. If set to0, 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) – Whether the invite grants temporary membership (i.e. they get kicked after they disconnect). Defaults toFalse.unique (
bool) – Whether a unique invite URL should be created. Defaults toTrue. If this is set toFalsethen it will return a previously created invite.target_type (
InviteTarget|None) –The type of target for the voice channel invite, if any.
New in version 2.0.
The user whose stream to display for this invite, required if
target_typeisInviteTarget.stream. The user must be streaming in the channel.New in version 2.0.
target_application (
Snowflake|None) –The ID of the embedded application for the invite, required if
target_typeisInviteTarget.embedded_application.New in version 2.0.
Changed in version 2.9:
PartyTypeis deprecated, andSnowflakeshould be used instead.guild_scheduled_event (
GuildScheduledEvent|None) –The guild scheduled event to include with the invite.
New in version 2.3.
reason (
str|None) – The reason for creating this invite. Shows up on the audit log.
- Raises:
HTTPException – Invite creation failed.
NotFound – The channel that was passed is a category or an invalid channel.
- Returns:
The newly created invite.
- Return type:
- await delete(*, reason=None)[source]¶
This function is a coroutine.
Deletes the channel.
You must have
Permissions.manage_channelspermission to do this.- Parameters:
reason (
str|None) – 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.
- await fetch_message(id, /)[source]¶
This function is a coroutine.
Retrieves a single
Messagefrom the destination.- Parameters:
id (
int) – The message ID to look for.- 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.
- Returns:
The message asked for.
- Return type:
- await invites()[source]¶
This function is a coroutine.
Returns a list of all active instant invites from this channel.
You must have
Permissions.manage_channelspermission to use this.- Raises:
Forbidden – You do not have proper permissions to get the information.
HTTPException – An error occurred while fetching the information.
- Returns:
The list of invites that are currently active.
- Return type:
- property jump_url[source]¶
A URL that can be used to jump to this channel.
New in version 2.4.
Note
This exists for all guild channels but may not be usable by the client for all guild channel types.
- await move(**kwargs)[source]¶
This function is a coroutine.
A rich interface to help move a channel relative to other channels.
If exact position movement is required,
editshould be used instead.You must have
Permissions.manage_channelspermission to do this.Note
Voice channels will always be sorted below text channels. This is a Discord limitation.
New in version 1.7.
Changed in version 2.6: Raises
TypeErrororValueErrorinstead ofInvalidArgument.- Parameters:
beginning (
bool) – Whether to move the channel to the beginning of the channel list (or category if given). This is mutually exclusive withend,before, andafter.end (
bool) – Whether to move the channel to the end of the channel list (or category if given). This is mutually exclusive withbeginning,before, andafter.before (
abc.Snowflake) – The channel that should be before our current channel. This is mutually exclusive withbeginning,end, andafter.after (
abc.Snowflake) – The channel that should be after our current channel. This is mutually exclusive withbeginning,end, andbefore.offset (
int) – The number of channels to offset the move by. For example, an offset of2withbeginning=Truewould move it 2 after the beginning. A positive number moves it below while a negative number moves it above. Note that this number is relative and computed after thebeginning,end,before, andafterparameters.category (
abc.Snowflake|None) – The category to move this channel under. IfNoneis given then it moves it out of the category. This parameter is ignored if moving a category channel.sync_permissions (
bool) – Whether to sync the permissions with the category (if given).reason (
str|None) – The reason for moving this channel. Shows up on the audit log.
- Raises:
Forbidden – You do not have permissions to move the channel.
HTTPException – Moving the channel failed.
TypeError – A bad mix of arguments were passed.
ValueError – An invalid position was given.
- property overwrites[source]¶
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:
- overwrites_for(obj)[source]¶
Returns the channel-specific overwrites for a member or a role.
- property permissions_synced[source]¶
Whether or not the permissions for this channel are synced with the category it belongs to.
If there is no category then this is
False.New in version 1.3.
- Type:
- pins(*, limit=50, before=None)[source]¶
Returns an
AsyncIteratorthat enables receiving the destination’s pinned messages.You must have the
Permissions.read_message_historyandPermissions.view_channelpermissions to use this.Note
Due to a limitation with the Discord API, the
Messageobjects returned by this method do not contain completeMessage.reactionsdata.Changed in version 2.11: Now returns an
AsyncIteratorto support changes in Discord’s API.awaiting the result of this method remains supported, but only returns the last 50 pins and is deprecated in favor ofasync for msg in channel.pins().Examples
Usage
counter = 0 async for message in channel.pins(limit=100): if message.author == client.user: counter += 1
Flattening to a list
pinned_messages = await channel.pins(limit=100).flatten() # pinned_messages is now a list of Message...
All parameters are optional.
- Parameters:
limit (
int|None) – The number of pinned messages to retrieve. IfNone, retrieves every pinned message in the channel. Note, however, that this would make it a slow operation.before (
abc.Snowflake|datetime.datetime|None) – Retrieve messages pinned 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.
- Raises:
HTTPException – Retrieving the pinned messages failed.
- Yields:
Message– The pinned message from the parsed message data.
- await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, suppress_embeds=None, flags=None, allowed_mentions=None, reference=None, mention_author=None, view=None, components=None, poll=None)[source]¶
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).At least one of
content,embed/embeds,file/files,stickers,components,pollorviewmust 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.Changed in version 2.6: Raises
TypeErrororValueErrorinstead ofInvalidArgument.- Parameters:
tts (
bool) – Whether the message should be sent using text-to-speech.embed (
Embed) – The rich embed for the content to send. This cannot be mixed with theembedsparameter.A list of embeds to send with the content. Must be a maximum of 10. This cannot be mixed with the
embedparameter.New in version 2.0.
file (
File) – The file to upload. This cannot be mixed with thefilesparameter.files (
list[File]) – A list of files to upload. Must be a maximum of 10. This cannot be mixed with thefileparameter.stickers (
Sequence[GuildSticker|StandardSticker|StickerItem]) –A list of stickers to upload. Must be a maximum of 3.
New in version 2.0.
nonce (
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.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
Client.allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set inClient.allowed_mentions. If no object is passed at all then the defaults given byClient.allowed_mentionsare used instead.New in version 1.4.
reference (
Message|MessageReference|PartialMessage) –A reference to the
Messageto which you are replying, this can be created usingMessage.to_reference()or passed directly as aMessage. You can control whether this mentions the author of the referenced message using theAllowedMentions.replied_userattribute ofallowed_mentionsor by settingmention_author.New in version 1.6.
Note
Passing a
MessageorPartialMessagewill only allow replies. To forward a message you must explicitly transform the message to aMessageReferenceusingMessage.to_reference()and specify theMessageReferenceType, or useMessage.forward().mention_author (
bool|None) –If set, overrides the
AllowedMentions.replied_userattribute ofallowed_mentions.New in version 1.6.
view (
ui.View) –A Discord UI View to add to the message. This cannot be mixed with
components.New in version 2.0.
components (
UIComponent|list[UIComponent|list[WrappedComponent]]) –A list of components to include in the message. This cannot be mixed with
view.New in version 2.4.
Note
Passing v2 components here automatically sets the
is_components_v2flag. Setting this flag cannot be reverted. Note that this also disables thecontent,embeds,stickers, andpollfields.suppress_embeds (
bool) –Whether to suppress embeds for the message. This hides all the embeds from the UI if set to
True.New in version 2.5.
flags (
MessageFlags) –The flags to set for this message. Only
suppress_embeds,suppress_notifications, andis_components_v2are supported.If parameter
suppress_embedsis provided, that will override the setting ofMessageFlags.suppress_embeds.New in version 2.9.
poll (
Poll) –The poll to send with the message.
New in version 2.10.
- Raises:
HTTPException – Sending the message failed.
Forbidden – You do not have the proper permissions to send the message.
TypeError – Specified both
fileandfiles, or you specified bothembedandembeds, or you specified bothviewandcomponents, or thereferenceobject is not aMessage,MessageReferenceorPartialMessage.ValueError – The
filesorembedslist is too large, or you tried to send v2 components together withcontent,embeds,stickers, orpoll.
- Returns:
The message that was sent.
- Return type:
- await set_permissions(target, *, overwrite=..., reason=None, **permissions)[source]¶
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
Permissions.manage_rolespermission to do this.Note
This method replaces the old overwrites with the ones given.
Changed in version 2.6: Raises
TypeErrorinstead ofInvalidArgument.Examples
Setting allow and deny:
await message.channel.set_permissions(message.author, view_channel=True, send_messages=False)
Deleting overwrites
await channel.set_permissions(member, overwrite=None)
Using
PermissionOverwriteoverwrite = disnake.PermissionOverwrite() overwrite.send_messages = False overwrite.view_channel = True await channel.set_permissions(member, overwrite=overwrite)
- Parameters:
target (
Member|Role) – The member or role to overwrite permissions for.overwrite (
PermissionOverwrite|None) – The permissions to allow and deny to the target, orNoneto delete the overwrite.**permissions – A keyword argument list of permissions to set for ease of use. Cannot be mixed with
overwrite.reason (
str|None) – 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.
TypeError –
overwriteis invalid, the target type was notRoleorMember, both keyword arguments andoverwritewere provided, or invalid permissions were provided as keyword arguments.
VoiceChannel¶
- asyncclone
- asyncconnect
- asynccreate_invite
- asynccreate_webhook
- asyncdelete
- asyncdelete_messages
- asyncedit
- asyncfetch_message
- defget_partial_message
- defhistory
- asyncinvites
- defis_nsfw
- asyncmove
- defoverwrites_for
- defpermissions_for
- asyncpurge
- asyncsend
- asyncsend_soundboard_sound
- asyncset_permissions
- asynctrigger_typing
- deftyping
- asyncwebhooks
- class disnake.VoiceChannel[source]¶
Represents a Discord guild voice channel.
- x == y
Checks if two channels are equal.
- x != y
Checks if two channels are not equal.
- hash(x)
Returns the channel’s hash.
- str(x)
Returns the channel’s name.
- position¶
The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0.
- Type:
- rtc_region¶
The region for the voice channel’s voice communication. A value of
Noneindicates automatic voice region detection.New in version 1.7.
Changed in version 2.5: No longer a
VoiceRegioninstance.
- video_quality_mode¶
The camera video quality for the voice channel’s participants.
- Type:
- nsfw¶
Whether the channel is marked as “not safe for work”.
Note
To check if the channel or the guild of that channel are marked as NSFW, consider
is_nsfw()instead.New in version 2.3.
- Type:
- slowmode_delay¶
The number of seconds a member must wait between sending messages in this channel. A value of 0 denotes that it is disabled. Bots, and users with
manage_channelsormanage_messages, bypass slowmode.New in version 2.3.
- Type:
- last_message_id¶
The last message ID of the message sent to this channel. It may not point to an existing or valid message.
New in version 2.3.
- property type[source]¶
The channel’s Discord type.
This always returns
ChannelType.voice.- Type:
- await clone(*, name=None, bitrate=..., user_limit=..., position=..., category=..., rtc_region=..., video_quality_mode=..., nsfw=..., overwrites=..., slowmode_delay=..., reason=None)[source]¶
This function is a coroutine.
Clones this channel. This creates a channel with the same properties as this channel.
You must have
Permissions.manage_channelspermission to do this.Changed in version 2.9: Added
bitrate,user_limit,position,category,rtc_region,video_quality_mode,nsfw,slowmode_delayandoverwriteskeyword-only parameters.Note
The current
VoiceChannel.flagsvalue won’t be cloned. This is a Discord limitation.- Parameters:
name (
str|None) – The name of the new channel. If not provided, defaults to this channel’s name.bitrate (
int) – The bitrate of the new channel. If not provided, defaults to this channel’s bitrate.user_limit (
int) – The user limit of the new channel. If not provided, defaults to this channel’s user limit.position (
int) – The position of the new channel. If not provided, defaults to this channel’s position.category (
abc.Snowflake|None) – The category where the new channel should be grouped. If not provided, defaults to this channel’s category.rtc_region (
str|VoiceRegion|None) – The rtc region of the new channel. If not provided, defaults to this channel’s rtc region.video_quality_mode (
VideoQualityMode) – The video quality mode of the new channel. If not provided, defaults to this channel’s video quality mode.nsfw (
bool) – Whether the new channel should be nsfw or not. If not provided, defaults to this channel’s NSFW value.overwrites (
Mapping[Member|Role,PermissionOverwrite]) – AMappingof target (either a role or a member) toPermissionOverwriteto apply to the channel. If not provided, defaults to this channel’s overwrites.slowmode_delay (
int|None) – The slowmode of the new channel. If not provided, defaults to this channel’s slowmode.reason (
str|None) – The reason for cloning this channel. Shows up on the audit log.
- Raises:
Forbidden – You do not have the proper permissions to create this channel.
HTTPException – Creating the channel failed.
- Returns:
The channel that was created.
- Return type:
- property last_message[source]¶
Gets the last message in this channel from the 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.New in version 2.3.
- get_partial_message(message_id, /)[source]¶
Creates a
PartialMessagefrom the given message ID.This is useful if you want to work with a message and only have its ID without doing an unnecessary API call.
New in version 2.3.
- Parameters:
message_id (
int) – The message ID to create a partial message for.- Returns:
The partial message object.
- Return type:
- await edit(*, name=..., bitrate=..., user_limit=..., position=..., sync_permissions=..., category=..., overwrites=..., rtc_region=..., video_quality_mode=..., nsfw=..., slowmode_delay=..., flags=..., reason=None, **kwargs)[source]¶
This function is a coroutine.
Edits the channel.
You must have
manage_channelspermission to do this.Changed in version 1.3: The
overwriteskeyword-only parameter was added.Changed in version 2.0: Edits are no longer in-place, the newly edited channel is returned instead.
Changed in version 2.6: Raises
TypeErrororValueErrorinstead ofInvalidArgument.- Parameters:
name (
str) – The channel’s new name.bitrate (
int) – The channel’s new bitrate.user_limit (
int) – The channel’s new user limit.position (
int) – The channel’s new position.sync_permissions (
bool) – Whether to sync permissions with the channel’s new or pre-existing category. Defaults toFalse.category (
abc.Snowflake|None) – The new category for this channel. Can beNoneto remove the category.reason (
str|None) – The reason for editing this channel. Shows up on the audit log.overwrites (
Mapping[Member|Role,PermissionOverwrite]) – AMappingof target (either a role or a member) toPermissionOverwriteto apply to the channel.rtc_region (
str|VoiceRegion|None) –The new region for the voice channel’s voice communication. A value of
Noneindicates automatic voice region detection.New in version 1.7.
video_quality_mode (
VideoQualityMode) –The camera video quality for the voice channel’s participants.
New in version 2.0.
nsfw (
bool) –Whether to mark the channel as NSFW.
New in version 2.3.
Specifies the slowmode rate limit for users in this channel, in seconds. A value of
0disables slowmode. The maximum value possible is21600.New in version 2.3.
flags (
ChannelFlags) –The new flags to set for this channel. This will overwrite any existing flags set on this channel.
New in version 2.6.
- Raises:
Forbidden – You do not have permissions to edit the channel.
HTTPException – Editing the channel failed.
TypeError – The permission overwrite information is not in proper form.
ValueError – The position is less than 0.
- Returns:
The newly edited voice channel. If the edit was only positional then
Noneis returned instead.- Return type:
- await delete_messages(messages)[source]¶
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.
You must have
manage_messagespermission to do this.New in version 2.5.
- Parameters:
messages (
Iterable[abc.Snowflake]) – An iterable of messages denoting which ones to bulk delete.- Raises:
ClientException – The number of messages to delete was more than 100.
Forbidden – You do not have proper permissions to delete the messages.
NotFound – If single delete, then the message was already deleted.
HTTPException – Deleting the messages failed.
- await purge(*, limit=100, check=..., before=None, after=None, around=None, oldest_first=False, bulk=True)[source]¶
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
manage_messagespermission to delete messages even if they are your own.read_message_historypermission is also needed to retrieve message history.New in version 2.5.
Note
See
TextChannel.purge()for examples.- Parameters:
limit (
int|None) – 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 (
abc.Snowflake|datetime.datetime|None) – Same asbeforeinhistory().after (
abc.Snowflake|datetime.datetime|None) – Same asafterinhistory().around (
abc.Snowflake|datetime.datetime|None) – Same asaroundinhistory().oldest_first (
bool|None) – 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.
- Raises:
Forbidden – You do not have proper permissions to do the actions required.
HTTPException – Purging the messages failed.
- Returns:
A list of messages that were deleted.
- Return type:
- await webhooks()[source]¶
This function is a coroutine.
Retrieves the list of webhooks this channel has.
You must have
manage_webhookspermission to use this.New in version 2.5.
- await create_webhook(*, name, avatar=None, reason=None)[source]¶
This function is a coroutine.
Creates a webhook for this channel.
You must have
manage_webhookspermission to do this.New in version 2.5.
- Parameters:
- Raises:
NotFound – The
avatarasset couldn’t be found.Forbidden – You do not have permissions to create a webhook.
HTTPException – Creating the webhook failed.
TypeError – The
avatarasset is a lottie sticker (seeSticker.read()).
- Returns:
The newly created webhook.
- Return type:
- await send_soundboard_sound(sound, /)[source]¶
This function is a coroutine.
Sends a soundboard sound in this channel.
You must have
speakanduse_soundboardpermissions to do this. For sounds from different guilds, you must also haveuse_external_soundspermission. Additionally, you may not be muted or deafened.- Parameters:
sound (
SoundboardSound|GuildSoundboardSound) – The sound to send in the channel.- Raises:
Forbidden – You are not allowed to send soundboard sounds.
HTTPException – An error occurred sending the soundboard sound.
- property category[source]¶
The category this channel belongs to.
If there is no category then this is
None.- Type:
- property changed_roles[source]¶
Returns a list of roles that have been overridden from their default values in the
Guild.rolesattribute.
- await connect(*, timeout=60.0, reconnect=True, cls=<class 'disnake.voice_client.VoiceClient'>)[source]¶
This function is a coroutine.
Connects to voice and creates a
VoiceClientto establish your connection to the voice server.This requires
Intents.voice_states.- Parameters:
timeout (
float) – The timeout in seconds to wait for the voice endpoint.reconnect (
bool) – Whether the bot should automatically attempt a reconnect if a part of the handshake fails or the gateway goes down.cls (
type[VoiceProtocol]) – A type that subclassesVoiceProtocolto connect with. Defaults toVoiceClient.
- Raises:
asyncio.TimeoutError – Could not connect to the voice channel in time.
ClientException – You are already connected to a voice channel.
opus.OpusNotLoaded – The opus library has not been loaded.
- Returns:
A voice client that is fully connected to the voice server.
- Return type:
- await create_invite(*, reason=None, max_age=0, max_uses=0, temporary=False, unique=True, target_type=None, target_user=None, target_application=None, guild_scheduled_event=None)[source]¶
This function is a coroutine.
Creates an instant invite from a text or voice channel.
You must have
Permissions.create_instant_invitepermission to do this.- Parameters:
max_age (
int) – How long the invite should last in seconds. If set to0, 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) – Whether the invite grants temporary membership (i.e. they get kicked after they disconnect). Defaults toFalse.unique (
bool) – Whether a unique invite URL should be created. Defaults toTrue. If this is set toFalsethen it will return a previously created invite.target_type (
InviteTarget|None) –The type of target for the voice channel invite, if any.
New in version 2.0.
The user whose stream to display for this invite, required if
target_typeisInviteTarget.stream. The user must be streaming in the channel.New in version 2.0.
target_application (
Snowflake|None) –The ID of the embedded application for the invite, required if
target_typeisInviteTarget.embedded_application.New in version 2.0.
Changed in version 2.9:
PartyTypeis deprecated, andSnowflakeshould be used instead.guild_scheduled_event (
GuildScheduledEvent|None) –The guild scheduled event to include with the invite.
New in version 2.3.
reason (
str|None) – The reason for creating this invite. Shows up on the audit log.
- Raises:
HTTPException – Invite creation failed.
NotFound – The channel that was passed is a category or an invalid channel.
- Returns:
The newly created invite.
- Return type:
- await delete(*, reason=None)[source]¶
This function is a coroutine.
Deletes the channel.
You must have
Permissions.manage_channelspermission to do this.- Parameters:
reason (
str|None) – 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.
- await fetch_message(id, /)[source]¶
This function is a coroutine.
Retrieves a single
Messagefrom the destination.- Parameters:
id (
int) – The message ID to look for.- 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.
- Returns:
The message asked for.
- Return type:
- history(*, limit=100, before=None, after=None, around=None, oldest_first=None)[source]¶
Returns an
AsyncIteratorthat enables receiving the destination’s message history.You must have
Permissions.read_message_historypermission to use this.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.
- Parameters:
limit (
int|None) – The number of messages to retrieve. IfNone, retrieves every message in the channel. Note, however, that this would make it a slow operation.before (
abc.Snowflake|datetime.datetime|None) – 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 (
abc.Snowflake|datetime.datetime|None) – 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 (
abc.Snowflake|datetime.datetime|None) – 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 (
bool|None) – If set toTrue, return messages in oldest->newest order. Defaults toTrueifafteris specified, otherwiseFalse.
- Raises:
Forbidden – You do not have permissions to get channel message history.
HTTPException – The request to get message history failed.
- Yields:
Message– The message with the message data parsed.
- await invites()[source]¶
This function is a coroutine.
Returns a list of all active instant invites from this channel.
You must have
Permissions.manage_channelspermission to use this.- Raises:
Forbidden – You do not have proper permissions to get the information.
HTTPException – An error occurred while fetching the information.
- Returns:
The list of invites that are currently active.
- Return type:
- property jump_url[source]¶
A URL that can be used to jump to this channel.
New in version 2.4.
Note
This exists for all guild channels but may not be usable by the client for all guild channel types.
- await move(**kwargs)[source]¶
This function is a coroutine.
A rich interface to help move a channel relative to other channels.
If exact position movement is required,
editshould be used instead.You must have
Permissions.manage_channelspermission to do this.Note
Voice channels will always be sorted below text channels. This is a Discord limitation.
New in version 1.7.
Changed in version 2.6: Raises
TypeErrororValueErrorinstead ofInvalidArgument.- Parameters:
beginning (
bool) – Whether to move the channel to the beginning of the channel list (or category if given). This is mutually exclusive withend,before, andafter.end (
bool) – Whether to move the channel to the end of the channel list (or category if given). This is mutually exclusive withbeginning,before, andafter.before (
abc.Snowflake) – The channel that should be before our current channel. This is mutually exclusive withbeginning,end, andafter.after (
abc.Snowflake) – The channel that should be after our current channel. This is mutually exclusive withbeginning,end, andbefore.offset (
int) – The number of channels to offset the move by. For example, an offset of2withbeginning=Truewould move it 2 after the beginning. A positive number moves it below while a negative number moves it above. Note that this number is relative and computed after thebeginning,end,before, andafterparameters.category (
abc.Snowflake|None) – The category to move this channel under. IfNoneis given then it moves it out of the category. This parameter is ignored if moving a category channel.sync_permissions (
bool) – Whether to sync the permissions with the category (if given).reason (
str|None) – The reason for moving this channel. Shows up on the audit log.
- Raises:
Forbidden – You do not have permissions to move the channel.
HTTPException – Moving the channel failed.
TypeError – A bad mix of arguments were passed.
ValueError – An invalid position was given.
- property overwrites[source]¶
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:
- overwrites_for(obj)[source]¶
Returns the channel-specific overwrites for a member or a role.
- permissions_for(obj, /, *, ignore_timeout=...)[source]¶
Handles permission resolution for the
MemberorRole.This function takes into consideration the following cases:
Guild owner
Guild roles
Channel overrides
Member overrides
Timeouts
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
Note
If the channel originated from an
Interactionand theguildattribute is unavailable, such as with user-installed applications in guilds, this method will not work due to an API limitation. Consider usingInteraction.permissionsorapp_permissionsinstead.Changed in version 2.0: The object passed in can now be a role object.
- Parameters:
obj (
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.ignore_timeout (
bool) –Whether or not to ignore the user’s timeout. Defaults to
False.New in version 2.4.
Note
This only applies to
Memberobjects.Changed in version 2.6: The default was changed to
False.
- Raises:
TypeError –
ignore_timeoutis only supported forMemberobjects.- Returns:
The resolved permissions for the member or role.
- Return type:
- property permissions_synced[source]¶
Whether or not the permissions for this channel are synced with the category it belongs to.
If there is no category then this is
False.New in version 1.3.
- Type:
- await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, suppress_embeds=None, flags=None, allowed_mentions=None, reference=None, mention_author=None, view=None, components=None, poll=None)[source]¶
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).At least one of
content,embed/embeds,file/files,stickers,components,pollorviewmust 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.Changed in version 2.6: Raises
TypeErrororValueErrorinstead ofInvalidArgument.- Parameters:
tts (
bool) – Whether the message should be sent using text-to-speech.embed (
Embed) – The rich embed for the content to send. This cannot be mixed with theembedsparameter.A list of embeds to send with the content. Must be a maximum of 10. This cannot be mixed with the
embedparameter.New in version 2.0.
file (
File) – The file to upload. This cannot be mixed with thefilesparameter.files (
list[File]) – A list of files to upload. Must be a maximum of 10. This cannot be mixed with thefileparameter.stickers (
Sequence[GuildSticker|StandardSticker|StickerItem]) –A list of stickers to upload. Must be a maximum of 3.
New in version 2.0.
nonce (
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.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
Client.allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set inClient.allowed_mentions. If no object is passed at all then the defaults given byClient.allowed_mentionsare used instead.New in version 1.4.
reference (
Message|MessageReference|PartialMessage) –A reference to the
Messageto which you are replying, this can be created usingMessage.to_reference()or passed directly as aMessage. You can control whether this mentions the author of the referenced message using theAllowedMentions.replied_userattribute ofallowed_mentionsor by settingmention_author.New in version 1.6.
Note
Passing a
MessageorPartialMessagewill only allow replies. To forward a message you must explicitly transform the message to aMessageReferenceusingMessage.to_reference()and specify theMessageReferenceType, or useMessage.forward().mention_author (
bool|None) –If set, overrides the
AllowedMentions.replied_userattribute ofallowed_mentions.New in version 1.6.
view (
ui.View) –A Discord UI View to add to the message. This cannot be mixed with
components.New in version 2.0.
components (
UIComponent|list[UIComponent|list[WrappedComponent]]) –A list of components to include in the message. This cannot be mixed with
view.New in version 2.4.
Note
Passing v2 components here automatically sets the
is_components_v2flag. Setting this flag cannot be reverted. Note that this also disables thecontent,embeds,stickers, andpollfields.suppress_embeds (
bool) –Whether to suppress embeds for the message. This hides all the embeds from the UI if set to
True.New in version 2.5.
flags (
MessageFlags) –The flags to set for this message. Only
suppress_embeds,suppress_notifications, andis_components_v2are supported.If parameter
suppress_embedsis provided, that will override the setting ofMessageFlags.suppress_embeds.New in version 2.9.
poll (
Poll) –The poll to send with the message.
New in version 2.10.
- Raises:
HTTPException – Sending the message failed.
Forbidden – You do not have the proper permissions to send the message.
TypeError – Specified both
fileandfiles, or you specified bothembedandembeds, or you specified bothviewandcomponents, or thereferenceobject is not aMessage,MessageReferenceorPartialMessage.ValueError – The
filesorembedslist is too large, or you tried to send v2 components together withcontent,embeds,stickers, orpoll.
- Returns:
The message that was sent.
- Return type:
- await set_permissions(target, *, overwrite=..., reason=None, **permissions)[source]¶
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
Permissions.manage_rolespermission to do this.Note
This method replaces the old overwrites with the ones given.
Changed in version 2.6: Raises
TypeErrorinstead ofInvalidArgument.Examples
Setting allow and deny:
await message.channel.set_permissions(message.author, view_channel=True, send_messages=False)
Deleting overwrites
await channel.set_permissions(member, overwrite=None)
Using
PermissionOverwriteoverwrite = disnake.PermissionOverwrite() overwrite.send_messages = False overwrite.view_channel = True await channel.set_permissions(member, overwrite=overwrite)
- Parameters:
target (
Member|Role) – The member or role to overwrite permissions for.overwrite (
PermissionOverwrite|None) – The permissions to allow and deny to the target, orNoneto delete the overwrite.**permissions – A keyword argument list of permissions to set for ease of use. Cannot be mixed with
overwrite.reason (
str|None) – 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.
TypeError –
overwriteis invalid, the target type was notRoleorMember, both keyword arguments andoverwritewere provided, or invalid permissions were provided as keyword arguments.
- await trigger_typing()[source]¶
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.
- typing()[source]¶
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.
Note
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!')
CategoryChannel¶
- asyncclone
- asynccreate_forum_channel
- asynccreate_invite
- asynccreate_media_channel
- asynccreate_stage_channel
- asynccreate_text_channel
- asynccreate_voice_channel
- asyncdelete
- asyncedit
- asyncinvites
- defis_nsfw
- asyncmove
- defoverwrites_for
- defpermissions_for
- asyncset_permissions
- class disnake.CategoryChannel[source]¶
Represents a Discord channel category.
These are useful to group channels to logical compartments.
- x == y
Checks if two channels are equal.
- x != y
Checks if two channels are not equal.
- hash(x)
Returns the category’s hash.
- str(x)
Returns the category’s name.
- position¶
The position in the category list. This is a number that starts at 0. e.g. the top category is position 0.
- Type:
- nsfw¶
If the channel is marked as “not safe for work”.
Note
To check if the channel or the guild of that channel are marked as NSFW, consider
is_nsfw()instead.- Type:
- property type[source]¶
The channel’s Discord type.
This always returns
ChannelType.category.- Type:
- permissions_for(obj, /, *, ignore_timeout=...)[source]¶
Handles permission resolution for the
MemberorRole.This function takes into consideration the following cases:
Guild owner
Guild roles
Channel overrides
Member overrides
Timeouts
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
Note
If the channel originated from an
Interactionand theguildattribute is unavailable, such as with user-installed applications in guilds, this method will not work due to an API limitation. Consider usingInteraction.permissionsorapp_permissionsinstead.Changed in version 2.0: The object passed in can now be a role object.
- Parameters:
obj (
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.ignore_timeout (
bool) –Whether or not to ignore the user’s timeout. Defaults to
False.New in version 2.4.
Note
This only applies to
Memberobjects.Changed in version 2.6: The default was changed to
False.
- Raises:
TypeError –
ignore_timeoutis only supported forMemberobjects.- Returns:
The resolved permissions for the member or role.
- Return type:
- await clone(*, name=None, position=..., overwrites=..., reason=None)[source]¶
This function is a coroutine.
Clones this channel. This creates a channel with the same properties as this channel.
You must have
Permissions.manage_channelspermission to do this.Changed in version 2.9: Added
position,nsfwandoverwriteskeyword-only parameters.Note
The current
CategoryChannel.flagsvalue won’t be cloned. This is a Discord limitation.- Parameters:
name (
str|None) – The name of the new channel. If not provided, defaults to this channel’s name.position (
int) – The position of the new channel. If not provided, defaults to this channel’s position.overwrites (
Mapping[Member|Role,PermissionOverwrite]) – AMappingof target (either a role or a member) toPermissionOverwriteto apply to the channel. If not provided, defaults to this channel’s overwrites.reason (
str|None) – The reason for cloning this channel. Shows up on the audit log.
- Raises:
Forbidden – You do not have the proper permissions to create this channel.
HTTPException – Creating the channel failed.
- Returns:
The channel that was created.
- Return type:
- await edit(*, name=..., position=..., nsfw=..., overwrites=..., flags=..., reason=None, **kwargs)[source]¶
This function is a coroutine.
Edits the category.
You must have
manage_channelspermission to do this.Changed in version 1.3: The
overwriteskeyword-only parameter was added.Changed in version 2.0: Edits are no longer in-place, the newly edited channel is returned instead.
Changed in version 2.6: Raises
TypeErrororValueErrorinstead ofInvalidArgument.- Parameters:
name (
str) – The new category’s name.position (
int) – The new category’s position.nsfw (
bool) – Whether to mark the category as NSFW.overwrites (
Mapping[Member|Role,PermissionOverwrite]) – AMappingof target (either a role or a member) toPermissionOverwriteto apply to the category.flags (
ChannelFlags) –The new flags to set for this channel. This will overwrite any existing flags set on this channel.
New in version 2.6.
reason (
str|None) – The reason for editing this category. Shows up on the audit log.
- Raises:
Forbidden – You do not have permissions to edit the category.
HTTPException – Editing the category failed.
TypeError – The permission overwrite information is not in proper form.
ValueError – The position is less than 0.
- Returns:
The newly edited category channel. If the edit was only positional then
Noneis returned instead.- Return type:
- await move(**kwargs)[source]¶
This function is a coroutine.
A rich interface to help move a channel relative to other channels.
If exact position movement is required,
editshould be used instead.You must have
Permissions.manage_channelspermission to do this.Note
Voice channels will always be sorted below text channels. This is a Discord limitation.
New in version 1.7.
Changed in version 2.6: Raises
TypeErrororValueErrorinstead ofInvalidArgument.- Parameters:
beginning (
bool) – Whether to move the channel to the beginning of the channel list (or category if given). This is mutually exclusive withend,before, andafter.end (
bool) – Whether to move the channel to the end of the channel list (or category if given). This is mutually exclusive withbeginning,before, andafter.before (
abc.Snowflake) – The channel that should be before our current channel. This is mutually exclusive withbeginning,end, andafter.after (
abc.Snowflake) – The channel that should be after our current channel. This is mutually exclusive withbeginning,end, andbefore.offset (
int) – The number of channels to offset the move by. For example, an offset of2withbeginning=Truewould move it 2 after the beginning. A positive number moves it below while a negative number moves it above. Note that this number is relative and computed after thebeginning,end,before, andafterparameters.category (
abc.Snowflake|None) – The category to move this channel under. IfNoneis given then it moves it out of the category. This parameter is ignored if moving a category channel.sync_permissions (
bool) – Whether to sync the permissions with the category (if given).reason (
str|None) – The reason for moving this channel. Shows up on the audit log.
- Raises:
Forbidden – You do not have permissions to move the channel.
HTTPException – Moving the channel failed.
TypeError – A bad mix of arguments were passed.
ValueError – An invalid position was given.
- property channels[source]¶
Returns the channels that are under this category.
These are sorted by the official Discord UI, which places voice channels below the text channels.
- Type:
- property stage_channels[source]¶
Returns the stage channels that are under this category.
New in version 1.7.
- Type:
- property forum_channels[source]¶
Returns the forum channels that are under this category.
New in version 2.5.
- Type:
- property media_channels[source]¶
Returns the media channels that are under this category.
New in version 2.10.
- Type:
- await create_text_channel(name, **options)[source]¶
This function is a coroutine.
A shortcut method to
Guild.create_text_channel()to create aTextChannelin the category.- Returns:
The newly created text channel.
- Return type:
- await create_voice_channel(name, **options)[source]¶
This function is a coroutine.
A shortcut method to
Guild.create_voice_channel()to create aVoiceChannelin the category.- Returns:
The newly created voice channel.
- Return type:
- await create_stage_channel(name, **options)[source]¶
This function is a coroutine.
A shortcut method to
Guild.create_stage_channel()to create aStageChannelin the category.New in version 1.7.
- Returns:
The newly created stage channel.
- Return type:
- await create_forum_channel(name, **options)[source]¶
This function is a coroutine.
A shortcut method to
Guild.create_forum_channel()to create aForumChannelin the category.New in version 2.5.
- Returns:
The newly created forum channel.
- Return type:
- await create_media_channel(name, **options)[source]¶
This function is a coroutine.
A shortcut method to
Guild.create_media_channel()to create aMediaChannelin the category.New in version 2.10.
- Returns:
The newly created media channel.
- Return type:
- property category[source]¶
The category this channel belongs to.
If there is no category then this is
None.- Type:
- property changed_roles[source]¶
Returns a list of roles that have been overridden from their default values in the
Guild.rolesattribute.
- await create_invite(*, reason=None, max_age=0, max_uses=0, temporary=False, unique=True, target_type=None, target_user=None, target_application=None, guild_scheduled_event=None)[source]¶
This function is a coroutine.
Creates an instant invite from a text or voice channel.
You must have
Permissions.create_instant_invitepermission to do this.- Parameters:
max_age (
int) – How long the invite should last in seconds. If set to0, 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) – Whether the invite grants temporary membership (i.e. they get kicked after they disconnect). Defaults toFalse.unique (
bool) – Whether a unique invite URL should be created. Defaults toTrue. If this is set toFalsethen it will return a previously created invite.target_type (
InviteTarget|None) –The type of target for the voice channel invite, if any.
New in version 2.0.
The user whose stream to display for this invite, required if
target_typeisInviteTarget.stream. The user must be streaming in the channel.New in version 2.0.
target_application (
Snowflake|None) –The ID of the embedded application for the invite, required if
target_typeisInviteTarget.embedded_application.New in version 2.0.
Changed in version 2.9:
PartyTypeis deprecated, andSnowflakeshould be used instead.guild_scheduled_event (
GuildScheduledEvent|None) –The guild scheduled event to include with the invite.
New in version 2.3.
reason (
str|None) – The reason for creating this invite. Shows up on the audit log.
- Raises:
HTTPException – Invite creation failed.
NotFound – The channel that was passed is a category or an invalid channel.
- Returns:
The newly created invite.
- Return type:
- await delete(*, reason=None)[source]¶
This function is a coroutine.
Deletes the channel.
You must have
Permissions.manage_channelspermission to do this.- Parameters:
reason (
str|None) – 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.
- await invites()[source]¶
This function is a coroutine.
Returns a list of all active instant invites from this channel.
You must have
Permissions.manage_channelspermission to use this.- Raises:
Forbidden – You do not have proper permissions to get the information.
HTTPException – An error occurred while fetching the information.
- Returns:
The list of invites that are currently active.
- Return type:
- property jump_url[source]¶
A URL that can be used to jump to this channel.
New in version 2.4.
Note
This exists for all guild channels but may not be usable by the client for all guild channel types.
- property overwrites[source]¶
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:
- overwrites_for(obj)[source]¶
Returns the channel-specific overwrites for a member or a role.
- property permissions_synced[source]¶
Whether or not the permissions for this channel are synced with the category it belongs to.
If there is no category then this is
False.New in version 1.3.
- Type:
- await set_permissions(target, *, overwrite=..., reason=None, **permissions)[source]¶
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
Permissions.manage_rolespermission to do this.Note
This method replaces the old overwrites with the ones given.
Changed in version 2.6: Raises
TypeErrorinstead ofInvalidArgument.Examples
Setting allow and deny:
await message.channel.set_permissions(message.author, view_channel=True, send_messages=False)
Deleting overwrites
await channel.set_permissions(member, overwrite=None)
Using
PermissionOverwriteoverwrite = disnake.PermissionOverwrite() overwrite.send_messages = False overwrite.view_channel = True await channel.set_permissions(member, overwrite=overwrite)
- Parameters:
target (
Member|Role) – The member or role to overwrite permissions for.overwrite (
PermissionOverwrite|None) – The permissions to allow and deny to the target, orNoneto delete the overwrite.**permissions – A keyword argument list of permissions to set for ease of use. Cannot be mixed with
overwrite.reason (
str|None) – 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.
TypeError –
overwriteis invalid, the target type was notRoleorMember, both keyword arguments andoverwritewere provided, or invalid permissions were provided as keyword arguments.
Thread¶
- applied_tags
- archive_timestamp
- archived
- auto_archive_duration
- category
- category_id
- create_timestamp
- created_at
- flags
- guild
- id
- invitable
- jump_url
- last_message
- last_message_id
- last_pin_timestamp
- locked
- me
- member_count
- members
- mention
- message_count
- name
- owner
- owner_id
- parent
- parent_id
- slowmode_delay
- total_message_sent
- type
- asyncadd_tags
- asyncadd_user
- asyncdelete
- asyncdelete_messages
- asyncedit
- asyncfetch_member
- asyncfetch_members
- asyncfetch_message
- defget_partial_message
- defhistory
- defis_news
- defis_nsfw
- defis_pinned
- defis_private
- asyncjoin
- asyncleave
- defpermissions_for
- defpins
- asyncpurge
- asyncremove_tags
- asyncremove_user
- asyncsend
- asynctrigger_typing
- deftyping
- class disnake.Thread[source]¶
Represents a Discord thread.
- x == y
Checks if two threads are equal.
- x != y
Checks if two threads are not equal.
- hash(x)
Returns the thread’s hash.
- str(x)
Returns the thread’s name.
New in version 2.0.
- parent_id¶
The parent
TextChannel,ForumChannel, orMediaChannelID this thread belongs to.- Type:
- last_message_id¶
The last message ID of the message sent to this thread. It may not point to an existing or valid message.
- slowmode_delay¶
The number of seconds a member must wait between sending messages in this thread. A value of 0 denotes that it is disabled. Bots, and users with
manage_channelsormanage_messages, bypass slowmode.- Type:
- message_count¶
An approximate number of messages in this thread.
Note
If the thread was created before July 1, 2022, this could be inaccurate.
- total_message_sent¶
The total number of messages sent in the thread, including deleted messages.
New in version 2.6.
Note
If the thread was created before July 1, 2022, this could be inaccurate.
- me¶
A thread member representing yourself, if you’ve joined the thread. This could not be available.
- Type:
- invitable¶
Whether non-moderators can add other non-moderators to this thread. This is always
Truefor public threads.- Type:
- auto_archive_duration¶
The duration in minutes until the thread is automatically archived due to inactivity. Usually a value of 60, 1440, 4320 and 10080.
- Type:
- archive_timestamp¶
An aware timestamp of when the thread’s archived status was last updated in UTC.
- Type:
- create_timestamp¶
An aware timestamp of when the thread was created in UTC. This is only available for threads created after 2022-01-09.
New in version 2.4.
- Type:
- last_pin_timestamp¶
The time the most recent message was pinned, or
Noneif no message is currently pinned.New in version 2.5.
- Type:
- async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)[source]¶
Returns an
AsyncIteratorthat enables receiving the destination’s message history.You must have
Permissions.read_message_historypermission to use this.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.
- Parameters:
limit (
int|None) – The number of messages to retrieve. IfNone, retrieves every message in the channel. Note, however, that this would make it a slow operation.before (
abc.Snowflake|datetime.datetime|None) – 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 (
abc.Snowflake|datetime.datetime|None) – 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 (
abc.Snowflake|datetime.datetime|None) – 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 (
bool|None) – If set toTrue, return messages in oldest->newest order. Defaults toTrueifafteris specified, otherwiseFalse.
- Raises:
Forbidden – You do not have permissions to get channel message history.
HTTPException – The request to get message history failed.
- Yields:
Message– The message with the message data parsed.
- async with typing()[source]¶
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.
Note
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!')
- property type[source]¶
The channel’s Discord type.
This always returns
ChannelType.public_thread,ChannelType.private_thread, orChannelType.news_thread.- Type:
- property members[source]¶
A list of thread members in 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.- Type:
- property last_message[source]¶
Gets the last message in this channel from the 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.
- property category[source]¶
The category channel the parent channel belongs to, if applicable.
- Raises:
ClientException – The parent channel was not cached and returned
None.- Returns:
The parent channel’s category.
- Return type:
- property category_id[source]¶
The category channel ID the parent channel belongs to, if applicable.
- Raises:
ClientException – The parent channel was not cached and returned
None.- Returns:
The parent channel’s category ID.
- Return type:
- property created_at[source]¶
Returns the thread’s creation time in UTC.
Changed in version 2.4: If
create_timestampis provided by Discord, that will be used instead of the time in the ID.- Type:
- is_private()[source]¶
Whether the thread is a private thread.
A private thread is only viewable by those that have been explicitly invited or have
manage_threadspermissions.- Return type:
- is_news()[source]¶
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()[source]¶
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()[source]¶
Whether the thread is pinned in a
ForumChannelorMediaChannel.Pinned threads are not affected by the auto archive duration.
This is a shortcut to
self.flags.pinned.New in version 2.5.
- Return type:
- property applied_tags[source]¶
The tags currently applied to this thread. Only applicable to threads in channels of type
ForumChannelorMediaChannel.New in version 2.6.
- permissions_for(obj, /, *, ignore_timeout=...)[source]¶
Handles permission resolution for the
MemberorRole.Since threads do not have their own permissions, they inherit them from the parent channel. However, the permission context is different compared to a normal channel, so this method has different behavior than calling the parent’s
GuildChannel.permissions_formethod directly.Note
If the thread originated from an
Interactionand theguildattribute is unavailable, such as with user-installed applications in guilds, this method will not work due to an API limitation. Consider usingInteraction.permissionsorapp_permissionsinstead.Changed in version 2.9: Properly takes
Permissions.send_messages_in_threadsinto consideration.- Parameters:
obj (
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.ignore_timeout (
bool) –Whether or not to ignore the user’s timeout. Defaults to
False.New in version 2.4.
Note
This only applies to
Memberobjects.Changed in version 2.6: The default was changed to
False.
- Raises:
ClientException – The parent channel was not cached and returned
None- Returns:
The resolved permissions for the member or role.
- Return type:
- await delete_messages(messages)[source]¶
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.- 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.
- await purge(*, limit=100, check=..., before=None, after=None, around=None, oldest_first=False, bulk=True)[source]¶
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.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)')
- Parameters:
limit (
int|None) – 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 (
abc.Snowflake|datetime.datetime|None) – Same asbeforeinhistory().after (
abc.Snowflake|datetime.datetime|None) – Same asafterinhistory().around (
abc.Snowflake|datetime.datetime|None) – Same asaroundinhistory().oldest_first (
bool|None) – 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.
- Raises:
Forbidden – You do not have proper permissions to do the actions required.
HTTPException – Purging the messages failed.
- Returns:
The list of messages that were deleted.
- Return type:
- await edit(*, name=..., archived=..., locked=..., invitable=..., slowmode_delay=..., auto_archive_duration=..., pinned=..., flags=..., applied_tags=..., reason=None)[source]¶
This function is a coroutine.
Edits the thread.
Editing the thread requires
Permissions.manage_threads. The thread creator can also editname,archived,auto_archive_durationandapplied_tags. Note that if the thread is locked then only those withPermissions.manage_threadscan 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|ThreadArchiveDuration) – The new duration in minutes before a thread is automatically archived for inactivity. Must be one of60,1440,4320, or10080.slowmode_delay (
int) – Specifies the slowmode rate limit for users in this thread, in seconds. A value of0disables slowmode. The maximum value possible is21600.pinned (
bool) –Whether to pin the thread or not. This is only available for threads created in a
ForumChannelorMediaChannel.New in version 2.5.
flags (
ChannelFlags) –The new channel flags to set for this thread. This will overwrite any existing flags set on this channel. If parameter
pinnedis provided, that will override the setting ofChannelFlags.pinned.New in version 2.6.
applied_tags (
Sequence[abc.Snowflake]) –The new tags of the thread. Maximum of 5. Can also be used to reorder existing tags.
This is only available for threads in a
ForumChannelorMediaChannel.If
moderatedtags are edited,Permissions.manage_threadspermissions are required.See also
add_tags()andremove_tags().New in version 2.6.
The reason for editing this thread. Shows up on the audit log.
New in version 2.5.
- Raises:
Forbidden – You do not have permissions to edit the thread.
HTTPException – Editing the thread failed.
- Returns:
The newly edited thread.
- Return type:
- await join()[source]¶
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.
- await leave()[source]¶
This function is a coroutine.
Leaves this thread.
- Raises:
HTTPException – Leaving the thread failed.
- await add_user(user)[source]¶
This function is a coroutine.
Adds a user to this thread.
You must have
send_messagespermission to add a user to a public thread. If the thread is private thensend_messagesand eithercreate_private_threadsormanage_messagespermissions is required to add a user to the thread.- 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.
- await remove_user(user)[source]¶
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 fetch_member(member_id, /)[source]¶
This function is a coroutine.
Retrieves a single
ThreadMemberfrom this thread.- Parameters:
member_id (
int) – The ID of the member to fetch.- Raises:
NotFound – The specified member was not found.
HTTPException – Retrieving the member failed.
- Returns:
The thread member asked for.
- Return type:
- await fetch_members()[source]¶
This function is a coroutine.
Retrieves all
ThreadMemberthat are in this thread.This requires
Intents.membersto get information about members other than yourself.- Raises:
HTTPException – Retrieving the members failed.
- Returns:
All thread members in the thread.
- Return type:
- await delete(*, reason=None)[source]¶
This function is a coroutine.
Deletes this thread.
You must have
manage_threadsto delete threads. Alternatively, you may delete a thread if it’s in aForumChannelorMediaChannel, you are the thread creator, and there are no messages other than the initial message.- Parameters:
The reason for deleting this thread. Shows up on the audit log.
New in version 2.5.
- Raises:
Forbidden – You do not have permissions to delete this thread.
HTTPException – Deleting the thread failed.
- await add_tags(*tags, reason=None)[source]¶
This function is a coroutine.
Adds the given tags to this thread, up to 5 in total.
The thread must be in a
ForumChannelorMediaChannel.Adding tags requires you to have
Permissions.manage_threadspermissions, or be the owner of the thread. However, addingmoderatedtags always requiresPermissions.manage_threadspermissions.New in version 2.6.
- Parameters:
*tags (
abc.Snowflake) – An argument list ofabc.Snowflakerepresenting theForumTags to add to the thread.reason (
str|None) – The reason for editing this thread. Shows up on the audit log.
- Raises:
Forbidden – You do not have permission to add these tags.
HTTPException – Editing the thread failed.
- await remove_tags(*tags, reason=None)[source]¶
This function is a coroutine.
Removes the given tags from this thread.
The thread must be in a
ForumChannelorMediaChannel.Removing tags requires you to have
Permissions.manage_threadspermissions, or be the owner of the thread. However, removingmoderatedtags always requiresPermissions.manage_threadspermissions.New in version 2.6.
- Parameters:
*tags (
abc.Snowflake) – An argument list ofabc.Snowflakerepresenting theForumTags to remove from the thread.reason (
str|None) – The reason for editing this thread. Shows up on the audit log.
- Raises:
Forbidden – You do not have permission to remove these tags.
HTTPException – Editing the thread failed.
- get_partial_message(message_id, /)[source]¶
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.
New in version 2.0.
- Parameters:
message_id (
int) – The message ID to create a partial message for.- Returns:
The partial message.
- Return type:
- await fetch_message(id, /)[source]¶
This function is a coroutine.
Retrieves a single
Messagefrom the destination.- Parameters:
id (
int) – The message ID to look for.- 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.
- Returns:
The message asked for.
- Return type:
- pins(*, limit=50, before=None)[source]¶
Returns an
AsyncIteratorthat enables receiving the destination’s pinned messages.You must have the
Permissions.read_message_historyandPermissions.view_channelpermissions to use this.Note
Due to a limitation with the Discord API, the
Messageobjects returned by this method do not contain completeMessage.reactionsdata.Changed in version 2.11: Now returns an
AsyncIteratorto support changes in Discord’s API.awaiting the result of this method remains supported, but only returns the last 50 pins and is deprecated in favor ofasync for msg in channel.pins().Examples
Usage
counter = 0 async for message in channel.pins(limit=100): if message.author == client.user: counter += 1
Flattening to a list
pinned_messages = await channel.pins(limit=100).flatten() # pinned_messages is now a list of Message...
All parameters are optional.
- Parameters:
limit (
int|None) – The number of pinned messages to retrieve. IfNone, retrieves every pinned message in the channel. Note, however, that this would make it a slow operation.before (
abc.Snowflake|datetime.datetime|None) – Retrieve messages pinned 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.
- Raises:
HTTPException – Retrieving the pinned messages failed.
- Yields:
Message– The pinned message from the parsed message data.
- await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, suppress_embeds=None, flags=None, allowed_mentions=None, reference=None, mention_author=None, view=None, components=None, poll=None)[source]¶
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).At least one of
content,embed/embeds,file/files,stickers,components,pollorviewmust 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.Changed in version 2.6: Raises
TypeErrororValueErrorinstead ofInvalidArgument.- Parameters:
tts (
bool) – Whether the message should be sent using text-to-speech.embed (
Embed) – The rich embed for the content to send. This cannot be mixed with theembedsparameter.A list of embeds to send with the content. Must be a maximum of 10. This cannot be mixed with the
embedparameter.New in version 2.0.
file (
File) – The file to upload. This cannot be mixed with thefilesparameter.files (
list[File]) – A list of files to upload. Must be a maximum of 10. This cannot be mixed with thefileparameter.stickers (
Sequence[GuildSticker|StandardSticker|StickerItem]) –A list of stickers to upload. Must be a maximum of 3.
New in version 2.0.
nonce (
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.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
Client.allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set inClient.allowed_mentions. If no object is passed at all then the defaults given byClient.allowed_mentionsare used instead.New in version 1.4.
reference (
Message|MessageReference|PartialMessage) –A reference to the
Messageto which you are replying, this can be created usingMessage.to_reference()or passed directly as aMessage. You can control whether this mentions the author of the referenced message using theAllowedMentions.replied_userattribute ofallowed_mentionsor by settingmention_author.New in version 1.6.
Note
Passing a
MessageorPartialMessagewill only allow replies. To forward a message you must explicitly transform the message to aMessageReferenceusingMessage.to_reference()and specify theMessageReferenceType, or useMessage.forward().mention_author (
bool|None) –If set, overrides the
AllowedMentions.replied_userattribute ofallowed_mentions.New in version 1.6.
view (
ui.View) –A Discord UI View to add to the message. This cannot be mixed with
components.New in version 2.0.
components (
UIComponent|list[UIComponent|list[WrappedComponent]]) –A list of components to include in the message. This cannot be mixed with
view.New in version 2.4.
Note
Passing v2 components here automatically sets the
is_components_v2flag. Setting this flag cannot be reverted. Note that this also disables thecontent,embeds,stickers, andpollfields.suppress_embeds (
bool) –Whether to suppress embeds for the message. This hides all the embeds from the UI if set to
True.New in version 2.5.
flags (
MessageFlags) –The flags to set for this message. Only
suppress_embeds,suppress_notifications, andis_components_v2are supported.If parameter
suppress_embedsis provided, that will override the setting ofMessageFlags.suppress_embeds.New in version 2.9.
poll (
Poll) –The poll to send with the message.
New in version 2.10.
- Raises:
HTTPException – Sending the message failed.
Forbidden – You do not have the proper permissions to send the message.
TypeError – Specified both
fileandfiles, or you specified bothembedandembeds, or you specified bothviewandcomponents, or thereferenceobject is not aMessage,MessageReferenceorPartialMessage.ValueError – The
filesorembedslist is too large, or you tried to send v2 components together withcontent,embeds,stickers, orpoll.
- Returns:
The message that was sent.
- Return type:
ThreadMember¶
- class disnake.ThreadMember[source]¶
Represents a Discord thread member.
- x == y
Checks if two thread members are equal.
- x != y
Checks if two thread members are not equal.
- hash(x)
Returns the thread member’s hash.
- str(x)
Returns the thread member’s name.
New in version 2.0.
- joined_at¶
The time the member joined the thread in UTC.
- Type:
StageChannel¶
- bitrate
- category
- category_id
- changed_roles
- created_at
- flags
- guild
- id
- instance
- jump_url
- last_message
- last_message_id
- listeners
- members
- mention
- moderators
- name
- nsfw
- overwrites
- permissions_synced
- position
- requesting_to_speak
- rtc_region
- slowmode_delay
- speakers
- topic
- type
- user_limit
- video_quality_mode
- voice_states
- asyncclone
- asyncconnect
- asynccreate_instance
- asynccreate_invite
- asynccreate_webhook
- asyncdelete
- asyncdelete_messages
- asyncedit
- asyncfetch_instance
- asyncfetch_message
- defget_partial_message
- defhistory
- asyncinvites
- defis_nsfw
- asyncmove
- defoverwrites_for
- defpermissions_for
- asyncpurge
- asyncsend
- asyncset_permissions
- asynctrigger_typing
- deftyping
- asyncwebhooks
- class disnake.StageChannel[source]¶
Represents a Discord guild stage channel.
New in version 1.7.
- x == y
Checks if two channels are equal.
- x != y
Checks if two channels are not equal.
- hash(x)
Returns the channel’s hash.
- str(x)
Returns the channel’s name.
- position¶
The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0.
- Type:
- rtc_region¶
The region for the stage channel’s voice communication. A value of
Noneindicates automatic voice region detection.Changed in version 2.5: No longer a
VoiceRegioninstance.
- video_quality_mode¶
The camera video quality for the stage channel’s participants.
New in version 2.0.
- Type:
- nsfw¶
Whether the channel is marked as “not safe for work”.
Note
To check if the channel or the guild of that channel are marked as NSFW, consider
is_nsfw()instead.New in version 2.9.
- Type:
- slowmode_delay¶
The number of seconds a member must wait between sending messages in this channel. A value of 0 denotes that it is disabled. Bots, and users with
manage_channelsormanage_messages, bypass slowmode.New in version 2.9.
- Type:
- last_message_id¶
The last message ID of the message sent to this channel. It may not point to an existing or valid message.
New in version 2.9.
- property requesting_to_speak[source]¶
A list of members who are requesting to speak in the stage channel.
- property speakers[source]¶
A list of members who have been permitted to speak in the stage channel.
New in version 2.0.
- property listeners[source]¶
A list of members who are listening in the stage channel.
New in version 2.0.
- property moderators[source]¶
A list of members who are moderating the stage channel.
New in version 2.0.
- property type[source]¶
The channel’s Discord type.
This always returns
ChannelType.stage_voice.- Type:
- await clone(*, name=None, bitrate=..., position=..., category=..., slowmode_delay=..., rtc_region=..., video_quality_mode=..., nsfw=..., overwrites=..., reason=None)[source]¶
This function is a coroutine.
Clones this channel. This creates a channel with the same properties as this channel.
You must have
Permissions.manage_channelspermission to do this.Changed in version 2.9: Added
position,category,rtc_region,video_quality_mode,bitrate,nsfw,slowmode_delayandoverwriteskeyword-only parameters.Note
The current
StageChannel.flagsvalue won’t be cloned. This is a Discord limitation.Warning
Currently the
user_limitattribute is not cloned due to a Discord limitation. You can directly edit the channel after its creation to set a user_limit.- Parameters:
name (
str|None) – The name of the new channel. If not provided, defaults to this channel’s name.bitrate (
int) – The bitrate of the new channel. If not provided, defaults to this channel’s bitrate.position (
int) – The position of the new channel. If not provided, defaults to this channel’s position.category (
abc.Snowflake|None) – The category where the new channel should be grouped. If not provided, defaults to this channel’s category.slowmode_delay (
int) – The slowmode of the new channel. If not provided, defaults to this channel’s slowmode.rtc_region (
str|VoiceRegion|None) – The rtc region of the new channel. If not provided, defaults to this channel’s rtc region.video_quality_mode (
VideoQualityMode) – The video quality mode of the new channel. If not provided, defaults to this channel’s video quality mode.nsfw (
bool) – Whether the new channel should be nsfw or not. If not provided, defaults to this channel’s NSFW value.overwrites (
Mapping[Member|Role,PermissionOverwrite]) – AMappingof target (either a role or a member) toPermissionOverwriteto apply to the channel. If not provided, defaults to this channel’s overwrites.reason (
str|None) – The reason for cloning this channel. Shows up on the audit log.
- Raises:
Forbidden – You do not have the proper permissions to create this channel.
HTTPException – Creating the channel failed.
- Returns:
The channel that was created.
- Return type:
- property last_message[source]¶
Gets the last message in this channel from the 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.New in version 2.9.
- get_partial_message(message_id, /)[source]¶
Creates a
PartialMessagefrom the given message ID.This is useful if you want to work with a message and only have its ID without doing an unnecessary API call.
New in version 2.9.
- Parameters:
message_id (
int) – The message ID to create a partial message for.- Returns:
The partial message object.
- Return type:
- property instance[source]¶
The running stage instance of the stage channel.
New in version 2.0.
- Type:
- await create_instance(*, topic, privacy_level=..., notify_everyone=False, guild_scheduled_event=..., reason=None)[source]¶
This function is a coroutine.
Creates a stage instance.
You must have
manage_channelspermission to do this.New in version 2.0.
Changed in version 2.6: Raises
TypeErrorinstead ofInvalidArgument.- Parameters:
topic (
str) – The stage instance’s topic.privacy_level (
StagePrivacyLevel) – The stage instance’s privacy level. Defaults toStagePrivacyLevel.guild_only.notify_everyone (
bool) –Whether to notify
@everyonethat the stage instance has started. Requires themention_everyonepermission on the stage channel. Defaults toFalse.New in version 2.5.
guild_scheduled_event (
abc.Snowflake) –The guild scheduled event associated with the stage instance. Setting this will automatically start the event.
New in version 2.10.
reason (
str|None) – The reason the stage instance was created. Shows up on the audit log.
- Raises:
Forbidden – You do not have permissions to create a stage instance.
HTTPException – Creating a stage instance failed.
TypeError – If the
privacy_levelparameter is not the proper type.
- Returns:
The newly created stage instance.
- Return type:
- await fetch_instance()[source]¶
This function is a coroutine.
Retrieves the running
StageInstance.New in version 2.0.
- Raises:
NotFound – The stage instance or channel could not be found.
HTTPException – Retrieving the stage instance failed.
- Returns:
The stage instance.
- Return type:
- await edit(*, name=..., bitrate=..., user_limit=..., position=..., sync_permissions=..., category=..., overwrites=..., rtc_region=..., video_quality_mode=..., nsfw=..., slowmode_delay=..., flags=..., reason=None, **kwargs)[source]¶
This function is a coroutine.
Edits the channel.
You must have
manage_channelspermission to do this.Changed in version 2.0: The
topicparameter must now be set viacreate_instance.Changed in version 2.0: Edits are no longer in-place, the newly edited channel is returned instead.
Changed in version 2.6: Raises
TypeErrororValueErrorinstead ofInvalidArgument.Changed in version 2.9: The
user_limit,nsfw, andslowmode_delaykeyword-only parameters were added.- Parameters:
name (
str) – The channel’s new name.bitrate (
int) –The channel’s new bitrate.
New in version 2.6.
user_limit (
int) –The channel’s new user limit.
New in version 2.9.
position (
int) – The channel’s new position.sync_permissions (
bool) – Whether to sync permissions with the channel’s new or pre-existing category. Defaults toFalse.category (
abc.Snowflake|None) – The new category for this channel. Can beNoneto remove the category.overwrites (
Mapping[Member|Role,PermissionOverwrite]) – AMappingof target (either a role or a member) toPermissionOverwriteto apply to the channel.rtc_region (
str|VoiceRegion|None) – The new region for the stage channel’s voice communication. A value ofNoneindicates automatic voice region detection.video_quality_mode (
VideoQualityMode) –The camera video quality for the stage channel’s participants.
New in version 2.9.
nsfw (
bool) –Whether to mark the channel as NSFW.
New in version 2.9.
Specifies the slowmode rate limit for users in this channel, in seconds. A value of
0disables slowmode. The maximum value possible is21600.New in version 2.9.
flags (
ChannelFlags) –The new flags to set for this channel. This will overwrite any existing flags set on this channel.
New in version 2.6.
reason (
str|None) – The reason for editing this channel. Shows up on the audit log.
- Raises:
Forbidden – You do not have permissions to edit the channel.
HTTPException – Editing the channel failed.
TypeError – The permission overwrite information is not in proper form.
ValueError – The position is less than 0.
- Returns:
The newly edited stage channel. If the edit was only positional then
Noneis returned instead.- Return type:
- await delete_messages(messages)[source]¶
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.
You must have
manage_messagespermission to do this.New in version 2.9.
- Parameters:
messages (
Iterable[abc.Snowflake]) – An iterable of messages denoting which ones to bulk delete.- Raises:
ClientException – The number of messages to delete was more than 100.
Forbidden – You do not have proper permissions to delete the messages.
NotFound – If single delete, then the message was already deleted.
HTTPException – Deleting the messages failed.
- await purge(*, limit=100, check=..., before=None, after=None, around=None, oldest_first=False, bulk=True)[source]¶
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
manage_messagespermission to delete messages even if they are your own.read_message_historypermission is also needed to retrieve message history.New in version 2.9.
Note
See
TextChannel.purge()for examples.- Parameters:
limit (
int|None) – 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 (
abc.Snowflake|datetime.datetime|None) – Same asbeforeinhistory().after (
abc.Snowflake|datetime.datetime|None) – Same asafterinhistory().around (
abc.Snowflake|datetime.datetime|None) – Same asaroundinhistory().oldest_first (
bool|None) – 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.
- Raises:
Forbidden – You do not have proper permissions to do the actions required.
HTTPException – Purging the messages failed.
- Returns:
A list of messages that were deleted.
- Return type:
- await webhooks()[source]¶
This function is a coroutine.
Retrieves the list of webhooks this channel has.
You must have
manage_webhookspermission to use this.New in version 2.9.
- await create_webhook(*, name, avatar=None, reason=None)[source]¶
This function is a coroutine.
Creates a webhook for this channel.
You must have
manage_webhookspermission to do this.New in version 2.9.
- Parameters:
- Raises:
NotFound – The
avatarasset couldn’t be found.Forbidden – You do not have permissions to create a webhook.
HTTPException – Creating the webhook failed.
TypeError – The
avatarasset is a lottie sticker (seeSticker.read()).
- Returns:
The newly created webhook.
- Return type:
- property category[source]¶
The category this channel belongs to.
If there is no category then this is
None.- Type:
- property changed_roles[source]¶
Returns a list of roles that have been overridden from their default values in the
Guild.rolesattribute.
- await connect(*, timeout=60.0, reconnect=True, cls=<class 'disnake.voice_client.VoiceClient'>)[source]¶
This function is a coroutine.
Connects to voice and creates a
VoiceClientto establish your connection to the voice server.This requires
Intents.voice_states.- Parameters:
timeout (
float) – The timeout in seconds to wait for the voice endpoint.reconnect (
bool) – Whether the bot should automatically attempt a reconnect if a part of the handshake fails or the gateway goes down.cls (
type[VoiceProtocol]) – A type that subclassesVoiceProtocolto connect with. Defaults toVoiceClient.
- Raises:
asyncio.TimeoutError – Could not connect to the voice channel in time.
ClientException – You are already connected to a voice channel.
opus.OpusNotLoaded – The opus library has not been loaded.
- Returns:
A voice client that is fully connected to the voice server.
- Return type:
- await create_invite(*, reason=None, max_age=0, max_uses=0, temporary=False, unique=True, target_type=None, target_user=None, target_application=None, guild_scheduled_event=None)[source]¶
This function is a coroutine.
Creates an instant invite from a text or voice channel.
You must have
Permissions.create_instant_invitepermission to do this.- Parameters:
max_age (
int) – How long the invite should last in seconds. If set to0, 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) – Whether the invite grants temporary membership (i.e. they get kicked after they disconnect). Defaults toFalse.unique (
bool) – Whether a unique invite URL should be created. Defaults toTrue. If this is set toFalsethen it will return a previously created invite.target_type (
InviteTarget|None) –The type of target for the voice channel invite, if any.
New in version 2.0.
The user whose stream to display for this invite, required if
target_typeisInviteTarget.stream. The user must be streaming in the channel.New in version 2.0.
target_application (
Snowflake|None) –The ID of the embedded application for the invite, required if
target_typeisInviteTarget.embedded_application.New in version 2.0.
Changed in version 2.9:
PartyTypeis deprecated, andSnowflakeshould be used instead.guild_scheduled_event (
GuildScheduledEvent|None) –The guild scheduled event to include with the invite.
New in version 2.3.
reason (
str|None) – The reason for creating this invite. Shows up on the audit log.
- Raises:
HTTPException – Invite creation failed.
NotFound – The channel that was passed is a category or an invalid channel.
- Returns:
The newly created invite.
- Return type:
- await delete(*, reason=None)[source]¶
This function is a coroutine.
Deletes the channel.
You must have
Permissions.manage_channelspermission to do this.- Parameters:
reason (
str|None) – 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.
- await fetch_message(id, /)[source]¶
This function is a coroutine.
Retrieves a single
Messagefrom the destination.- Parameters:
id (
int) – The message ID to look for.- 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.
- Returns:
The message asked for.
- Return type:
- history(*, limit=100, before=None, after=None, around=None, oldest_first=None)[source]¶
Returns an
AsyncIteratorthat enables receiving the destination’s message history.You must have
Permissions.read_message_historypermission to use this.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.
- Parameters:
limit (
int|None) – The number of messages to retrieve. IfNone, retrieves every message in the channel. Note, however, that this would make it a slow operation.before (
abc.Snowflake|datetime.datetime|None) – 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 (
abc.Snowflake|datetime.datetime|None) – 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 (
abc.Snowflake|datetime.datetime|None) – 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 (
bool|None) – If set toTrue, return messages in oldest->newest order. Defaults toTrueifafteris specified, otherwiseFalse.
- Raises:
Forbidden – You do not have permissions to get channel message history.
HTTPException – The request to get message history failed.
- Yields:
Message– The message with the message data parsed.
- await invites()[source]¶
This function is a coroutine.
Returns a list of all active instant invites from this channel.
You must have
Permissions.manage_channelspermission to use this.- Raises:
Forbidden – You do not have proper permissions to get the information.
HTTPException – An error occurred while fetching the information.
- Returns:
The list of invites that are currently active.
- Return type:
- property jump_url[source]¶
A URL that can be used to jump to this channel.
New in version 2.4.
Note
This exists for all guild channels but may not be usable by the client for all guild channel types.
- await move(**kwargs)[source]¶
This function is a coroutine.
A rich interface to help move a channel relative to other channels.
If exact position movement is required,
editshould be used instead.You must have
Permissions.manage_channelspermission to do this.Note
Voice channels will always be sorted below text channels. This is a Discord limitation.
New in version 1.7.
Changed in version 2.6: Raises
TypeErrororValueErrorinstead ofInvalidArgument.- Parameters:
beginning (
bool) – Whether to move the channel to the beginning of the channel list (or category if given). This is mutually exclusive withend,before, andafter.end (
bool) – Whether to move the channel to the end of the channel list (or category if given). This is mutually exclusive withbeginning,before, andafter.before (
abc.Snowflake) – The channel that should be before our current channel. This is mutually exclusive withbeginning,end, andafter.after (
abc.Snowflake) – The channel that should be after our current channel. This is mutually exclusive withbeginning,end, andbefore.offset (
int) – The number of channels to offset the move by. For example, an offset of2withbeginning=Truewould move it 2 after the beginning. A positive number moves it below while a negative number moves it above. Note that this number is relative and computed after thebeginning,end,before, andafterparameters.category (
abc.Snowflake|None) – The category to move this channel under. IfNoneis given then it moves it out of the category. This parameter is ignored if moving a category channel.sync_permissions (
bool) – Whether to sync the permissions with the category (if given).reason (
str|None) – The reason for moving this channel. Shows up on the audit log.
- Raises:
Forbidden – You do not have permissions to move the channel.
HTTPException – Moving the channel failed.
TypeError – A bad mix of arguments were passed.
ValueError – An invalid position was given.
- property overwrites[source]¶
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:
- overwrites_for(obj)[source]¶
Returns the channel-specific overwrites for a member or a role.
- permissions_for(obj, /, *, ignore_timeout=...)[source]¶
Handles permission resolution for the
MemberorRole.This function takes into consideration the following cases:
Guild owner
Guild roles
Channel overrides
Member overrides
Timeouts
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
Note
If the channel originated from an
Interactionand theguildattribute is unavailable, such as with user-installed applications in guilds, this method will not work due to an API limitation. Consider usingInteraction.permissionsorapp_permissionsinstead.Changed in version 2.0: The object passed in can now be a role object.
- Parameters:
obj (
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.ignore_timeout (
bool) –Whether or not to ignore the user’s timeout. Defaults to
False.New in version 2.4.
Note
This only applies to
Memberobjects.Changed in version 2.6: The default was changed to
False.
- Raises:
TypeError –
ignore_timeoutis only supported forMemberobjects.- Returns:
The resolved permissions for the member or role.
- Return type:
- property permissions_synced[source]¶
Whether or not the permissions for this channel are synced with the category it belongs to.
If there is no category then this is
False.New in version 1.3.
- Type:
- await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, suppress_embeds=None, flags=None, allowed_mentions=None, reference=None, mention_author=None, view=None, components=None, poll=None)[source]¶
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).At least one of
content,embed/embeds,file/files,stickers,components,pollorviewmust 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.Changed in version 2.6: Raises
TypeErrororValueErrorinstead ofInvalidArgument.- Parameters:
tts (
bool) – Whether the message should be sent using text-to-speech.embed (
Embed) – The rich embed for the content to send. This cannot be mixed with theembedsparameter.A list of embeds to send with the content. Must be a maximum of 10. This cannot be mixed with the
embedparameter.New in version 2.0.
file (
File) – The file to upload. This cannot be mixed with thefilesparameter.files (
list[File]) – A list of files to upload. Must be a maximum of 10. This cannot be mixed with thefileparameter.stickers (
Sequence[GuildSticker|StandardSticker|StickerItem]) –A list of stickers to upload. Must be a maximum of 3.
New in version 2.0.
nonce (
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.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
Client.allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set inClient.allowed_mentions. If no object is passed at all then the defaults given byClient.allowed_mentionsare used instead.New in version 1.4.
reference (
Message|MessageReference|PartialMessage) –A reference to the
Messageto which you are replying, this can be created usingMessage.to_reference()or passed directly as aMessage. You can control whether this mentions the author of the referenced message using theAllowedMentions.replied_userattribute ofallowed_mentionsor by settingmention_author.New in version 1.6.
Note
Passing a
MessageorPartialMessagewill only allow replies. To forward a message you must explicitly transform the message to aMessageReferenceusingMessage.to_reference()and specify theMessageReferenceType, or useMessage.forward().mention_author (
bool|None) –If set, overrides the
AllowedMentions.replied_userattribute ofallowed_mentions.New in version 1.6.
view (
ui.View) –A Discord UI View to add to the message. This cannot be mixed with
components.New in version 2.0.
components (
UIComponent|list[UIComponent|list[WrappedComponent]]) –A list of components to include in the message. This cannot be mixed with
view.New in version 2.4.
Note
Passing v2 components here automatically sets the
is_components_v2flag. Setting this flag cannot be reverted. Note that this also disables thecontent,embeds,stickers, andpollfields.suppress_embeds (
bool) –Whether to suppress embeds for the message. This hides all the embeds from the UI if set to
True.New in version 2.5.
flags (
MessageFlags) –The flags to set for this message. Only
suppress_embeds,suppress_notifications, andis_components_v2are supported.If parameter
suppress_embedsis provided, that will override the setting ofMessageFlags.suppress_embeds.New in version 2.9.
poll (
Poll) –The poll to send with the message.
New in version 2.10.
- Raises:
HTTPException – Sending the message failed.
Forbidden – You do not have the proper permissions to send the message.
TypeError – Specified both
fileandfiles, or you specified bothembedandembeds, or you specified bothviewandcomponents, or thereferenceobject is not aMessage,MessageReferenceorPartialMessage.ValueError – The
filesorembedslist is too large, or you tried to send v2 components together withcontent,embeds,stickers, orpoll.
- Returns:
The message that was sent.
- Return type:
- await set_permissions(target, *, overwrite=..., reason=None, **permissions)[source]¶
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
Permissions.manage_rolespermission to do this.Note
This method replaces the old overwrites with the ones given.
Changed in version 2.6: Raises
TypeErrorinstead ofInvalidArgument.Examples
Setting allow and deny:
await message.channel.set_permissions(message.author, view_channel=True, send_messages=False)
Deleting overwrites
await channel.set_permissions(member, overwrite=None)
Using
PermissionOverwriteoverwrite = disnake.PermissionOverwrite() overwrite.send_messages = False overwrite.view_channel = True await channel.set_permissions(member, overwrite=overwrite)
- Parameters:
target (
Member|Role) – The member or role to overwrite permissions for.overwrite (
PermissionOverwrite|None) – The permissions to allow and deny to the target, orNoneto delete the overwrite.**permissions – A keyword argument list of permissions to set for ease of use. Cannot be mixed with
overwrite.reason (
str|None) – 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.
TypeError –
overwriteis invalid, the target type was notRoleorMember, both keyword arguments andoverwritewere provided, or invalid permissions were provided as keyword arguments.
- await trigger_typing()[source]¶
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.
- typing()[source]¶
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.
Note
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!')
ForumChannel¶
- available_tags
- category
- category_id
- changed_roles
- created_at
- default_auto_archive_duration
- default_layout
- default_reaction
- default_sort_order
- default_thread_slowmode_delay
- flags
- guild
- id
- jump_url
- last_thread
- last_thread_id
- members
- mention
- name
- nsfw
- overwrites
- permissions_synced
- position
- slowmode_delay
- threads
- topic
- type
- defarchived_threads
- asyncclone
- asynccreate_invite
- asynccreate_thread
- asynccreate_webhook
- asyncdelete
- asyncedit
- defget_tag
- defget_tag_by_name
- defget_thread
- asyncinvites
- defis_nsfw
- asyncmove
- defoverwrites_for
- defpermissions_for
- defrequires_tag
- asyncset_permissions
- asynctrigger_typing
- deftyping
- asyncwebhooks
- class disnake.ForumChannel[source]¶
Represents a Discord guild forum channel.
New in version 2.5.
- x == y
Checks if two channels are equal.
- x != y
Checks if two channels are not equal.
- hash(x)
Returns the channel’s hash.
- str(x)
Returns the channel’s name.
- position¶
The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0.
- Type:
- nsfw¶
Whether the channel is marked as “not safe for work”.
Note
To check if the channel or the guild of that channel are marked as NSFW, consider
is_nsfw()instead.- Type:
- last_thread_id¶
The ID of the last created thread in this channel. It may not point to an existing or valid thread.
- default_auto_archive_duration¶
The default auto archive duration in minutes for threads created in this channel.
- Type:
- slowmode_delay¶
The number of seconds a member must wait between creating threads in this channel.
A value of
0denotes that it is disabled. Bots, and users withmanage_channelsormanage_messages, bypass slowmode.See also
default_thread_slowmode_delay.- Type:
- default_thread_slowmode_delay¶
The default number of seconds a member must wait between sending messages in newly created threads in this channel.
A value of
0denotes that it is disabled. Bots, and users withmanage_channelsormanage_messages, bypass slowmode.New in version 2.6.
- Type:
- default_sort_order¶
The default sort order of threads in this channel. Members will still be able to change this locally.
New in version 2.6.
- Type:
- default_layout¶
The default layout of threads in this channel. Members will still be able to change this locally.
New in version 2.8.
- Type:
- async with typing()[source]¶
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.
Note
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!')
- property type[source]¶
The channel’s Discord type.
This always returns
ChannelType.forum.- Type:
- await edit(*, name=..., topic=..., position=..., nsfw=..., sync_permissions=..., category=..., slowmode_delay=..., default_thread_slowmode_delay=..., default_auto_archive_duration=..., overwrites=..., flags=..., require_tag=..., available_tags=..., default_reaction=..., default_sort_order=..., default_layout=..., reason=None, **kwargs)[source]¶
This function is a coroutine.
Edits the channel.
You must have
manage_channelspermission to do this.Changed in version 2.6: Raises
TypeErrororValueErrorinstead ofInvalidArgument.- Parameters:
name (
str) – The channel’s new name.position (
int) – The channel’s new position.nsfw (
bool) – Whether to mark the channel as NSFW.sync_permissions (
bool) – Whether to sync permissions with the channel’s new or pre-existing category. Defaults toFalse.category (
abc.Snowflake|None) – The new category for this channel. Can beNoneto remove the category.slowmode_delay (
int|None) – Specifies the slowmode rate limit at which users can create threads in this channel, in seconds. A value of0orNonedisables slowmode. The maximum value possible is21600.default_thread_slowmode_delay (
int|None) –Specifies the slowmode rate limit at which users can send messages in newly created threads in this channel, in seconds. This does not apply retroactively to existing threads. A value of
0orNonedisables slowmode. The maximum value possible is21600.New in version 2.6.
overwrites (
Mapping[Member|Role,PermissionOverwrite]) – AMappingof target (either a role or a member) toPermissionOverwriteto apply to the channel.default_auto_archive_duration (
int|ThreadArchiveDuration|None) – The new default auto archive duration in minutes for threads created in this channel. Must be one of60,1440,4320, or10080.flags (
ChannelFlags) –The new flags to set for this channel. This will overwrite any existing flags set on this channel. If parameter
require_tagis provided, that will override the setting ofChannelFlags.require_tag.New in version 2.6.
require_tag (
bool) –Whether all newly created threads are required to have a tag.
New in version 2.6.
available_tags (
Sequence[ForumTag]) –The new
ForumTags available for threads in this channel. Can be used to create new tags and edit/reorder/delete existing tags. Maximum of 20.Note that this overwrites all tags, removing existing tags unless they’re passed as well.
See
ForumTagfor examples regarding creating/editing tags.New in version 2.6.
default_reaction (
str|Emoji|PartialEmoji|None) –The new default emoji shown for reacting to threads.
New in version 2.6.
default_sort_order (
ThreadSortOrder|None) –The new default sort order of threads in this channel.
New in version 2.6.
default_layout (
ThreadLayout) –The new default layout of threads in this channel.
New in version 2.8.
reason (
str|None) – The reason for editing this channel. Shows up on the audit log.
- Raises:
Forbidden – You do not have permissions to edit the channel.
HTTPException – Editing the channel failed.
TypeError – The permission overwrite information is not in proper form.
ValueError – The position is less than 0.
- Returns:
The newly edited forum channel. If the edit was only positional then
Noneis returned instead.- Return type:
- await clone(*, name=None, topic=..., position=..., nsfw=..., category=..., slowmode_delay=..., default_thread_slowmode_delay=..., default_auto_archive_duration=..., available_tags=..., default_reaction=..., default_sort_order=..., default_layout=..., overwrites=..., reason=None)[source]¶
This function is a coroutine.
Clones this channel. This creates a channel with the same properties as this channel.
You must have
Permissions.manage_channelspermission to do this.Changed in version 2.9: Added new
topic,position,nsfw,category,slowmode_delay,default_thread_slowmode_delay,default_auto_archive_duration,available_tags,default_reaction,default_sort_orderandoverwriteskeyword-only parameters.Changed in version 2.10: Added
default_layoutparameter.Note
The current
ForumChannel.flagsvalue won’t be cloned. This is a Discord limitation.- Parameters:
name (
str|None) – The name of the new channel. If not provided, defaults to this channel’s name.topic (
str|None) – The topic of the new channel. If not provided, defaults to this channel’s topic.position (
int) – The position of the new channel. If not provided, defaults to this channel’s position.nsfw (
bool) – Whether the new channel should be nsfw or not. If not provided, defaults to this channel’s NSFW value.category (
abc.Snowflake|None) – The category where the new channel should be grouped. If not provided, defaults to this channel’s category.slowmode_delay (
int|None) – The slowmode delay of the new channel. If not provided, defaults to this channel’s slowmode delay.default_thread_slowmode_delay (
int|None) – The default thread slowmode delay of the new channel. If not provided, defaults to this channel’s default thread slowmode delay.default_auto_archive_duration (
int|ThreadArchiveDuration|None) – The default auto archive duration of the new channel. If not provided, defaults to this channel’s default auto archive duration.available_tags (
Sequence[ForumTag]) – The applicable tags of the new channel. If not provided, defaults to this channel’s available tags.default_reaction (
str|Emoji|PartialEmoji|None) – The default reaction of the new channel. If not provided, defaults to this channel’s default reaction.default_sort_order (
ThreadSortOrder|None) – The default sort order of the new channel. If not provided, defaults to this channel’s default sort order.default_layout (
ThreadLayout) – The default layout of threads in the new channel. If not provided, defaults to this channel’s default layout.overwrites (
Mapping[Member|Role,PermissionOverwrite]) – AMappingof target (either a role or a member) toPermissionOverwriteto apply to the channel. If not provided, defaults to this channel’s overwrites.reason (
str|None) – The reason for cloning this channel. Shows up on the audit log.
- Raises:
Forbidden – You do not have the proper permissions to create this channel.
HTTPException – Creating the channel failed.
- Returns:
The channel that was created.
- Return type:
- archived_threads(*, limit=50, before=None)[source]¶
Returns an
AsyncIteratorthat iterates over all archived threads in the channel.You must have
read_message_historypermission to use this.- Parameters:
limit (
int|None) – The number of threads to retrieve. IfNone, retrieves every archived thread in the channel. Note, however, that this would make it a slow operation.before (
abc.Snowflake|datetime.datetime|None) – Retrieve archived channels before the given date or ID.
- Raises:
Forbidden – You do not have permissions to get archived threads.
HTTPException – The request to get the archived threads failed.
- Yields:
Thread– The archived threads.
- property available_tags[source]¶
The available tags for threads in this channel.
To create/edit/delete tags, use
edit().New in version 2.6.
- property category[source]¶
The category this channel belongs to.
If there is no category then this is
None.- Type:
- property changed_roles[source]¶
Returns a list of roles that have been overridden from their default values in the
Guild.rolesattribute.
- await create_invite(*, reason=None, max_age=0, max_uses=0, temporary=False, unique=True, target_type=None, target_user=None, target_application=None, guild_scheduled_event=None)[source]¶
This function is a coroutine.
Creates an instant invite from a text or voice channel.
You must have
Permissions.create_instant_invitepermission to do this.- Parameters:
max_age (
int) – How long the invite should last in seconds. If set to0, 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) – Whether the invite grants temporary membership (i.e. they get kicked after they disconnect). Defaults toFalse.unique (
bool) – Whether a unique invite URL should be created. Defaults toTrue. If this is set toFalsethen it will return a previously created invite.target_type (
InviteTarget|None) –The type of target for the voice channel invite, if any.
New in version 2.0.
The user whose stream to display for this invite, required if
target_typeisInviteTarget.stream. The user must be streaming in the channel.New in version 2.0.
target_application (
Snowflake|None) –The ID of the embedded application for the invite, required if
target_typeisInviteTarget.embedded_application.New in version 2.0.
Changed in version 2.9:
PartyTypeis deprecated, andSnowflakeshould be used instead.guild_scheduled_event (
GuildScheduledEvent|None) –The guild scheduled event to include with the invite.
New in version 2.3.
reason (
str|None) – The reason for creating this invite. Shows up on the audit log.
- Raises:
HTTPException – Invite creation failed.
NotFound – The channel that was passed is a category or an invalid channel.
- Returns:
The newly created invite.
- Return type:
- await create_thread(*, name, auto_archive_duration=..., slowmode_delay=..., applied_tags=..., content=..., embed=..., embeds=..., file=..., files=..., suppress_embeds=..., flags=..., stickers=..., allowed_mentions=..., view=..., components=..., reason=None)[source]¶
This function is a coroutine.
Creates a thread (with an initial message) in this channel.
You must have the
create_forum_threadspermission to do this.At least one of
content,embed/embeds,file/files,stickers,components, orviewmust be provided.Changed in version 2.6: Raises
TypeErrororValueErrorinstead ofInvalidArgument.Changed in version 2.6: The
contentparameter is no longer required.Note
Unlike
TextChannel.create_thread(), this returns a tuple with both the created thread and message.- Parameters:
name (
str) – The name of the thread.auto_archive_duration (
int|ThreadArchiveDuration) – The duration in minutes before the thread is automatically archived for inactivity. If not provided, the channel’s default auto archive duration is used. Must be one of60,1440,4320, or10080.slowmode_delay (
int|None) – Specifies the slowmode rate limit for users in this thread, in seconds. A value of0disables slowmode. The maximum value possible is21600. If set toNoneor not provided, slowmode is inherited from the parent’sdefault_thread_slowmode_delay.applied_tags (
Sequence[abc.Snowflake]) –The tags to apply to the new thread. Maximum of 5.
New in version 2.6.
content (
str) – The content of the message to send.embed (
Embed) – The rich embed for the content to send. This cannot be mixed with theembedsparameter.embeds (
list[Embed]) – A list of embeds to send with the content. Must be a maximum of 10. This cannot be mixed with theembedparameter.suppress_embeds (
bool) – Whether to suppress embeds for the message. This hides all the embeds from the UI if set toTrue.flags (
MessageFlags) –The flags to set for this message. Only
suppress_embedsandis_components_v2are supported.If parameter
suppress_embedsis provided, that will override the setting ofMessageFlags.suppress_embeds.New in version 2.9.
file (
File) – The file to upload. This cannot be mixed with thefilesparameter.files (
list[File]) – A list of files to upload. Must be a maximum of 10. This cannot be mixed with thefileparameter.stickers (
Sequence[GuildSticker|StandardSticker|StickerItem]) – A list of stickers to upload. Must be a maximum of 3.allowed_mentions (
AllowedMentions) – Controls the mentions being processed in this message. If this is passed, then the object is merged withClient.allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set inClient.allowed_mentions. If no object is passed at all then the defaults given byClient.allowed_mentionsare used instead.view (
ui.View) – A Discord UI View to add to the message. This cannot be mixed withcomponents.components (
UIComponent|list[UIComponent|list[WrappedComponent]]) –A list of components to include in the message. This cannot be mixed with
view.Note
Passing v2 components here automatically sets the
is_components_v2flag. Setting this flag cannot be reverted. Note that this also disables thecontent,embeds, andstickersfields.reason (
str|None) – The reason for creating the thread. Shows up on the audit log.
- Raises:
Forbidden – You do not have permissions to create a thread.
HTTPException – Starting the thread failed.
TypeError – Specified both
fileandfiles, or you specified bothembedandembeds, or you specified bothviewandcomponents, or you have passed an object that is notFiletofileorfiles.ValueError – Specified more than 10 embeds, or more than 10 files, or you tried to send v2 components together with
content,embeds, orstickers.
- Returns:
A
NamedTuplewith the newly created thread and the message sent in it.- Return type:
- await create_webhook(*, name, avatar=None, reason=None)[source]¶
This function is a coroutine.
Creates a webhook for this channel.
You must have
manage_webhookspermission to do this.New in version 2.6.
- Parameters:
- Raises:
NotFound – The
avatarasset couldn’t be found.Forbidden – You do not have permissions to create a webhook.
HTTPException – Creating the webhook failed.
TypeError – The
avatarasset is a lottie sticker (seeSticker.read()).
- Returns:
The newly created webhook.
- Return type:
- property default_reaction[source]¶
Emoji|PartialEmoji|None: The default emoji shown for reacting to threads.Due to a Discord limitation, this will have an empty
nameif it is a customPartialEmoji.New in version 2.6.
- await delete(*, reason=None)[source]¶
This function is a coroutine.
Deletes the channel.
You must have
Permissions.manage_channelspermission to do this.- Parameters:
reason (
str|None) – 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.
- get_tag_by_name(name, /)[source]¶
Returns a thread tag with the given name.
Tags can be uniquely identified based on the name, as tag names in a channel must be unique.
New in version 2.6.
- await invites()[source]¶
This function is a coroutine.
Returns a list of all active instant invites from this channel.
You must have
Permissions.manage_channelspermission to use this.- Raises:
Forbidden – You do not have proper permissions to get the information.
HTTPException – An error occurred while fetching the information.
- Returns:
The list of invites that are currently active.
- Return type:
- property jump_url[source]¶
A URL that can be used to jump to this channel.
New in version 2.4.
Note
This exists for all guild channels but may not be usable by the client for all guild channel types.
- property last_thread[source]¶
Gets the last created thread in this channel from the cache.
The thread might not be valid or point to an existing thread.
Reliable Fetching
For a slightly more reliable method of fetching the last thread, use
Guild.fetch_channel()with thelast_thread_idattribute.
- await move(**kwargs)[source]¶
This function is a coroutine.
A rich interface to help move a channel relative to other channels.
If exact position movement is required,
editshould be used instead.You must have
Permissions.manage_channelspermission to do this.Note
Voice channels will always be sorted below text channels. This is a Discord limitation.
New in version 1.7.
Changed in version 2.6: Raises
TypeErrororValueErrorinstead ofInvalidArgument.- Parameters:
beginning (
bool) – Whether to move the channel to the beginning of the channel list (or category if given). This is mutually exclusive withend,before, andafter.end (
bool) – Whether to move the channel to the end of the channel list (or category if given). This is mutually exclusive withbeginning,before, andafter.before (
abc.Snowflake) – The channel that should be before our current channel. This is mutually exclusive withbeginning,end, andafter.after (
abc.Snowflake) – The channel that should be after our current channel. This is mutually exclusive withbeginning,end, andbefore.offset (
int) – The number of channels to offset the move by. For example, an offset of2withbeginning=Truewould move it 2 after the beginning. A positive number moves it below while a negative number moves it above. Note that this number is relative and computed after thebeginning,end,before, andafterparameters.category (
abc.Snowflake|None) – The category to move this channel under. IfNoneis given then it moves it out of the category. This parameter is ignored if moving a category channel.sync_permissions (
bool) – Whether to sync the permissions with the category (if given).reason (
str|None) – The reason for moving this channel. Shows up on the audit log.
- Raises:
Forbidden – You do not have permissions to move the channel.
HTTPException – Moving the channel failed.
TypeError – A bad mix of arguments were passed.
ValueError – An invalid position was given.
- property overwrites[source]¶
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:
- overwrites_for(obj)[source]¶
Returns the channel-specific overwrites for a member or a role.
- permissions_for(obj, /, *, ignore_timeout=...)[source]¶
Handles permission resolution for the
MemberorRole.This function takes into consideration the following cases:
Guild owner
Guild roles
Channel overrides
Member overrides
Timeouts
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
Note
If the channel originated from an
Interactionand theguildattribute is unavailable, such as with user-installed applications in guilds, this method will not work due to an API limitation. Consider usingInteraction.permissionsorapp_permissionsinstead.Changed in version 2.0: The object passed in can now be a role object.
- Parameters:
obj (
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.ignore_timeout (
bool) –Whether or not to ignore the user’s timeout. Defaults to
False.New in version 2.4.
Note
This only applies to
Memberobjects.Changed in version 2.6: The default was changed to
False.
- Raises:
TypeError –
ignore_timeoutis only supported forMemberobjects.- Returns:
The resolved permissions for the member or role.
- Return type:
- property permissions_synced[source]¶
Whether or not the permissions for this channel are synced with the category it belongs to.
If there is no category then this is
False.New in version 1.3.
- Type:
- requires_tag()[source]¶
Whether all newly created threads in this channel are required to have a tag.
This is a shortcut to
self.flags.require_tag.New in version 2.6.
- Return type:
- await set_permissions(target, *, overwrite=..., reason=None, **permissions)[source]¶
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
Permissions.manage_rolespermission to do this.Note
This method replaces the old overwrites with the ones given.
Changed in version 2.6: Raises
TypeErrorinstead ofInvalidArgument.Examples
Setting allow and deny:
await message.channel.set_permissions(message.author, view_channel=True, send_messages=False)
Deleting overwrites
await channel.set_permissions(member, overwrite=None)
Using
PermissionOverwriteoverwrite = disnake.PermissionOverwrite() overwrite.send_messages = False overwrite.view_channel = True await channel.set_permissions(member, overwrite=overwrite)
- Parameters:
target (
Member|Role) – The member or role to overwrite permissions for.overwrite (
PermissionOverwrite|None) – The permissions to allow and deny to the target, orNoneto delete the overwrite.**permissions – A keyword argument list of permissions to set for ease of use. Cannot be mixed with
overwrite.reason (
str|None) – 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.
TypeError –
overwriteis invalid, the target type was notRoleorMember, both keyword arguments andoverwritewere provided, or invalid permissions were provided as keyword arguments.
- await trigger_typing()[source]¶
This function is a coroutine.
Triggers a typing indicator to the destination.
Typing indicator will go away after 10 seconds.
- await webhooks()[source]¶
This function is a coroutine.
Retrieves the list of webhooks this channel has.
You must have
manage_webhookspermission to use this.New in version 2.6.
MediaChannel¶
- available_tags
- category
- category_id
- changed_roles
- created_at
- default_auto_archive_duration
- default_reaction
- default_sort_order
- default_thread_slowmode_delay
- flags
- guild
- id
- jump_url
- last_thread
- last_thread_id
- members
- mention
- name
- nsfw
- overwrites
- permissions_synced
- position
- slowmode_delay
- threads
- topic
- type
- defarchived_threads
- asyncclone
- asynccreate_invite
- asynccreate_thread
- asynccreate_webhook
- asyncdelete
- asyncedit
- defget_tag
- defget_tag_by_name
- defget_thread
- defhides_media_download_options
- asyncinvites
- defis_nsfw
- asyncmove
- defoverwrites_for
- defpermissions_for
- defrequires_tag
- asyncset_permissions
- asynctrigger_typing
- deftyping
- asyncwebhooks
- class disnake.MediaChannel[source]¶
Represents a Discord guild media channel.
Media channels are very similar to forum channels - only threads can be created in them, with only minor differences in functionality.
New in version 2.10.
- x == y
Checks if two channels are equal.
- x != y
Checks if two channels are not equal.
- hash(x)
Returns the channel’s hash.
- str(x)
Returns the channel’s name.
- position¶
The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0.
- Type:
- nsfw¶
Whether the channel is marked as “not safe for work”.
Note
To check if the channel or the guild of that channel are marked as NSFW, consider
is_nsfw()instead.- Type:
- last_thread_id¶
The ID of the last created thread in this channel. It may not point to an existing or valid thread.
- default_auto_archive_duration¶
The default auto archive duration in minutes for threads created in this channel.
- Type:
- slowmode_delay¶
The number of seconds a member must wait between creating threads in this channel.
A value of
0denotes that it is disabled. Bots, and users withmanage_channelsormanage_messages, bypass slowmode.See also
default_thread_slowmode_delay.- Type:
- default_thread_slowmode_delay¶
The default number of seconds a member must wait between sending messages in newly created threads in this channel.
A value of
0denotes that it is disabled. Bots, and users withmanage_channelsormanage_messages, bypass slowmode.- Type:
- default_sort_order¶
The default sort order of threads in this channel. Members will still be able to change this locally.
- Type:
- async with typing()[source]¶
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.
Note
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!')
- property type[source]¶
The channel’s Discord type.
This always returns
ChannelType.media.- Type:
- hides_media_download_options()[source]¶
Whether the channel hides the embedded media download options.
This is a shortcut to
self.flags.hide_media_download_options.- Return type:
- await edit(*, name=..., topic=..., position=..., nsfw=..., sync_permissions=..., category=..., slowmode_delay=..., default_thread_slowmode_delay=..., default_auto_archive_duration=..., overwrites=..., flags=..., require_tag=..., available_tags=..., default_reaction=..., default_sort_order=..., reason=None, **kwargs)[source]¶
This function is a coroutine.
Edits the channel.
You must have
manage_channelspermission to do this.- Parameters:
name (
str) – The channel’s new name.position (
int) – The channel’s new position.nsfw (
bool) – Whether to mark the channel as NSFW.sync_permissions (
bool) – Whether to sync permissions with the channel’s new or pre-existing category. Defaults toFalse.category (
abc.Snowflake|None) – The new category for this channel. Can beNoneto remove the category.slowmode_delay (
int|None) – Specifies the slowmode rate limit at which users can create threads in this channel, in seconds. A value of0orNonedisables slowmode. The maximum value possible is21600.default_thread_slowmode_delay (
int|None) – Specifies the slowmode rate limit at which users can send messages in newly created threads in this channel, in seconds. This does not apply retroactively to existing threads. A value of0orNonedisables slowmode. The maximum value possible is21600.overwrites (
Mapping[Member|Role,PermissionOverwrite]) – AMappingof target (either a role or a member) toPermissionOverwriteto apply to the channel.default_auto_archive_duration (
int|ThreadArchiveDuration|None) – The new default auto archive duration in minutes for threads created in this channel. Must be one of60,1440,4320, or10080.flags (
ChannelFlags) – The new flags to set for this channel. This will overwrite any existing flags set on this channel. If parameterrequire_tagis provided, that will override the setting ofChannelFlags.require_tag.require_tag (
bool) – Whether all newly created threads are required to have a tag.available_tags (
Sequence[ForumTag]) –The new
ForumTags available for threads in this channel. Can be used to create new tags and edit/reorder/delete existing tags. Maximum of 20.Note that this overwrites all tags, removing existing tags unless they’re passed as well.
See
ForumTagfor examples regarding creating/editing tags.default_reaction (
str|Emoji|PartialEmoji|None) – The new default emoji shown for reacting to threads.default_sort_order (
ThreadSortOrder|None) – The new default sort order of threads in this channel.reason (
str|None) – The reason for editing this channel. Shows up on the audit log.
- Raises:
Forbidden – You do not have permissions to edit the channel.
HTTPException – Editing the channel failed.
TypeError – The permission overwrite information is not in proper form.
ValueError – The position is less than 0.
- Returns:
The newly edited media channel. If the edit was only positional then
Noneis returned instead.- Return type:
- await clone(*, name=None, topic=..., position=..., nsfw=..., category=..., slowmode_delay=..., default_thread_slowmode_delay=..., default_auto_archive_duration=..., available_tags=..., default_reaction=..., default_sort_order=..., overwrites=..., reason=None)[source]¶
This function is a coroutine.
Clones this channel. This creates a channel with the same properties as this channel.
You must have
Permissions.manage_channelspermission to do this.Note
The current
MediaChannel.flagsvalue won’t be cloned. This is a Discord limitation.- Parameters:
name (
str|None) – The name of the new channel. If not provided, defaults to this channel’s name.topic (
str|None) – The topic of the new channel. If not provided, defaults to this channel’s topic.position (
int) – The position of the new channel. If not provided, defaults to this channel’s position.nsfw (
bool) – Whether the new channel should be nsfw or not. If not provided, defaults to this channel’s NSFW value.category (
abc.Snowflake|None) – The category where the new channel should be grouped. If not provided, defaults to this channel’s category.slowmode_delay (
int|None) – The slowmode delay of the new channel. If not provided, defaults to this channel’s slowmode delay.default_thread_slowmode_delay (
int|None) – The default thread slowmode delay of the new channel. If not provided, defaults to this channel’s default thread slowmode delay.default_auto_archive_duration (
int|ThreadArchiveDuration|None) – The default auto archive duration of the new channel. If not provided, defaults to this channel’s default auto archive duration.available_tags (
Sequence[ForumTag]) – The applicable tags of the new channel. If not provided, defaults to this channel’s available tags.default_reaction (
str|Emoji|PartialEmoji|None) – The default reaction of the new channel. If not provided, defaults to this channel’s default reaction.default_sort_order (
ThreadSortOrder|None) – The default sort order of the new channel. If not provided, defaults to this channel’s default sort order.overwrites (
Mapping[Member|Role,PermissionOverwrite]) – AMappingof target (either a role or a member) toPermissionOverwriteto apply to the channel. If not provided, defaults to this channel’s overwrites.reason (
str|None) – The reason for cloning this channel. Shows up on the audit log.
- Raises:
Forbidden – You do not have the proper permissions to create this channel.
HTTPException – Creating the channel failed.
- Returns:
The channel that was created.
- Return type:
- archived_threads(*, limit=50, before=None)[source]¶
Returns an
AsyncIteratorthat iterates over all archived threads in the channel.You must have
read_message_historypermission to use this.- Parameters:
limit (
int|None) – The number of threads to retrieve. IfNone, retrieves every archived thread in the channel. Note, however, that this would make it a slow operation.before (
abc.Snowflake|datetime.datetime|None) – Retrieve archived channels before the given date or ID.
- Raises:
Forbidden – You do not have permissions to get archived threads.
HTTPException – The request to get the archived threads failed.
- Yields:
Thread– The archived threads.
- property available_tags[source]¶
The available tags for threads in this channel.
To create/edit/delete tags, use
edit().New in version 2.6.
- property category[source]¶
The category this channel belongs to.
If there is no category then this is
None.- Type:
- property changed_roles[source]¶
Returns a list of roles that have been overridden from their default values in the
Guild.rolesattribute.
- await create_invite(*, reason=None, max_age=0, max_uses=0, temporary=False, unique=True, target_type=None, target_user=None, target_application=None, guild_scheduled_event=None)[source]¶
This function is a coroutine.
Creates an instant invite from a text or voice channel.
You must have
Permissions.create_instant_invitepermission to do this.- Parameters:
max_age (
int) – How long the invite should last in seconds. If set to0, 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) – Whether the invite grants temporary membership (i.e. they get kicked after they disconnect). Defaults toFalse.unique (
bool) – Whether a unique invite URL should be created. Defaults toTrue. If this is set toFalsethen it will return a previously created invite.target_type (
InviteTarget|None) –The type of target for the voice channel invite, if any.
New in version 2.0.
The user whose stream to display for this invite, required if
target_typeisInviteTarget.stream. The user must be streaming in the channel.New in version 2.0.
target_application (
Snowflake|None) –The ID of the embedded application for the invite, required if
target_typeisInviteTarget.embedded_application.New in version 2.0.
Changed in version 2.9:
PartyTypeis deprecated, andSnowflakeshould be used instead.guild_scheduled_event (
GuildScheduledEvent|None) –The guild scheduled event to include with the invite.
New in version 2.3.
reason (
str|None) – The reason for creating this invite. Shows up on the audit log.
- Raises:
HTTPException – Invite creation failed.
NotFound – The channel that was passed is a category or an invalid channel.
- Returns:
The newly created invite.
- Return type:
- await create_thread(*, name, auto_archive_duration=..., slowmode_delay=..., applied_tags=..., content=..., embed=..., embeds=..., file=..., files=..., suppress_embeds=..., flags=..., stickers=..., allowed_mentions=..., view=..., components=..., reason=None)[source]¶
This function is a coroutine.
Creates a thread (with an initial message) in this channel.
You must have the
create_forum_threadspermission to do this.At least one of
content,embed/embeds,file/files,stickers,components, orviewmust be provided.Changed in version 2.6: Raises
TypeErrororValueErrorinstead ofInvalidArgument.Changed in version 2.6: The
contentparameter is no longer required.Note
Unlike
TextChannel.create_thread(), this returns a tuple with both the created thread and message.- Parameters:
name (
str) – The name of the thread.auto_archive_duration (
int|ThreadArchiveDuration) – The duration in minutes before the thread is automatically archived for inactivity. If not provided, the channel’s default auto archive duration is used. Must be one of60,1440,4320, or10080.slowmode_delay (
int|None) – Specifies the slowmode rate limit for users in this thread, in seconds. A value of0disables slowmode. The maximum value possible is21600. If set toNoneor not provided, slowmode is inherited from the parent’sdefault_thread_slowmode_delay.applied_tags (
Sequence[abc.Snowflake]) –The tags to apply to the new thread. Maximum of 5.
New in version 2.6.
content (
str) – The content of the message to send.embed (
Embed) – The rich embed for the content to send. This cannot be mixed with theembedsparameter.embeds (
list[Embed]) – A list of embeds to send with the content. Must be a maximum of 10. This cannot be mixed with theembedparameter.suppress_embeds (
bool) – Whether to suppress embeds for the message. This hides all the embeds from the UI if set toTrue.flags (
MessageFlags) –The flags to set for this message. Only
suppress_embedsandis_components_v2are supported.If parameter
suppress_embedsis provided, that will override the setting ofMessageFlags.suppress_embeds.New in version 2.9.
file (
File) – The file to upload. This cannot be mixed with thefilesparameter.files (
list[File]) – A list of files to upload. Must be a maximum of 10. This cannot be mixed with thefileparameter.stickers (
Sequence[GuildSticker|StandardSticker|StickerItem]) – A list of stickers to upload. Must be a maximum of 3.allowed_mentions (
AllowedMentions) – Controls the mentions being processed in this message. If this is passed, then the object is merged withClient.allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set inClient.allowed_mentions. If no object is passed at all then the defaults given byClient.allowed_mentionsare used instead.view (
ui.View) – A Discord UI View to add to the message. This cannot be mixed withcomponents.components (
UIComponent|list[UIComponent|list[WrappedComponent]]) –A list of components to include in the message. This cannot be mixed with
view.Note
Passing v2 components here automatically sets the
is_components_v2flag. Setting this flag cannot be reverted. Note that this also disables thecontent,embeds, andstickersfields.reason (
str|None) – The reason for creating the thread. Shows up on the audit log.
- Raises:
Forbidden – You do not have permissions to create a thread.
HTTPException – Starting the thread failed.
TypeError – Specified both
fileandfiles, or you specified bothembedandembeds, or you specified bothviewandcomponents, or you have passed an object that is notFiletofileorfiles.ValueError – Specified more than 10 embeds, or more than 10 files, or you tried to send v2 components together with
content,embeds, orstickers.
- Returns:
A
NamedTuplewith the newly created thread and the message sent in it.- Return type:
- await create_webhook(*, name, avatar=None, reason=None)[source]¶
This function is a coroutine.
Creates a webhook for this channel.
You must have
manage_webhookspermission to do this.New in version 2.6.
- Parameters:
- Raises:
NotFound – The
avatarasset couldn’t be found.Forbidden – You do not have permissions to create a webhook.
HTTPException – Creating the webhook failed.
TypeError – The
avatarasset is a lottie sticker (seeSticker.read()).
- Returns:
The newly created webhook.
- Return type:
- property default_reaction[source]¶
Emoji|PartialEmoji|None: The default emoji shown for reacting to threads.Due to a Discord limitation, this will have an empty
nameif it is a customPartialEmoji.New in version 2.6.
- await delete(*, reason=None)[source]¶
This function is a coroutine.
Deletes the channel.
You must have
Permissions.manage_channelspermission to do this.- Parameters:
reason (
str|None) – 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.
- get_tag_by_name(name, /)[source]¶
Returns a thread tag with the given name.
Tags can be uniquely identified based on the name, as tag names in a channel must be unique.
New in version 2.6.
- await invites()[source]¶
This function is a coroutine.
Returns a list of all active instant invites from this channel.
You must have
Permissions.manage_channelspermission to use this.- Raises:
Forbidden – You do not have proper permissions to get the information.
HTTPException – An error occurred while fetching the information.
- Returns:
The list of invites that are currently active.
- Return type:
- property jump_url[source]¶
A URL that can be used to jump to this channel.
New in version 2.4.
Note
This exists for all guild channels but may not be usable by the client for all guild channel types.
- property last_thread[source]¶
Gets the last created thread in this channel from the cache.
The thread might not be valid or point to an existing thread.
Reliable Fetching
For a slightly more reliable method of fetching the last thread, use
Guild.fetch_channel()with thelast_thread_idattribute.
- await move(**kwargs)[source]¶
This function is a coroutine.
A rich interface to help move a channel relative to other channels.
If exact position movement is required,
editshould be used instead.You must have
Permissions.manage_channelspermission to do this.Note
Voice channels will always be sorted below text channels. This is a Discord limitation.
New in version 1.7.
Changed in version 2.6: Raises
TypeErrororValueErrorinstead ofInvalidArgument.- Parameters:
beginning (
bool) – Whether to move the channel to the beginning of the channel list (or category if given). This is mutually exclusive withend,before, andafter.end (
bool) – Whether to move the channel to the end of the channel list (or category if given). This is mutually exclusive withbeginning,before, andafter.before (
abc.Snowflake) – The channel that should be before our current channel. This is mutually exclusive withbeginning,end, andafter.after (
abc.Snowflake) – The channel that should be after our current channel. This is mutually exclusive withbeginning,end, andbefore.offset (
int) – The number of channels to offset the move by. For example, an offset of2withbeginning=Truewould move it 2 after the beginning. A positive number moves it below while a negative number moves it above. Note that this number is relative and computed after thebeginning,end,before, andafterparameters.category (
abc.Snowflake|None) – The category to move this channel under. IfNoneis given then it moves it out of the category. This parameter is ignored if moving a category channel.sync_permissions (
bool) – Whether to sync the permissions with the category (if given).reason (
str|None) – The reason for moving this channel. Shows up on the audit log.
- Raises:
Forbidden – You do not have permissions to move the channel.
HTTPException – Moving the channel failed.
TypeError – A bad mix of arguments were passed.
ValueError – An invalid position was given.
- property overwrites[source]¶
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:
- overwrites_for(obj)[source]¶
Returns the channel-specific overwrites for a member or a role.
- permissions_for(obj, /, *, ignore_timeout=...)[source]¶
Handles permission resolution for the
MemberorRole.This function takes into consideration the following cases:
Guild owner
Guild roles
Channel overrides
Member overrides
Timeouts
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
Note
If the channel originated from an
Interactionand theguildattribute is unavailable, such as with user-installed applications in guilds, this method will not work due to an API limitation. Consider usingInteraction.permissionsorapp_permissionsinstead.Changed in version 2.0: The object passed in can now be a role object.
- Parameters:
obj (
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.ignore_timeout (
bool) –Whether or not to ignore the user’s timeout. Defaults to
False.New in version 2.4.
Note
This only applies to
Memberobjects.Changed in version 2.6: The default was changed to
False.
- Raises:
TypeError –
ignore_timeoutis only supported forMemberobjects.- Returns:
The resolved permissions for the member or role.
- Return type:
- property permissions_synced[source]¶
Whether or not the permissions for this channel are synced with the category it belongs to.
If there is no category then this is
False.New in version 1.3.
- Type:
- requires_tag()[source]¶
Whether all newly created threads in this channel are required to have a tag.
This is a shortcut to
self.flags.require_tag.New in version 2.6.
- Return type:
- await set_permissions(target, *, overwrite=..., reason=None, **permissions)[source]¶
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
Permissions.manage_rolespermission to do this.Note
This method replaces the old overwrites with the ones given.
Changed in version 2.6: Raises
TypeErrorinstead ofInvalidArgument.Examples
Setting allow and deny:
await message.channel.set_permissions(message.author, view_channel=True, send_messages=False)
Deleting overwrites
await channel.set_permissions(member, overwrite=None)
Using
PermissionOverwriteoverwrite = disnake.PermissionOverwrite() overwrite.send_messages = False overwrite.view_channel = True await channel.set_permissions(member, overwrite=overwrite)
- Parameters:
target (
Member|Role) – The member or role to overwrite permissions for.overwrite (
PermissionOverwrite|None) – The permissions to allow and deny to the target, orNoneto delete the overwrite.**permissions – A keyword argument list of permissions to set for ease of use. Cannot be mixed with
overwrite.reason (
str|None) – 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.
TypeError –
overwriteis invalid, the target type was notRoleorMember, both keyword arguments andoverwritewere provided, or invalid permissions were provided as keyword arguments.
- await trigger_typing()[source]¶
This function is a coroutine.
Triggers a typing indicator to the destination.
Typing indicator will go away after 10 seconds.
- await webhooks()[source]¶
This function is a coroutine.
Retrieves the list of webhooks this channel has.
You must have
manage_webhookspermission to use this.New in version 2.6.
DMChannel¶
- asyncfetch_message
- defget_partial_message
- defhistory
- defpermissions_for
- defpins
- asyncsend
- asynctrigger_typing
- deftyping
- class disnake.DMChannel[source]¶
Represents a Discord direct message channel.
- x == y
Checks if two channels are equal.
- x != y
Checks if two channels are not equal.
- hash(x)
Returns the channel’s hash.
- str(x)
Returns a string representation of the channel
- recipient¶
The user you are participating with in the direct message channel. If this channel is received through the gateway, the recipient information may not be always available.
- me¶
The user presenting yourself.
- Type:
- last_pin_timestamp¶
The time the most recent message was pinned, or
Noneif no message is currently pinned.New in version 2.5.
- Type:
- async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)[source]¶
Returns an
AsyncIteratorthat enables receiving the destination’s message history.You must have
Permissions.read_message_historypermission to use this.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.
- Parameters:
limit (
int|None) – The number of messages to retrieve. IfNone, retrieves every message in the channel. Note, however, that this would make it a slow operation.before (
abc.Snowflake|datetime.datetime|None) – 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 (
abc.Snowflake|datetime.datetime|None) – 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 (
abc.Snowflake|datetime.datetime|None) – 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 (
bool|None) – If set toTrue, return messages in oldest->newest order. Defaults toTrueifafteris specified, otherwiseFalse.
- Raises:
Forbidden – You do not have permissions to get channel message history.
HTTPException – The request to get message history failed.
- Yields:
Message– The message with the message data parsed.
- async with typing()[source]¶
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.
Note
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!')
- property type[source]¶
The channel’s Discord type.
This always returns
ChannelType.private.- Type:
- await fetch_message(id, /)[source]¶
This function is a coroutine.
Retrieves a single
Messagefrom the destination.- Parameters:
id (
int) – The message ID to look for.- 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.
- Returns:
The message asked for.
- Return type:
- pins(*, limit=50, before=None)[source]¶
Returns an
AsyncIteratorthat enables receiving the destination’s pinned messages.You must have the
Permissions.read_message_historyandPermissions.view_channelpermissions to use this.Note
Due to a limitation with the Discord API, the
Messageobjects returned by this method do not contain completeMessage.reactionsdata.Changed in version 2.11: Now returns an
AsyncIteratorto support changes in Discord’s API.awaiting the result of this method remains supported, but only returns the last 50 pins and is deprecated in favor ofasync for msg in channel.pins().Examples
Usage
counter = 0 async for message in channel.pins(limit=100): if message.author == client.user: counter += 1
Flattening to a list
pinned_messages = await channel.pins(limit=100).flatten() # pinned_messages is now a list of Message...
All parameters are optional.
- Parameters:
limit (
int|None) – The number of pinned messages to retrieve. IfNone, retrieves every pinned message in the channel. Note, however, that this would make it a slow operation.before (
abc.Snowflake|datetime.datetime|None) – Retrieve messages pinned 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.
- Raises:
HTTPException – Retrieving the pinned messages failed.
- Yields:
Message– The pinned message from the parsed message data.
- await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, suppress_embeds=None, flags=None, allowed_mentions=None, reference=None, mention_author=None, view=None, components=None, poll=None)[source]¶
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).At least one of
content,embed/embeds,file/files,stickers,components,pollorviewmust 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.Changed in version 2.6: Raises
TypeErrororValueErrorinstead ofInvalidArgument.- Parameters:
tts (
bool) – Whether the message should be sent using text-to-speech.embed (
Embed) – The rich embed for the content to send. This cannot be mixed with theembedsparameter.A list of embeds to send with the content. Must be a maximum of 10. This cannot be mixed with the
embedparameter.New in version 2.0.
file (
File) – The file to upload. This cannot be mixed with thefilesparameter.files (
list[File]) – A list of files to upload. Must be a maximum of 10. This cannot be mixed with thefileparameter.stickers (
Sequence[GuildSticker|StandardSticker|StickerItem]) –A list of stickers to upload. Must be a maximum of 3.
New in version 2.0.
nonce (
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.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
Client.allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set inClient.allowed_mentions. If no object is passed at all then the defaults given byClient.allowed_mentionsare used instead.New in version 1.4.
reference (
Message|MessageReference|PartialMessage) –A reference to the
Messageto which you are replying, this can be created usingMessage.to_reference()or passed directly as aMessage. You can control whether this mentions the author of the referenced message using theAllowedMentions.replied_userattribute ofallowed_mentionsor by settingmention_author.New in version 1.6.
Note
Passing a
MessageorPartialMessagewill only allow replies. To forward a message you must explicitly transform the message to aMessageReferenceusingMessage.to_reference()and specify theMessageReferenceType, or useMessage.forward().mention_author (
bool|None) –If set, overrides the
AllowedMentions.replied_userattribute ofallowed_mentions.New in version 1.6.
view (
ui.View) –A Discord UI View to add to the message. This cannot be mixed with
components.New in version 2.0.
components (
UIComponent|list[UIComponent|list[WrappedComponent]]) –A list of components to include in the message. This cannot be mixed with
view.New in version 2.4.
Note
Passing v2 components here automatically sets the
is_components_v2flag. Setting this flag cannot be reverted. Note that this also disables thecontent,embeds,stickers, andpollfields.suppress_embeds (
bool) –Whether to suppress embeds for the message. This hides all the embeds from the UI if set to
True.New in version 2.5.
flags (
MessageFlags) –The flags to set for this message. Only
suppress_embeds,suppress_notifications, andis_components_v2are supported.If parameter
suppress_embedsis provided, that will override the setting ofMessageFlags.suppress_embeds.New in version 2.9.
poll (
Poll) –The poll to send with the message.
New in version 2.10.
- Raises:
HTTPException – Sending the message failed.
Forbidden – You do not have the proper permissions to send the message.
TypeError – Specified both
fileandfiles, or you specified bothembedandembeds, or you specified bothviewandcomponents, or thereferenceobject is not aMessage,MessageReferenceorPartialMessage.ValueError – The
filesorembedslist is too large, or you tried to send v2 components together withcontent,embeds,stickers, orpoll.
- Returns:
The message that was sent.
- Return type:
- await trigger_typing()[source]¶
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.
- permissions_for(obj=None, /, *, ignore_timeout=...)[source]¶
Handles permission resolution for a
User.This function is there for compatibility with other channel types.
Actual direct messages do not really have the concept of permissions.
This returns all the
Permissions.private_channel()permissions set toTrue.- Parameters:
obj (
User) – The user to check permissions for. This parameter is ignored but kept for compatibility with otherpermissions_formethods.ignore_timeout (
bool) – Whether to ignore the guild timeout when checking permsisions. This parameter is ignored but kept for compatibility with otherpermissions_formethods.
- Returns:
The resolved permissions.
- Return type:
- get_partial_message(message_id, /)[source]¶
Creates a
PartialMessagefrom the given message ID.This is useful if you want to work with a message and only have its ID without doing an unnecessary API call.
New in version 1.6.
- Parameters:
message_id (
int) – The message ID to create a partial message for.- Returns:
The partial message object.
- Return type:
GroupChannel¶
- asyncfetch_message
- defget_partial_message
- defhistory
- asyncleave
- defpermissions_for
- defpins
- asyncsend
- asynctrigger_typing
- deftyping
- class disnake.GroupChannel[source]¶
Represents a Discord group channel.
- x == y
Checks if two channels are equal.
- x != y
Checks if two channels are not equal.
- hash(x)
Returns the channel’s hash.
- str(x)
Returns a string representation of the channel
- recipients¶
The users you are participating with in the group channel. If this channel is received through the gateway, the recipient information may not be always available.
- me¶
The user representing yourself.
- Type:
- async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)[source]¶
Returns an
AsyncIteratorthat enables receiving the destination’s message history.You must have
Permissions.read_message_historypermission to use this.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.
- Parameters:
limit (
int|None) – The number of messages to retrieve. IfNone, retrieves every message in the channel. Note, however, that this would make it a slow operation.before (
abc.Snowflake|datetime.datetime|None) – 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 (
abc.Snowflake|datetime.datetime|None) – 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 (
abc.Snowflake|datetime.datetime|None) – 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 (
bool|None) – If set toTrue, return messages in oldest->newest order. Defaults toTrueifafteris specified, otherwiseFalse.
- Raises:
Forbidden – You do not have permissions to get channel message history.
HTTPException – The request to get message history failed.
- Yields:
Message– The message with the message data parsed.
- async with typing()[source]¶
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.
Note
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 fetch_message(id, /)[source]¶
This function is a coroutine.
Retrieves a single
Messagefrom the destination.- Parameters:
id (
int) – The message ID to look for.- 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.
- Returns:
The message asked for.
- Return type:
- pins(*, limit=50, before=None)[source]¶
Returns an
AsyncIteratorthat enables receiving the destination’s pinned messages.You must have the
Permissions.read_message_historyandPermissions.view_channelpermissions to use this.Note
Due to a limitation with the Discord API, the
Messageobjects returned by this method do not contain completeMessage.reactionsdata.Changed in version 2.11: Now returns an
AsyncIteratorto support changes in Discord’s API.awaiting the result of this method remains supported, but only returns the last 50 pins and is deprecated in favor ofasync for msg in channel.pins().Examples
Usage
counter = 0 async for message in channel.pins(limit=100): if message.author == client.user: counter += 1
Flattening to a list
pinned_messages = await channel.pins(limit=100).flatten() # pinned_messages is now a list of Message...
All parameters are optional.
- Parameters:
limit (
int|None) – The number of pinned messages to retrieve. IfNone, retrieves every pinned message in the channel. Note, however, that this would make it a slow operation.before (
abc.Snowflake|datetime.datetime|None) – Retrieve messages pinned 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.
- Raises:
HTTPException – Retrieving the pinned messages failed.
- Yields:
Message– The pinned message from the parsed message data.
- await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, suppress_embeds=None, flags=None, allowed_mentions=None, reference=None, mention_author=None, view=None, components=None, poll=None)[source]¶
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).At least one of
content,embed/embeds,file/files,stickers,components,pollorviewmust 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.Changed in version 2.6: Raises
TypeErrororValueErrorinstead ofInvalidArgument.- Parameters:
tts (
bool) – Whether the message should be sent using text-to-speech.embed (
Embed) – The rich embed for the content to send. This cannot be mixed with theembedsparameter.A list of embeds to send with the content. Must be a maximum of 10. This cannot be mixed with the
embedparameter.New in version 2.0.
file (
File) – The file to upload. This cannot be mixed with thefilesparameter.files (
list[File]) – A list of files to upload. Must be a maximum of 10. This cannot be mixed with thefileparameter.stickers (
Sequence[GuildSticker|StandardSticker|StickerItem]) –A list of stickers to upload. Must be a maximum of 3.
New in version 2.0.
nonce (
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.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
Client.allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set inClient.allowed_mentions. If no object is passed at all then the defaults given byClient.allowed_mentionsare used instead.New in version 1.4.
reference (
Message|MessageReference|PartialMessage) –A reference to the
Messageto which you are replying, this can be created usingMessage.to_reference()or passed directly as aMessage. You can control whether this mentions the author of the referenced message using theAllowedMentions.replied_userattribute ofallowed_mentionsor by settingmention_author.New in version 1.6.
Note
Passing a
MessageorPartialMessagewill only allow replies. To forward a message you must explicitly transform the message to aMessageReferenceusingMessage.to_reference()and specify theMessageReferenceType, or useMessage.forward().mention_author (
bool|None) –If set, overrides the
AllowedMentions.replied_userattribute ofallowed_mentions.New in version 1.6.
view (
ui.View) –A Discord UI View to add to the message. This cannot be mixed with
components.New in version 2.0.
components (
UIComponent|list[UIComponent|list[WrappedComponent]]) –A list of components to include in the message. This cannot be mixed with
view.New in version 2.4.
Note
Passing v2 components here automatically sets the
is_components_v2flag. Setting this flag cannot be reverted. Note that this also disables thecontent,embeds,stickers, andpollfields.suppress_embeds (
bool) –Whether to suppress embeds for the message. This hides all the embeds from the UI if set to
True.New in version 2.5.
flags (
MessageFlags) –The flags to set for this message. Only
suppress_embeds,suppress_notifications, andis_components_v2are supported.If parameter
suppress_embedsis provided, that will override the setting ofMessageFlags.suppress_embeds.New in version 2.9.
poll (
Poll) –The poll to send with the message.
New in version 2.10.
- Raises:
HTTPException – Sending the message failed.
Forbidden – You do not have the proper permissions to send the message.
TypeError – Specified both
fileandfiles, or you specified bothembedandembeds, or you specified bothviewandcomponents, or thereferenceobject is not aMessage,MessageReferenceorPartialMessage.ValueError – The
filesorembedslist is too large, or you tried to send v2 components together withcontent,embeds,stickers, orpoll.
- Returns:
The message that was sent.
- Return type:
- await trigger_typing()[source]¶
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.
- property type[source]¶
The channel’s Discord type.
This always returns
ChannelType.group.- Type:
- permissions_for(obj, /, *, ignore_timeout=...)[source]¶
Handles permission resolution for a
User.This function is there for compatibility with other channel types.
Actual direct messages do not really have the concept of permissions.
This returns all the
Permissions.private_channel()permissions set toTrue.This also checks the kick_members permission if the user is the owner.
- Parameters:
- Returns:
The resolved permissions for the user.
- Return type:
- get_partial_message(message_id, /)[source]¶
Creates a
PartialMessagefrom the given message ID.This is useful if you want to work with a message and only have its ID without doing an unnecessary API call.
New in version 2.10.
- Parameters:
message_id (
int) – The message ID to create a partial message for.- Returns:
The partial message object.
- Return type:
- await leave()[source]¶
This function is a coroutine.
Leaves the group.
If you are the only one in the group, this deletes it as well.
- Raises:
HTTPException – Leaving the group failed.
RawThreadDeleteEvent¶
- class disnake.RawThreadDeleteEvent[source]¶
Represents the payload for a
on_raw_thread_delete()event.New in version 2.5.
- thread_type¶
The type of the deleted thread.
- Type:
RawThreadMemberRemoveEvent¶
- class disnake.RawThreadMemberRemoveEvent[source]¶
Represents the event payload for an
on_raw_thread_member_remove()event.New in version 2.5.
- cached_member¶
The member, if they could be found in the internal cache.
- Type:
Data Classes¶
PartialMessageable¶
- asyncfetch_message
- defget_partial_message
- defhistory
- defpins
- asyncsend
- asynctrigger_typing
- deftyping
- class disnake.PartialMessageable[source]¶
Represents a partial messageable to aid with working messageable channels when only a channel ID is present.
The only way to construct this class is through
Client.get_partial_messageable().Note that this class is trimmed down and has no rich attributes.
New in version 2.0.
- x == y
Checks if two partial messageables are equal.
- x != y
Checks if two partial messageables are not equal.
- hash(x)
Returns the partial messageable’s hash.
- type¶
The channel type associated with this partial messageable, if given.
- Type:
- await fetch_message(id, /)[source]¶
This function is a coroutine.
Retrieves a single
Messagefrom the destination.- Parameters:
id (
int) – The message ID to look for.- 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.
- Returns:
The message asked for.
- Return type:
- history(*, limit=100, before=None, after=None, around=None, oldest_first=None)[source]¶
Returns an
AsyncIteratorthat enables receiving the destination’s message history.You must have
Permissions.read_message_historypermission to use this.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.
- Parameters:
limit (
int|None) – The number of messages to retrieve. IfNone, retrieves every message in the channel. Note, however, that this would make it a slow operation.before (
abc.Snowflake|datetime.datetime|None) – 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 (
abc.Snowflake|datetime.datetime|None) – 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 (
abc.Snowflake|datetime.datetime|None) – 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 (
bool|None) – If set toTrue, return messages in oldest->newest order. Defaults toTrueifafteris specified, otherwiseFalse.
- Raises:
Forbidden – You do not have permissions to get channel message history.
HTTPException – The request to get message history failed.
- Yields:
Message– The message with the message data parsed.
- pins(*, limit=50, before=None)[source]¶
Returns an
AsyncIteratorthat enables receiving the destination’s pinned messages.You must have the
Permissions.read_message_historyandPermissions.view_channelpermissions to use this.Note
Due to a limitation with the Discord API, the
Messageobjects returned by this method do not contain completeMessage.reactionsdata.Changed in version 2.11: Now returns an
AsyncIteratorto support changes in Discord’s API.awaiting the result of this method remains supported, but only returns the last 50 pins and is deprecated in favor ofasync for msg in channel.pins().Examples
Usage
counter = 0 async for message in channel.pins(limit=100): if message.author == client.user: counter += 1
Flattening to a list
pinned_messages = await channel.pins(limit=100).flatten() # pinned_messages is now a list of Message...
All parameters are optional.
- Parameters:
limit (
int|None) – The number of pinned messages to retrieve. IfNone, retrieves every pinned message in the channel. Note, however, that this would make it a slow operation.before (
abc.Snowflake|datetime.datetime|None) – Retrieve messages pinned 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.
- Raises:
HTTPException – Retrieving the pinned messages failed.
- Yields:
Message– The pinned message from the parsed message data.
- await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, suppress_embeds=None, flags=None, allowed_mentions=None, reference=None, mention_author=None, view=None, components=None, poll=None)[source]¶
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).At least one of
content,embed/embeds,file/files,stickers,components,pollorviewmust 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.Changed in version 2.6: Raises
TypeErrororValueErrorinstead ofInvalidArgument.- Parameters:
tts (
bool) – Whether the message should be sent using text-to-speech.embed (
Embed) – The rich embed for the content to send. This cannot be mixed with theembedsparameter.A list of embeds to send with the content. Must be a maximum of 10. This cannot be mixed with the
embedparameter.New in version 2.0.
file (
File) – The file to upload. This cannot be mixed with thefilesparameter.files (
list[File]) – A list of files to upload. Must be a maximum of 10. This cannot be mixed with thefileparameter.stickers (
Sequence[GuildSticker|StandardSticker|StickerItem]) –A list of stickers to upload. Must be a maximum of 3.
New in version 2.0.
nonce (
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.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
Client.allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set inClient.allowed_mentions. If no object is passed at all then the defaults given byClient.allowed_mentionsare used instead.New in version 1.4.
reference (
Message|MessageReference|PartialMessage) –A reference to the
Messageto which you are replying, this can be created usingMessage.to_reference()or passed directly as aMessage. You can control whether this mentions the author of the referenced message using theAllowedMentions.replied_userattribute ofallowed_mentionsor by settingmention_author.New in version 1.6.
Note
Passing a
MessageorPartialMessagewill only allow replies. To forward a message you must explicitly transform the message to aMessageReferenceusingMessage.to_reference()and specify theMessageReferenceType, or useMessage.forward().mention_author (
bool|None) –If set, overrides the
AllowedMentions.replied_userattribute ofallowed_mentions.New in version 1.6.
view (
ui.View) –A Discord UI View to add to the message. This cannot be mixed with
components.New in version 2.0.
components (
UIComponent|list[UIComponent|list[WrappedComponent]]) –A list of components to include in the message. This cannot be mixed with
view.New in version 2.4.
Note
Passing v2 components here automatically sets the
is_components_v2flag. Setting this flag cannot be reverted. Note that this also disables thecontent,embeds,stickers, andpollfields.suppress_embeds (
bool) –Whether to suppress embeds for the message. This hides all the embeds from the UI if set to
True.New in version 2.5.
flags (
MessageFlags) –The flags to set for this message. Only
suppress_embeds,suppress_notifications, andis_components_v2are supported.If parameter
suppress_embedsis provided, that will override the setting ofMessageFlags.suppress_embeds.New in version 2.9.
poll (
Poll) –The poll to send with the message.
New in version 2.10.
- Raises:
HTTPException – Sending the message failed.
Forbidden – You do not have the proper permissions to send the message.
TypeError – Specified both
fileandfiles, or you specified bothembedandembeds, or you specified bothviewandcomponents, or thereferenceobject is not aMessage,MessageReferenceorPartialMessage.ValueError – The
filesorembedslist is too large, or you tried to send v2 components together withcontent,embeds,stickers, orpoll.
- Returns:
The message that was sent.
- Return type:
- await trigger_typing()[source]¶
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.
- typing()[source]¶
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.
Note
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!')
- get_partial_message(message_id, /)[source]¶
Creates a
PartialMessagefrom the given message ID.This is useful if you want to work with a message and only have its ID without doing an unnecessary API call.
- Parameters:
message_id (
int) – The message ID to create a partial message for.- Returns:
The partial message object.
- Return type:
ChannelFlags¶
- class disnake.ChannelFlags(**kwargs)[source]¶
Wraps up the Discord Channel flags.
- x == y
Checks if two ChannelFlags instances are equal.
- x != y
Checks if two ChannelFlags instances are not equal.
- x <= y
Checks if a ChannelFlags instance is a subset of another ChannelFlags instance.
New in version 2.6.
- x >= y
Checks if a ChannelFlags instance is a superset of another ChannelFlags instance.
New in version 2.6.
- x < y
Checks if a ChannelFlags instance is a strict subset of another ChannelFlags instance.
New in version 2.6.
- x > y
Checks if a ChannelFlags instance is a strict superset of another ChannelFlags instance.
New in version 2.6.
- x | y, x |= y
Returns a new ChannelFlags instance with all enabled flags from both x and y. (Using
|=will update in place).New in version 2.6.
- x & y, x &= y
Returns a new ChannelFlags instance with only flags enabled on both x and y. (Using
&=will update in place).New in version 2.6.
- x ^ y, x ^= y
Returns a new ChannelFlags instance with only flags enabled on one of x or y, but not both. (Using
^=will update in place).New in version 2.6.
- ~x
Returns a new ChannelFlags instance with all flags from x inverted.
New in version 2.6.
- hash(x)
Return the flag’s hash.
- iter(x)
Returns an iterator of
(name, value)pairs. This allows it to be, for example, constructed as a dict or a list of pairs. Note that aliases are not shown.
Additionally supported are a few operations on class attributes.
- ChannelFlags.y | ChannelFlags.z, ChannelFlags(y=True) | ChannelFlags.z
Returns a ChannelFlags instance with all provided flags enabled.
New in version 2.6.
- ~ChannelFlags.y
Returns a ChannelFlags instance with all flags except
yinverted from their default value.New in version 2.6.
New in version 2.5.
- value¶
The raw value. You should query flags via the properties rather than using this raw value.
- Type:
- pinned¶
Returns
Trueif the thread is pinned.This only applies to threads that are part of a
ForumChannelorMediaChannel.- Type:
- require_tag¶
Returns
Trueif the channel requires all newly created threads to have a tag.This only applies to channels of types
ForumChannelorMediaChannel.New in version 2.6.
- Type:
- hide_media_download_options¶
Returns
Trueif the channel hides the embedded media download options.This only applies to channels of type
MediaChannel.New in version 2.10.
- Type:
ForumTag¶
- defwith_changes
- class disnake.ForumTag[source]¶
Represents a tag for threads in forum/media channels.
- x == y
Checks if two tags are equal.
- x != y
Checks if two tags are not equal.
- hash(x)
Returns the tag’s hash.
- str(x)
Returns the tag’s name.
New in version 2.6.
Examples
Creating a new tag:
tags = forum.available_tags tags.append(ForumTag(name="cool new tag", moderated=True)) await forum.edit(available_tags=tags)
Editing an existing tag:
tags = [] for tag in forum.available_tags: if tag.id == 1234: tag = tag.with_changes(name="whoa new name") tags.append(tag) await forum.edit(available_tags=tags)
- moderated¶
Whether only moderators can add this tag to threads or remove it. Defaults to
False.- Type:
- emoji¶
The emoji associated with this tag, if any. Due to a Discord limitation, this will have an empty
nameif it is a customPartialEmoji.- Type:
Emoji|PartialEmoji|None
- with_changes(*, name=..., emoji=..., moderated=...)[source]¶
Returns a new instance with the given changes applied, for easy use with
ForumChannel.edit()orMediaChannel.edit(). All other fields will be kept intact.- Returns:
The new tag instance.
- Return type:
ThreadWithMessage¶
- class disnake.ThreadWithMessage[source]¶
A
NamedTuplewhich represents a thread and message returned fromForumChannel.create_thread().
Enumerations¶
ChannelType¶
- class disnake.ChannelType[source]¶
Specifies the type of channel.
- text¶
A text channel.
- private¶
A private text channel. Also called a direct message.
- voice¶
A voice channel.
- group¶
A private group text channel.
- category¶
A category channel.
- news¶
A guild news channel.
- news_thread¶
A news thread.
New in version 2.0.
- public_thread¶
A public thread.
New in version 2.0.
- private_thread¶
A private thread.
New in version 2.0.
- stage_voice¶
A guild stage voice channel.
New in version 1.7.
- guild_directory¶
A student hub channel.
New in version 2.1.
- forum¶
A channel of only threads.
New in version 2.5.
- media¶
A channel of only threads but with a focus on media, similar to forum channels.
New in version 2.10.
ThreadArchiveDuration¶
- class disnake.ThreadArchiveDuration[source]¶
Represents the automatic archive duration of a thread in minutes.
New in version 2.3.
- hour¶
The thread will archive after an hour of inactivity.
- day¶
The thread will archive after a day of inactivity.
- three_days¶
The thread will archive after three days of inactivity.
- week¶
The thread will archive after a week of inactivity.
VideoQualityMode¶
ThreadSortOrder¶
- class disnake.ThreadSortOrder[source]¶
Represents the sort order of threads in a
ForumChannelorMediaChannel.New in version 2.6.
- latest_activity¶
Sort forum threads by activity.
- creation_date¶
Sort forum threads by creation date/time (from newest to oldest).