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
- asyncpins
- asyncpurge
- asyncsend
- asyncset_permissions
- asynctrigger_typing
- deftyping
- asyncwebhooks
- class disnake.TextChannel[source]¶
This class is a Discord Model.
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.
- Type:
Optional[
int]
- 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.- 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:
Optional[
datetime.datetime]
- 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 (Optional[
int]) – The number of messages to retrieve. IfNone, retrieves every message in the channel. Note, however, that this would make it a slow operation.before (Optional[Union[
abc.Snowflake,datetime.datetime]]) – Retrieve messages before this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.after (Optional[Union[
abc.Snowflake,datetime.datetime]]) – Retrieve messages after this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.around (Optional[Union[
abc.Snowflake,datetime.datetime]]) – Retrieve messages around this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time. When using this argument, the maximum limit is 101. Note that if the limit is an even number then this will return at most limit + 1 messages.oldest_first (Optional[
bool]) – If set toTrue, return messages in oldest->newest order. Defaults toTrueifafteris specified, otherwiseFalse.
- 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
Changed in version 2.0: The object passed in can now be a role object.
- Parameters:
obj (Union[
Member,Role]) – The object to resolve permissions for. This could be either a member or a role. If it’s a role then member overwrites are not computed.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 threads[source]¶
Returns all the threads that you can see.
New in version 2.0.
- Type:
List[
Thread]
- 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.- Returns:
The last message in this channel or
Noneif not found.- Return type:
Optional[
Message]
- await edit(*, name=..., topic=..., position=..., nsfw=..., sync_permissions=..., category=..., 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.topic (Optional[
str]) – The new channel’s topic.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 (Optional[
abc.Snowflake]) – The new category for this channel. Can beNoneto remove the category.slowmode_delay (Optional[
int]) – Specifies the slowmode rate limit for users in this channel, in seconds. A value of0disables slowmode. The maximum value possible is21600.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) – AMappingof target (either a role or a member) toPermissionOverwriteto apply to the channel.default_auto_archive_duration (Optional[Union[
int,ThreadArchiveDuration]]) – 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 (Optional[
str]) – 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:
Optional[
TextChannel]
- await clone(*, name=None, 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.New in version 1.1.
- Parameters:
- 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 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 (Optional[
int]) – The number of messages to search through. This is not the number of messages that will be deleted, though it can be.check (Callable[[
Message],bool]) – The function used to check if a message should be deleted. It must take aMessageas its sole parameter.before (Optional[Union[
abc.Snowflake,datetime.datetime]]) – Same asbeforeinhistory().after (Optional[Union[
abc.Snowflake,datetime.datetime]]) – Same asafterinhistory().around (Optional[Union[
abc.Snowflake,datetime.datetime]]) – Same asaroundinhistory().oldest_first (Optional[
bool]) – Same asoldest_firstinhistory().bulk (
bool) – IfTrue, use bulk delete. Setting this toFalseis useful for mass-deleting a bot’s own messages withoutPermissions.manage_messages. WhenTrue, will fall back to single delete if messages are older than two weeks.
- 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:
List[
Message]
- 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 (Optional[Union[
bytes,Asset,Emoji,PartialEmoji,StickerItem,Sticker]]) –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 (Optional[
str]) – 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.reason (Optional[
str]) –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. Additionally, the guild must havePRIVATE_THREADSinGuild.featuresto create private threads.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 (Union[
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.
slowmode_delay (
int) –Specifies the slowmode rate limit for users in this thread, in seconds. A value of
0disables slowmode. The maximum value possible is21600. If not provided, slowmode is disabled.New in version 2.3.
reason (Optional[
str]) – 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 (Optional[
int]) – 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 (Optional[Union[
abc.Snowflake,datetime.datetime]]) – 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:
Optional[
CategoryChannel]
- property changed_roles[source]¶
Returns a list of roles that have been overridden from their default values in the
Guild.rolesattribute.- Type:
List[
Role]
- 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 it’s 0 then the invite doesn’t expire. Defaults to0.max_uses (
int) – How many uses the invite could be used for. If it’s 0 then there are unlimited uses. Defaults to0.temporary (
bool) – 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 (Optional[
InviteTarget]) –The type of target for the voice channel invite, if any.
New in version 2.0.
target_user (Optional[
User]) –The user whose stream to display for this invite, required if target_type is TargetType.stream. The user must be streaming in the channel.
New in version 2.0.
target_application (Optional[
PartyType]) –The ID of the embedded application for the invite, required if target_type is TargetType.embedded_application.
New in version 2.0.
guild_scheduled_event (Optional[
GuildScheduledEvent]) –The guild scheduled event to include with the invite.
New in version 2.3.
reason (Optional[
str]) – 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 (Optional[
str]) – The reason for deleting this channel. Shows up on the audit log.- Raises:
Forbidden – You do not have proper permissions to delete the channel.
NotFound – The channel was not found or was already deleted.
HTTPException – Deleting the channel failed.
- 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:
List[
Invite]
- 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 (Optional[
abc.Snowflake]) – 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 (Optional[
str]) – 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:
Dict[Union[
Role,Member],PermissionOverwrite]
- 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 pins()[source]¶
This function is a coroutine.
Retrieves all messages that are currently pinned in the channel.
Note
Due to a limitation with the Discord API, the
Messageobjects returned by this method do not contain completeMessage.reactionsdata.- Raises:
HTTPException – Retrieving the pinned messages failed.
- Returns:
The messages that are currently pinned.
- Return type:
List[
Message]
- await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, suppress_embeds=False, allowed_mentions=None, reference=None, mention_author=None, view=None, components=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, orviewmust 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:
content (Optional[
str]) – The content of the message to send.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.embeds (List[
Embed]) –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[Union[
GuildSticker,StickerItem]]) –A list of stickers to upload. Must be a maximum of 3.
New in version 2.0.
nonce (Union[
str,int]) – The nonce to use for sending this message. If the message was successfully sent, then the message will have a nonce with this value.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 (Union[
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.
mention_author (Optional[
bool]) –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 (Union[
disnake.ui.ActionRow,disnake.ui.WrappedComponent, List[Union[disnake.ui.ActionRow,disnake.ui.WrappedComponent, List[disnake.ui.WrappedComponent]]]]) –A list of components to include in the message. This cannot be mixed with
view.New in version 2.4.
suppress_embeds (
bool) –Whether to suppress embeds for the message. This hides all embeds from the UI if set to
True.New in version 2.5.
- 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.
- 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 (Union[
Member,Role]) – The member or role to overwrite permissions for.overwrite (Optional[
PermissionOverwrite]) – The permissions to allow and deny to the target, orNoneto delete the overwrite.**permissions – A keyword argument list of permissions to set for ease of use. Cannot be mixed with
overwrite.reason (Optional[
str]) – The reason for doing this action. Shows up on the audit log.
- Raises:
Forbidden – You do not have permissions to edit channel specific permissions.
HTTPException – Editing channel specific permissions failed.
NotFound – The role or member being edited is not part of the guild.
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
- asyncpins
- asyncpurge
- asyncsend
- asyncset_permissions
- asynctrigger_typing
- deftyping
- asyncwebhooks
- class disnake.VoiceChannel[source]¶
This class is a Discord Model.
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.- Type:
Optional[
str]
- 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.
- Type:
Optional[
int]
- property type[source]¶
The channel’s Discord type.
This always returns
ChannelType.voice.- Type:
- await clone(*, name=None, 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.New in version 1.1.
- Parameters:
- 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.
- Returns:
The last message in this channel or
Noneif not found.- Return type:
Optional[
Message]
- 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:
- 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
Changed in version 2.0: The object passed in can now be a role object.
- Parameters:
obj (Union[
Member,Role]) – The object to resolve permissions for. This could be either a member or a role. If it’s a role then member overwrites are not computed.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 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 new channel’s name.bitrate (
int) – The new channel’s bitrate.user_limit (
int) – The new channel’s user limit.position (
int) – The new channel’s position.sync_permissions (
bool) – Whether to sync permissions with the channel’s new or pre-existing category. Defaults toFalse.category (Optional[
abc.Snowflake]) – The new category for this channel. Can beNoneto remove the category.reason (Optional[
str]) – The reason for editing this channel. Shows up on the audit log.overwrites (
Mapping) – AMappingof target (either a role or a member) toPermissionOverwriteto apply to the channel.rtc_region (Optional[Union[
str,VoiceRegion]]) –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.
slowmode_delay (Optional[
int]) –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:
Optional[
VoiceChannel]
- 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 (Optional[
int]) – The number of messages to search through. This is not the number of messages that will be deleted, though it can be.check (Callable[[
Message],bool]) – The function used to check if a message should be deleted. It must take aMessageas its sole parameter.before (Optional[Union[
abc.Snowflake,datetime.datetime]]) – Same asbeforeinhistory().after (Optional[Union[
abc.Snowflake,datetime.datetime]]) – Same asafterinhistory().around (Optional[Union[
abc.Snowflake,datetime.datetime]]) – Same asaroundinhistory().oldest_first (Optional[
bool]) – Same asoldest_firstinhistory().bulk (
bool) – IfTrue, use bulk delete. Setting this toFalseis useful for mass-deleting a bot’s own messages withoutPermissions.manage_messages. WhenTrue, will fall back to single delete if messages are older than two weeks.
- 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:
List[
Message]
- 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:
- property category[source]¶
The category this channel belongs to.
If there is no category then this is
None.- Type:
Optional[
CategoryChannel]
- property changed_roles[source]¶
Returns a list of roles that have been overridden from their default values in the
Guild.rolesattribute.- Type:
List[
Role]
- 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 it’s 0 then the invite doesn’t expire. Defaults to0.max_uses (
int) – How many uses the invite could be used for. If it’s 0 then there are unlimited uses. Defaults to0.temporary (
bool) – 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 (Optional[
InviteTarget]) –The type of target for the voice channel invite, if any.
New in version 2.0.
target_user (Optional[
User]) –The user whose stream to display for this invite, required if target_type is TargetType.stream. The user must be streaming in the channel.
New in version 2.0.
target_application (Optional[
PartyType]) –The ID of the embedded application for the invite, required if target_type is TargetType.embedded_application.
New in version 2.0.
guild_scheduled_event (Optional[
GuildScheduledEvent]) –The guild scheduled event to include with the invite.
New in version 2.3.
reason (Optional[
str]) – 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 (Optional[
str]) – The reason for deleting this channel. Shows up on the audit log.- Raises:
Forbidden – You do not have proper permissions to delete the channel.
NotFound – The channel was not found or was already deleted.
HTTPException – Deleting the channel failed.
- 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 (Optional[
int]) – The number of messages to retrieve. IfNone, retrieves every message in the channel. Note, however, that this would make it a slow operation.before (Optional[Union[
abc.Snowflake,datetime.datetime]]) – Retrieve messages before this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.after (Optional[Union[
abc.Snowflake,datetime.datetime]]) – Retrieve messages after this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.around (Optional[Union[
abc.Snowflake,datetime.datetime]]) – Retrieve messages around this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time. When using this argument, the maximum limit is 101. Note that if the limit is an even number then this will return at most limit + 1 messages.oldest_first (Optional[
bool]) – If set toTrue, return messages in oldest->newest order. Defaults toTrueifafteris specified, otherwiseFalse.
- 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:
List[
Invite]
- 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 members[source]¶
Returns all members that are currently inside this voice channel.
- Type:
List[
Member]
- 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 (Optional[
abc.Snowflake]) – 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 (Optional[
str]) – 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:
Dict[Union[
Role,Member],PermissionOverwrite]
- 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 pins()[source]¶
This function is a coroutine.
Retrieves all messages that are currently pinned in the channel.
Note
Due to a limitation with the Discord API, the
Messageobjects returned by this method do not contain completeMessage.reactionsdata.- Raises:
HTTPException – Retrieving the pinned messages failed.
- Returns:
The messages that are currently pinned.
- Return type:
List[
Message]
- await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, suppress_embeds=False, allowed_mentions=None, reference=None, mention_author=None, view=None, components=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, orviewmust 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:
content (Optional[
str]) – The content of the message to send.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.embeds (List[
Embed]) –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[Union[
GuildSticker,StickerItem]]) –A list of stickers to upload. Must be a maximum of 3.
New in version 2.0.
nonce (Union[
str,int]) – The nonce to use for sending this message. If the message was successfully sent, then the message will have a nonce with this value.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 (Union[
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.
mention_author (Optional[
bool]) –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 (Union[
disnake.ui.ActionRow,disnake.ui.WrappedComponent, List[Union[disnake.ui.ActionRow,disnake.ui.WrappedComponent, List[disnake.ui.WrappedComponent]]]]) –A list of components to include in the message. This cannot be mixed with
view.New in version 2.4.
suppress_embeds (
bool) –Whether to suppress embeds for the message. This hides all embeds from the UI if set to
True.New in version 2.5.
- 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.
- 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 (Union[
Member,Role]) – The member or role to overwrite permissions for.overwrite (Optional[
PermissionOverwrite]) – The permissions to allow and deny to the target, orNoneto delete the overwrite.**permissions – A keyword argument list of permissions to set for ease of use. Cannot be mixed with
overwrite.reason (Optional[
str]) – The reason for doing this action. Shows up on the audit log.
- Raises:
Forbidden – You do not have permissions to edit channel specific permissions.
HTTPException – Editing channel specific permissions failed.
NotFound – The role or member being edited is not part of the guild.
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!')
- property voice_states[source]¶
Returns a mapping of member IDs who have voice states in this channel.
New in version 1.3.
Note
This function is intentionally low level to replace
memberswhen the member cache is unavailable.- Returns:
The mapping of member ID to a voice state.
- Return type:
Mapping[
int,VoiceState]
CategoryChannel¶
- asyncclone
- asynccreate_forum_channel
- asynccreate_invite
- 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]¶
This class is a Discord Model.
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:
- await clone(*, name=None, 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.New in version 1.1.
- Parameters:
- 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) – 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 (Optional[
str]) – 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:
Optional[
CategoryChannel]
- 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 (Optional[
abc.Snowflake]) – 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 (Optional[
str]) – 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:
List[
abc.GuildChannel]
- property text_channels[source]¶
Returns the text channels that are under this category.
- Type:
List[
TextChannel]
- property voice_channels[source]¶
Returns the voice channels that are under this category.
- Type:
List[
VoiceChannel]
- property stage_channels[source]¶
Returns the stage channels that are under this category.
New in version 1.7.
- Type:
List[
StageChannel]
- property forum_channels[source]¶
Returns the forum channels that are under this category.
New in version 2.5.
- Type:
List[
ForumChannel]
- 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:
- property category[source]¶
The category this channel belongs to.
If there is no category then this is
None.- Type:
Optional[
CategoryChannel]
- property changed_roles[source]¶
Returns a list of roles that have been overridden from their default values in the
Guild.rolesattribute.- Type:
List[
Role]
- 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 it’s 0 then the invite doesn’t expire. Defaults to0.max_uses (
int) – How many uses the invite could be used for. If it’s 0 then there are unlimited uses. Defaults to0.temporary (
bool) – 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 (Optional[
InviteTarget]) –The type of target for the voice channel invite, if any.
New in version 2.0.
target_user (Optional[
User]) –The user whose stream to display for this invite, required if target_type is TargetType.stream. The user must be streaming in the channel.
New in version 2.0.
target_application (Optional[
PartyType]) –The ID of the embedded application for the invite, required if target_type is TargetType.embedded_application.
New in version 2.0.
guild_scheduled_event (Optional[
GuildScheduledEvent]) –The guild scheduled event to include with the invite.
New in version 2.3.
reason (Optional[
str]) – 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 (Optional[
str]) – The reason for deleting this channel. Shows up on the audit log.- Raises:
Forbidden – You do not have proper permissions to delete the channel.
NotFound – The channel was not found or was already deleted.
HTTPException – Deleting the channel failed.
- 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:
List[
Invite]
- 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:
Dict[Union[
Role,Member],PermissionOverwrite]
- 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
Changed in version 2.0: The object passed in can now be a role object.
- Parameters:
obj (Union[
Member,Role]) – The object to resolve permissions for. This could be either a member or a role. If it’s a role then member overwrites are not computed.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 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 (Union[
Member,Role]) – The member or role to overwrite permissions for.overwrite (Optional[
PermissionOverwrite]) – The permissions to allow and deny to the target, orNoneto delete the overwrite.**permissions – A keyword argument list of permissions to set for ease of use. Cannot be mixed with
overwrite.reason (Optional[
str]) – The reason for doing this action. Shows up on the audit log.
- Raises:
Forbidden – You do not have permissions to edit channel specific permissions.
HTTPException – Editing channel specific permissions failed.
NotFound – The role or member being edited is not part of the guild.
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
- asyncpins
- asyncpurge
- asyncremove_tags
- asyncremove_user
- asyncsend
- asynctrigger_typing
- deftyping
- class disnake.Thread[source]¶
This class is a Discord Model.
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
TextChannelorForumChannelID 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.
- Type:
Optional[
int]
- 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.
- Type:
Optional[
int]
- 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.
- Type:
Optional[
int]
- me¶
A thread member representing yourself, if you’ve joined the thread. This could not be available.
- Type:
Optional[
ThreadMember]
- 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:
Optional[
datetime.datetime]
- last_pin_timestamp¶
The time the most recent message was pinned, or
Noneif no message is currently pinned.New in version 2.5.
- Type:
Optional[
datetime.datetime]
- 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 (Optional[
int]) – The number of messages to retrieve. IfNone, retrieves every message in the channel. Note, however, that this would make it a slow operation.before (Optional[Union[
abc.Snowflake,datetime.datetime]]) – Retrieve messages before this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.after (Optional[Union[
abc.Snowflake,datetime.datetime]]) – Retrieve messages after this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.around (Optional[Union[
abc.Snowflake,datetime.datetime]]) – Retrieve messages around this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time. When using this argument, the maximum limit is 101. Note that if the limit is an even number then this will return at most limit + 1 messages.oldest_first (Optional[
bool]) – If set toTrue, return messages in oldest->newest order. Defaults toTrueifafteris specified, otherwiseFalse.
- 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 parent[source]¶
The parent channel this thread belongs to.
- Type:
Optional[Union[
TextChannel,ForumChannel]]
- 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:
List[
ThreadMember]
- 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.- Returns:
The last message in this channel or
Noneif not found.- Return type:
Optional[
Message]
- 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:
Optional[
CategoryChannel]
- 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:
Optional[
int]
- property created_at[source]¶
Returns the thread’s creation time in UTC.
Changed in version 2.4: If create_timestamp is 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_threads.- 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
ForumChannelPinned 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
ForumChannels.New in version 2.6.
- Type:
List[
ForumTag]
- 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. This is a convenience method for calling
permissions_for()on the parent channel.- Parameters:
obj (Union[
Member,Role]) – The object to resolve permissions for. This could be either a member or a role. If it’s a role then member overwrites are not computed.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 (Optional[
int]) – The number of messages to search through. This is not the number of messages that will be deleted, though it can be.check (Callable[[
Message],bool]) – The function used to check if a message should be deleted. It must take aMessageas its sole parameter.before (Optional[Union[
abc.Snowflake,datetime.datetime]]) – Same asbeforeinhistory().after (Optional[Union[
abc.Snowflake,datetime.datetime]]) – Same asafterinhistory().around (Optional[Union[
abc.Snowflake,datetime.datetime]]) – Same asaroundinhistory().oldest_first (Optional[
bool]) – Same asoldest_firstinhistory().bulk (
bool) – IfTrue, use bulk delete. Setting this toFalseis useful for mass-deleting a bot’s own messages withoutPermissions.manage_messages. WhenTrue, will fall back to single delete if messages are older than two weeks.
- 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:
List[
Message]
- 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 (Union[
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
ForumChannel.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
ForumChannel.If
moderatedtags are edited,Permissions.manage_threadspermissions are required.See also
add_tags()andremove_tags().New in version 2.6.
reason (Optional[
str]) –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 add to 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:
List[
ThreadMember]
- 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 aForumChannel, you are the thread creator, and there are no messages other than the initial message.- Parameters:
reason (Optional[
str]) –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
ForumChannel.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 (Optional[
str]) – 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
ForumChannel.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 (Optional[
str]) – 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:
- await pins()[source]¶
This function is a coroutine.
Retrieves all messages that are currently pinned in the channel.
Note
Due to a limitation with the Discord API, the
Messageobjects returned by this method do not contain completeMessage.reactionsdata.- Raises:
HTTPException – Retrieving the pinned messages failed.
- Returns:
The messages that are currently pinned.
- Return type:
List[
Message]
- await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, suppress_embeds=False, allowed_mentions=None, reference=None, mention_author=None, view=None, components=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, orviewmust 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:
content (Optional[
str]) – The content of the message to send.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.embeds (List[
Embed]) –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[Union[
GuildSticker,StickerItem]]) –A list of stickers to upload. Must be a maximum of 3.
New in version 2.0.
nonce (Union[
str,int]) – The nonce to use for sending this message. If the message was successfully sent, then the message will have a nonce with this value.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 (Union[
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.
mention_author (Optional[
bool]) –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 (Union[
disnake.ui.ActionRow,disnake.ui.WrappedComponent, List[Union[disnake.ui.ActionRow,disnake.ui.WrappedComponent, List[disnake.ui.WrappedComponent]]]]) –A list of components to include in the message. This cannot be mixed with
view.New in version 2.4.
suppress_embeds (
bool) –Whether to suppress embeds for the message. This hides all embeds from the UI if set to
True.New in version 2.5.
- 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.
- Returns:
The message that was sent.
- Return type:
ThreadMember¶
- class disnake.ThreadMember[source]¶
This class is a Discord Model.
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:
ForumTag¶
- defwith_changes
- class disnake.ForumTag[source]¶
Represents a tag for threads in forum 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:
Optional[Union[
Emoji,PartialEmoji]]
- with_changes(*, name=..., emoji=..., moderated=...)[source]¶
Returns a new instance with the given changes applied, for easy use with
ForumChannel.edit(). All other fields will be kept intact.- Returns:
The new tag instance.
- Return type:
StageChannel¶
- asyncclone
- asyncconnect
- asynccreate_instance
- asynccreate_invite
- asyncdelete
- asyncedit
- asyncfetch_instance
- asyncinvites
- asyncmove
- defoverwrites_for
- defpermissions_for
- asyncset_permissions
- class disnake.StageChannel[source]¶
This class is a Discord Model.
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.- Type:
Optional[
str]
- video_quality_mode¶
The camera video quality for the stage channel’s participants.
New in version 2.0.
- Type:
- property requesting_to_speak[source]¶
A list of members who are requesting to speak in the stage channel.
- Type:
List[
Member]
- property speakers[source]¶
A list of members who have been permitted to speak in the stage channel.
New in version 2.0.
- Type:
List[
Member]
- property listeners[source]¶
A list of members who are listening in the stage channel.
New in version 2.0.
- Type:
List[
Member]
- property moderators[source]¶
A list of members who are moderating the stage channel.
New in version 2.0.
- Type:
List[
Member]
- property type[source]¶
The channel’s Discord type.
This always returns
ChannelType.stage_voice.- Type:
- await clone(*, name=None, 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.New in version 1.1.
- Parameters:
- 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 instance[source]¶
The running stage instance of the stage channel.
New in version 2.0.
- Type:
Optional[
StageInstance]
- 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
Changed in version 2.0: The object passed in can now be a role object.
- Parameters:
obj (Union[
Member,Role]) – The object to resolve permissions for. This could be either a member or a role. If it’s a role then member overwrites are not computed.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 create_instance(*, topic, privacy_level=..., notify_everyone=False, 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.reason (Optional[
str]) – The reason the stage instance was created. Shows up on the audit log.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.
- 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=..., position=..., sync_permissions=..., category=..., overwrites=..., rtc_region=..., video_quality_mode=..., bitrate=..., 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.- Parameters:
name (
str) – The new channel’s name.position (
int) – The new channel’s position.sync_permissions (
bool) – Whether to sync permissions with the channel’s new or pre-existing category. Defaults toFalse.category (Optional[
abc.Snowflake]) – The new category for this channel. Can beNoneto remove the category.overwrites (
Mapping) – AMappingof target (either a role or a member) toPermissionOverwriteto apply to the channel.rtc_region (Optional[Union[
str,VoiceRegion]]) – 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.0.
bitrate (
int) –The new channel’s bitrate.
New in version 2.6.
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 (Optional[
str]) – 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:
Optional[
StageChannel]
- property category[source]¶
The category this channel belongs to.
If there is no category then this is
None.- Type:
Optional[
CategoryChannel]
- property changed_roles[source]¶
Returns a list of roles that have been overridden from their default values in the
Guild.rolesattribute.- Type:
List[
Role]
- 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 it’s 0 then the invite doesn’t expire. Defaults to0.max_uses (
int) – How many uses the invite could be used for. If it’s 0 then there are unlimited uses. Defaults to0.temporary (
bool) – 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 (Optional[
InviteTarget]) –The type of target for the voice channel invite, if any.
New in version 2.0.
target_user (Optional[
User]) –The user whose stream to display for this invite, required if target_type is TargetType.stream. The user must be streaming in the channel.
New in version 2.0.
target_application (Optional[
PartyType]) –The ID of the embedded application for the invite, required if target_type is TargetType.embedded_application.
New in version 2.0.
guild_scheduled_event (Optional[
GuildScheduledEvent]) –The guild scheduled event to include with the invite.
New in version 2.3.
reason (Optional[
str]) – 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 (Optional[
str]) – The reason for deleting this channel. Shows up on the audit log.- Raises:
Forbidden – You do not have proper permissions to delete the channel.
NotFound – The channel was not found or was already deleted.
HTTPException – Deleting the channel failed.
- 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:
List[
Invite]
- 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 members[source]¶
Returns all members that are currently inside this voice channel.
- Type:
List[
Member]
- 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 (Optional[
abc.Snowflake]) – 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 (Optional[
str]) – 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:
Dict[Union[
Role,Member],PermissionOverwrite]
- 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 (Union[
Member,Role]) – The member or role to overwrite permissions for.overwrite (Optional[
PermissionOverwrite]) – The permissions to allow and deny to the target, orNoneto delete the overwrite.**permissions – A keyword argument list of permissions to set for ease of use. Cannot be mixed with
overwrite.reason (Optional[
str]) – The reason for doing this action. Shows up on the audit log.
- Raises:
Forbidden – You do not have permissions to edit channel specific permissions.
HTTPException – Editing channel specific permissions failed.
NotFound – The role or member being edited is not part of the guild.
TypeError –
overwriteis invalid, the target type was notRoleorMember, both keyword arguments andoverwritewere provided, or invalid permissions were provided as keyword arguments.
- property voice_states[source]¶
Returns a mapping of member IDs who have voice states in this channel.
New in version 1.3.
Note
This function is intentionally low level to replace
memberswhen the member cache is unavailable.- Returns:
The mapping of member ID to a voice state.
- Return type:
Mapping[
int,VoiceState]
ForumChannel¶
- 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
- asyncinvites
- defis_nsfw
- asyncmove
- defoverwrites_for
- defpermissions_for
- defrequires_tag
- asyncset_permissions
- asynctrigger_typing
- deftyping
- asyncwebhooks
- class disnake.ForumChannel[source]¶
This class is a Discord Model.
Represents a Discord 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.
- Type:
Optional[
int]
- 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:
Optional[
ThreadSortOrder]
- 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:
- 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
Changed in version 2.0: The object passed in can now be a role object.
- Parameters:
obj (Union[
Member,Role]) – The object to resolve permissions for. This could be either a member or a role. If it’s a role then member overwrites are not computed.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:
- 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:
- property default_reaction[source]¶
Optional[Union[
Emoji,PartialEmoji]]: 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.
- 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.- Returns:
The last created thread in this channel or
Noneif not found.- Return type:
Optional[
Thread]
- property available_tags[source]¶
The available tags for threads in this forum channel.
To create/edit/delete tags, use
edit().New in version 2.6.
- Type:
List[
ForumTag]
- await trigger_typing()[source]¶
This function is a coroutine.
Triggers a typing indicator to the desination.
Typing indicator will go away after 10 seconds.
- 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.Changed in version 2.6: Raises
TypeErrororValueErrorinstead ofInvalidArgument.- Parameters:
name (
str) – The channel’s new name.topic (Optional[
str]) – The channel’s new topic.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 (Optional[
abc.Snowflake]) – The new category for this channel. Can beNoneto remove the category.slowmode_delay (Optional[
int]) – 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 (Optional[
int]) –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) – AMappingof target (either a role or a member) toPermissionOverwriteto apply to the channel.default_auto_archive_duration (Optional[Union[
int,ThreadArchiveDuration]]) – 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 (Optional[Union[
str,Emoji,PartialEmoji]]) –The new default emoji shown for reacting to threads.
New in version 2.6.
default_sort_order (Optional[
ThreadSortOrder]) –The new default sort order of threads in this channel.
New in version 2.6.
reason (Optional[
str]) – 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:
Optional[
ForumChannel]
- await clone(*, name=None, 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.New in version 1.1.
- Parameters:
- 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 create_thread(*, name, auto_archive_duration=..., slowmode_delay=..., applied_tags=..., content=..., embed=..., embeds=..., file=..., files=..., suppress_embeds=..., stickers=..., allowed_mentions=..., view=..., components=..., reason=None)[source]¶
This function is a coroutine.
Creates a thread in this forum 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.- Parameters:
name (
str) – The name of the thread.auto_archive_duration (Union[
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) – Specifies the slowmode rate limit for users in this thread, in seconds. A value of0disables slowmode. The maximum value possible is21600. If 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 embeds from the UI if set toTrue.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[Union[
GuildSticker,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 (Union[
disnake.ui.ActionRow,disnake.ui.WrappedComponent, List[Union[disnake.ui.ActionRow,disnake.ui.WrappedComponent, List[disnake.ui.WrappedComponent]]]]) – A list of components to include in the message. This cannot be mixed withview.reason (Optional[
str]) – 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.
- Returns:
A
NamedTuplewith the newly created thread and the message sent in it.These values can also be accessed through the
threadandmessagefields.- 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 (Optional[
int]) – 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 (Optional[Union[
abc.Snowflake,datetime.datetime]]) – 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.
- 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.
- 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:
- 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 forum channel must be unique.
New in version 2.6.
- property category[source]¶
The category this channel belongs to.
If there is no category then this is
None.- Type:
Optional[
CategoryChannel]
- property changed_roles[source]¶
Returns a list of roles that have been overridden from their default values in the
Guild.rolesattribute.- Type:
List[
Role]
- 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 it’s 0 then the invite doesn’t expire. Defaults to0.max_uses (
int) – How many uses the invite could be used for. If it’s 0 then there are unlimited uses. Defaults to0.temporary (
bool) – 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 (Optional[
InviteTarget]) –The type of target for the voice channel invite, if any.
New in version 2.0.
target_user (Optional[
User]) –The user whose stream to display for this invite, required if target_type is TargetType.stream. The user must be streaming in the channel.
New in version 2.0.
target_application (Optional[
PartyType]) –The ID of the embedded application for the invite, required if target_type is TargetType.embedded_application.
New in version 2.0.
guild_scheduled_event (Optional[
GuildScheduledEvent]) –The guild scheduled event to include with the invite.
New in version 2.3.
reason (Optional[
str]) – 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 (Optional[
str]) – The reason for deleting this channel. Shows up on the audit log.- Raises:
Forbidden – You do not have proper permissions to delete the channel.
NotFound – The channel was not found or was already deleted.
HTTPException – Deleting the channel failed.
- 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:
List[
Invite]
- 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 (Optional[
abc.Snowflake]) – 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 (Optional[
str]) – 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:
Dict[Union[
Role,Member],PermissionOverwrite]
- 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 (Union[
Member,Role]) – The member or role to overwrite permissions for.overwrite (Optional[
PermissionOverwrite]) – The permissions to allow and deny to the target, orNoneto delete the overwrite.**permissions – A keyword argument list of permissions to set for ease of use. Cannot be mixed with
overwrite.reason (Optional[
str]) – The reason for doing this action. Shows up on the audit log.
- Raises:
Forbidden – You do not have permissions to edit channel specific permissions.
HTTPException – Editing channel specific permissions failed.
NotFound – The role or member being edited is not part of the guild.
TypeError –
overwriteis invalid, the target type was notRoleorMember, both keyword arguments andoverwritewere provided, or invalid permissions were provided as keyword arguments.
DMChannel¶
- asyncfetch_message
- defget_partial_message
- defhistory
- defpermissions_for
- asyncpins
- asyncsend
- asynctrigger_typing
- deftyping
- class disnake.DMChannel[source]¶
This class is a Discord Model.
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.
- Type:
Optional[
User]
- 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:
Optional[
datetime.datetime]
- 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 (Optional[
int]) – The number of messages to retrieve. IfNone, retrieves every message in the channel. Note, however, that this would make it a slow operation.before (Optional[Union[
abc.Snowflake,datetime.datetime]]) – Retrieve messages before this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.after (Optional[Union[
abc.Snowflake,datetime.datetime]]) – Retrieve messages after this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.around (Optional[Union[
abc.Snowflake,datetime.datetime]]) – Retrieve messages around this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time. When using this argument, the maximum limit is 101. Note that if the limit is an even number then this will return at most limit + 1 messages.oldest_first (Optional[
bool]) – If set toTrue, return messages in oldest->newest order. Defaults toTrueifafteris specified, otherwiseFalse.
- 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:
- 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:
- 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 pins()[source]¶
This function is a coroutine.
Retrieves all messages that are currently pinned in the channel.
Note
Due to a limitation with the Discord API, the
Messageobjects returned by this method do not contain completeMessage.reactionsdata.- Raises:
HTTPException – Retrieving the pinned messages failed.
- Returns:
The messages that are currently pinned.
- Return type:
List[
Message]
- await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, suppress_embeds=False, allowed_mentions=None, reference=None, mention_author=None, view=None, components=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, orviewmust 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:
content (Optional[
str]) – The content of the message to send.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.embeds (List[
Embed]) –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[Union[
GuildSticker,StickerItem]]) –A list of stickers to upload. Must be a maximum of 3.
New in version 2.0.
nonce (Union[
str,int]) – The nonce to use for sending this message. If the message was successfully sent, then the message will have a nonce with this value.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 (Union[
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.
mention_author (Optional[
bool]) –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 (Union[
disnake.ui.ActionRow,disnake.ui.WrappedComponent, List[Union[disnake.ui.ActionRow,disnake.ui.WrappedComponent, List[disnake.ui.WrappedComponent]]]]) –A list of components to include in the message. This cannot be mixed with
view.New in version 2.4.
suppress_embeds (
bool) –Whether to suppress embeds for the message. This hides all embeds from the UI if set to
True.New in version 2.5.
- 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.
- Returns:
The message that was sent.
- Return type:
GroupChannel¶
- asyncfetch_message
- defhistory
- asyncleave
- defpermissions_for
- asyncpins
- asyncsend
- asynctrigger_typing
- deftyping
- class disnake.GroupChannel[source]¶
This class is a Discord Model.
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
- me¶
The user presenting 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 (Optional[
int]) – The number of messages to retrieve. IfNone, retrieves every message in the channel. Note, however, that this would make it a slow operation.before (Optional[Union[
abc.Snowflake,datetime.datetime]]) – Retrieve messages before this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.after (Optional[Union[
abc.Snowflake,datetime.datetime]]) – Retrieve messages after this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.around (Optional[Union[
abc.Snowflake,datetime.datetime]]) – Retrieve messages around this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time. When using this argument, the maximum limit is 101. Note that if the limit is an even number then this will return at most limit + 1 messages.oldest_first (Optional[
bool]) – If set toTrue, return messages in oldest->newest order. Defaults toTrueifafteris specified, otherwiseFalse.
- 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:
- await pins()[source]¶
This function is a coroutine.
Retrieves all messages that are currently pinned in the channel.
Note
Due to a limitation with the Discord API, the
Messageobjects returned by this method do not contain completeMessage.reactionsdata.- Raises:
HTTPException – Retrieving the pinned messages failed.
- Returns:
The messages that are currently pinned.
- Return type:
List[
Message]
- await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, suppress_embeds=False, allowed_mentions=None, reference=None, mention_author=None, view=None, components=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, orviewmust 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:
content (Optional[
str]) – The content of the message to send.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.embeds (List[
Embed]) –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[Union[
GuildSticker,StickerItem]]) –A list of stickers to upload. Must be a maximum of 3.
New in version 2.0.
nonce (Union[
str,int]) – The nonce to use for sending this message. If the message was successfully sent, then the message will have a nonce with this value.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 (Union[
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.
mention_author (Optional[
bool]) –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 (Union[
disnake.ui.ActionRow,disnake.ui.WrappedComponent, List[Union[disnake.ui.ActionRow,disnake.ui.WrappedComponent, List[disnake.ui.WrappedComponent]]]]) –A list of components to include in the message. This cannot be mixed with
view.New in version 2.4.
suppress_embeds (
bool) –Whether to suppress embeds for the message. This hides all embeds from the UI if set to
True.New in version 2.5.
- 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.
- 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:
- 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.
PartialMessageable¶
- asyncfetch_message
- defget_partial_message
- defhistory
- asyncpins
- asyncsend
- asynctrigger_typing
- deftyping
- class disnake.PartialMessageable[source]¶
This class is a Discord Model.
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:
Optional[
ChannelType]
- 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 (Optional[
int]) – The number of messages to retrieve. IfNone, retrieves every message in the channel. Note, however, that this would make it a slow operation.before (Optional[Union[
abc.Snowflake,datetime.datetime]]) – Retrieve messages before this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.after (Optional[Union[
abc.Snowflake,datetime.datetime]]) – Retrieve messages after this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.around (Optional[Union[
abc.Snowflake,datetime.datetime]]) – Retrieve messages around this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time. When using this argument, the maximum limit is 101. Note that if the limit is an even number then this will return at most limit + 1 messages.oldest_first (Optional[
bool]) – If set toTrue, return messages in oldest->newest order. Defaults toTrueifafteris specified, otherwiseFalse.
- 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 pins()[source]¶
This function is a coroutine.
Retrieves all messages that are currently pinned in the channel.
Note
Due to a limitation with the Discord API, the
Messageobjects returned by this method do not contain completeMessage.reactionsdata.- Raises:
HTTPException – Retrieving the pinned messages failed.
- Returns:
The messages that are currently pinned.
- Return type:
List[
Message]
- await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, suppress_embeds=False, allowed_mentions=None, reference=None, mention_author=None, view=None, components=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, orviewmust 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:
content (Optional[
str]) – The content of the message to send.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.embeds (List[
Embed]) –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[Union[
GuildSticker,StickerItem]]) –A list of stickers to upload. Must be a maximum of 3.
New in version 2.0.
nonce (Union[
str,int]) – The nonce to use for sending this message. If the message was successfully sent, then the message will have a nonce with this value.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 (Union[
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.
mention_author (Optional[
bool]) –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 (Union[
disnake.ui.ActionRow,disnake.ui.WrappedComponent, List[Union[disnake.ui.ActionRow,disnake.ui.WrappedComponent, List[disnake.ui.WrappedComponent]]]]) –A list of components to include in the message. This cannot be mixed with
view.New in version 2.4.
suppress_embeds (
bool) –Whether to suppress embeds for the message. This hides all embeds from the UI if set to
True.New in version 2.5.
- 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.
- 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:
Data Classes¶
ChannelFlags¶
- class disnake.ChannelFlags(**kwargs)[source]¶
This class is a Data Class.
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:
- require_tag¶
Returns
Trueif the channel requires all newly created threads to have a tag.This only applies to channels of type
ForumChannel.New in version 2.6.
- Type:
RawThreadDeleteEvent¶
- class disnake.RawThreadDeleteEvent[source]¶
This class is a Data Class.
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]¶
This class is a Data Class.
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:
Optional[
ThreadMember]
Enumerations¶
ChannelType¶
- class disnake.ChannelType[source]¶
This class is an Enumeration.
Specifies the type of channel.
- text¶
A text channel.
- voice¶
A voice channel.
- private¶
A private text channel. Also called a direct message.
- group¶
A private group text channel.
- category¶
A category channel.
- news¶
A guild news channel.
- stage_voice¶
A guild stage voice channel.
New in version 1.7.
- 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.
- guild_directory¶
A student hub channel.
New in version 2.1.
- forum¶
A channel of only threads.
New in version 2.5.
ThreadArchiveDuration¶
- class disnake.ThreadArchiveDuration[source]¶
This class is an Enumeration.
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¶
- class disnake.VideoQualityMode[source]¶
This class is an Enumeration.
Represents the camera video quality mode for voice channel participants.
New in version 2.0.
- auto¶
Represents auto camera video quality.
- full¶
Represents full camera video quality.
ThreadSortOrder¶
- class disnake.ThreadSortOrder[source]¶
Represents the sort order of threads in
ForumChannels.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).
Events¶
See all related events!