Clients¶
This section documents everything related to Client and it’s connectivity to Discord.
If this is your first time working with disnake, it is highly recommended to read Getting Started articles first.
Classes¶
Client¶
- activity
- allowed_mentions
- application_flags
- application_id
- cached_messages
- emojis
- global_application_commands
- global_message_commands
- global_slash_commands
- global_user_commands
- guilds
- i18n
- intents
- latency
- loop
- persistent_views
- private_channels
- session_start_limit
- soundboard_sounds
- status
- stickers
- user
- users
- voice_clients
- ws
- defadd_listener
- defadd_view
- asyncapplication_info
- asyncbefore_identify_hook
- asyncbulk_fetch_command_permissions
- asyncbulk_overwrite_global_commands
- asyncbulk_overwrite_guild_commands
- asyncchange_presence
- defclear
- asyncclose
- asyncconnect
- asynccreate_application_emoji
- asynccreate_dm
- asynccreate_entitlement
- asynccreate_global_command
- asynccreate_guild
- asynccreate_guild_command
- asyncdelete_global_command
- asyncdelete_guild_command
- asyncdelete_invite
- asyncedit_global_command
- asyncedit_guild_command
- asyncedit_role_connection_metadata
- defentitlements
- @event
- asyncfetch_application_emoji
- asyncfetch_application_emojis
- asyncfetch_channel
- asyncfetch_command_permissions
- asyncfetch_default_soundboard_sounds
- asyncfetch_entitlement
- asyncfetch_global_command
- asyncfetch_global_commands
- asyncfetch_guild
- asyncfetch_guild_command
- asyncfetch_guild_commands
- asyncfetch_guild_preview
- deffetch_guilds
- asyncfetch_invite
- deffetch_premium_sticker_packs
- asyncfetch_role_connection_metadata
- asyncfetch_stage_instance
- asyncfetch_sticker
- asyncfetch_sticker_pack
- asyncfetch_sticker_packs
- asyncfetch_template
- asyncfetch_user
- asyncfetch_voice_regions
- asyncfetch_webhook
- asyncfetch_widget
- defget_all_channels
- defget_all_members
- defget_channel
- defget_emoji
- defget_global_command
- defget_global_command_named
- defget_guild
- defget_guild_application_commands
- defget_guild_command
- defget_guild_command_named
- defget_guild_message_commands
- defget_guild_slash_commands
- defget_guild_user_commands
- defget_listeners
- defget_message
- asyncget_or_fetch_user
- defget_partial_messageable
- defget_soundboard_sound
- defget_stage_instance
- defget_sticker
- defget_user
- asyncgetch_user
- defguild_builder
- defis_closed
- defis_ready
- defis_ws_ratelimited
- @listen
- asynclogin
- asyncon_error
- asyncon_gateway_error
- defremove_listener
- defrun
- asyncskus
- asyncstart
- asyncwait_for
- asyncwait_until_first_connect
- asyncwait_until_ready
- class disnake.Client(*, asyncio_debug=False, loop=None, shard_id=None, shard_count=None, enable_debug_events=False, enable_gateway_error_handler=True, localization_provider=None, strict_localization=False, gateway_params=None, connector=None, proxy=None, proxy_auth=None, assume_unsync_clock=True, max_messages=1000, application_id=None, heartbeat_timeout=60.0, guild_ready_timeout=2.0, allowed_mentions=None, activity=None, status=None, intents=None, chunk_guilds_at_startup=None, member_cache_flags=None)[source]¶
- Represents a client connection that connects to Discord. This class is used to interact with the Discord WebSocket and API. - A number of options can be passed to the - Client.- Parameters:
- max_messages (Optional[ - int]) –- The maximum number of messages to store in the internal message cache. This defaults to - 1000. Passing in- Nonedisables the message cache.- Changed in version 1.3: Allow disabling the message cache and change the default size to - 1000.
- loop (Optional[ - asyncio.AbstractEventLoop]) – The- asyncio.AbstractEventLoopto use for asynchronous operations. Defaults to- None, in which case the current event loop is used, or a new loop is created if there is none.
- asyncio_debug ( - bool) – Whether to enable asyncio debugging when the client starts. Defaults to False.
- connector (Optional[ - aiohttp.BaseConnector]) – The connector to use for connection pooling.
- proxy (Optional[ - str]) – Proxy URL.
- proxy_auth (Optional[ - aiohttp.BasicAuth]) – An object that represents proxy HTTP Basic Authorization.
- shard_id (Optional[ - int]) – Integer starting at- 0and less than- shard_count.
- shard_count (Optional[ - int]) – The total number of shards.
- application_id ( - int) – The client’s application ID.
- intents (Optional[ - Intents]) –- The intents that you want to enable for the session. This is a way of disabling and enabling certain gateway events from triggering and being sent. If not given, defaults to a regularly constructed - Intentsclass.- New in version 1.5. 
- member_cache_flags ( - MemberCacheFlags) –- Allows for finer control over how the library caches members. If not given, defaults to cache as much as possible with the currently selected intents. - New in version 1.5. 
- chunk_guilds_at_startup ( - bool) –- Indicates if - on_ready()should be delayed to chunk all guilds at start-up if necessary. This operation is incredibly slow for large amounts of guilds. The default is- Trueif- Intents.membersis- True.- New in version 1.5. 
- status (Optional[Union[class:str, - Status]]) – A status to start your presence with upon logging on to Discord.
- activity (Optional[ - BaseActivity]) – An activity to start your presence with upon logging on to Discord.
- allowed_mentions (Optional[ - AllowedMentions]) –- Control how the client handles mentions by default on every message sent. - New in version 1.4. 
- heartbeat_timeout ( - float) – The maximum numbers of seconds before timing out and restarting the WebSocket in the case of not receiving a HEARTBEAT_ACK. Useful if processing the initial packets take too long to the point of disconnecting you. The default timeout is 60 seconds.
- guild_ready_timeout ( - float) –- The maximum number of seconds to wait for the GUILD_CREATE stream to end before preparing the member cache and firing READY. The default timeout is 2 seconds. - New in version 1.4. 
- assume_unsync_clock ( - bool) –- Whether to assume the system clock is unsynced. This applies to the ratelimit handling code. If this is set to - True, the default, then the library uses the time to reset a rate limit bucket given by Discord. If this is- Falsethen your system clock is used to calculate how long to sleep for. If this is set to- Falseit is recommended to sync your system clock to Google’s NTP server.- New in version 1.3. 
- enable_debug_events ( - bool) –- Whether to enable events that are useful only for debugging gateway related information. - Right now this involves - on_socket_raw_receive()and- on_socket_raw_send(). If this is- Falsethen those events will not be dispatched (due to performance considerations). To enable these events, this must be set to- True. Defaults to- False.- New in version 2.0. 
- enable_gateway_error_handler ( - bool) –- Whether to enable the - disnake.on_gateway_error()event. Defaults to- True.- If this is disabled, exceptions that occur while parsing (known) gateway events won’t be handled and the pre-v2.6 behavior of letting the exception propagate up to the - connect()/- start()/- run()call is used instead.- New in version 2.6. 
- localization_provider ( - LocalizationProtocol) –- An implementation of - LocalizationProtocolto use for localization of application commands. If not provided, the default- LocalizationStoreimplementation is used.- New in version 2.5. - Changed in version 2.6: Can no longer be provided together with - strict_localization, as it does not apply to the custom localization provider entered in this parameter.
- strict_localization ( - bool) –- Whether to raise an exception when localizations for a specific key couldn’t be found. This is mainly useful for testing/debugging, consider disabling this eventually as missing localized names will automatically fall back to the default/base name without it. Only applicable if the - localization_providerparameter is not provided. Defaults to- False.- New in version 2.5. - Changed in version 2.6: Can no longer be provided together with - localization_provider, as this parameter is ignored for custom localization providers.
- gateway_params ( - GatewayParams) –- Allows configuring parameters used for establishing gateway connections, notably enabling/disabling compression (enabled by default). Encodings other than JSON are not supported. - New in version 2.6. 
 
 - ws¶
- The websocket gateway the client is currently connected to. Could be - None.
 - loop¶
- The event loop that the client uses for asynchronous operations. 
 - session_start_limit¶
- Information about the current session start limit. Only available after initiating the connection. - New in version 2.5. - Type:
- Optional[ - SessionStartLimit]
 
 - i18n¶
- An implementation of - LocalizationProtocolused for localization of application commands.- New in version 2.5. - Type:
 
 - @event[source]¶
- A decorator that registers an event to listen to. - You can find more info about the events in the documentation. - The events must be a coroutine, if not, - TypeErroris raised.- Example - @client.event async def on_ready(): print('Ready!') - Raises:
- TypeError – The coroutine passed is not actually a coroutine. 
 
 - async for ... in fetch_guilds(*, limit=100, before=None, after=None, with_counts=True)[source]¶
- Retrieves an - AsyncIteratorthat enables receiving your guilds.- Note - Using this, you will only receive - Guild.id,- Guild.name,- Guild.features,- Guild.icon, and- Guild.bannerper- Guild.- Note - This method is an API call. For general usage, consider - guildsinstead.- Examples - Usage - async for guild in client.fetch_guilds(limit=150): print(guild.name) - Flattening into a list - guilds = await client.fetch_guilds(limit=150).flatten() # guilds is now a list of Guild... - All parameters are optional. - Parameters:
- limit (Optional[ - int]) – The number of guilds to retrieve. If- None, it retrieves every guild you have access to. Note, however, that this would make it a slow operation. Defaults to- 100.
- before (Union[ - abc.Snowflake,- datetime.datetime]) – Retrieves guilds before this date or object. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.
- after (Union[ - abc.Snowflake,- datetime.datetime]) – Retrieve guilds after this date or object. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.
- with_counts ( - bool) –- Whether to include approximate member and presence counts for the guilds. Defaults to - True.- New in version 2.10. 
 
- Raises:
- HTTPException – Retrieving the guilds failed. 
- Yields:
- Guild– The guild with the guild data parsed.
 
 - @listen(name=None)[source]¶
- A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as - on_ready()- The functions being listened to must be a coroutine. - Changed in version 2.10: The definition of this method was moved from - ext.commands.Botto the- Clientclass.- Example - @client.listen() async def on_message(message): print('one') # in some other file... @client.listen('on_message') async def my_message(message): print('two') # in yet another file @client.listen(Event.message) async def another_message(message): print('three') - Would print one, two and three in an unspecified order. 
 - property latency[source]¶
- Measures latency between a HEARTBEAT and a HEARTBEAT_ACK in seconds. - This could be referred to as the Discord WebSocket protocol latency. - Type:
 
 - is_ws_ratelimited()[source]¶
- Whether the websocket is currently rate limited. - This can be useful to know when deciding whether you should query members using HTTP or via the gateway. - New in version 1.6. - Return type:
 
 - property user[source]¶
- Represents the connected client. - Noneif not logged in.- Type:
- Optional[ - ClientUser]
 
 - property stickers[source]¶
- The stickers that the connected client has. - New in version 2.0. - Type:
- List[ - GuildSticker]
 
 - property soundboard_sounds[source]¶
- The soundboard sounds that the connected client has. - New in version 2.10. - Type:
- List[ - GuildSoundboardSound]
 
 - property cached_messages[source]¶
- Read-only list of messages the connected client has cached. - New in version 1.1. - Type:
- Sequence[ - Message]
 
 - property private_channels[source]¶
- The private channels that the connected client is participating on. - Note - This returns only up to 128 most recent private channels due to an internal working on how Discord deals with private channels. - Type:
- List[ - abc.PrivateChannel]
 
 - property voice_clients[source]¶
- Represents a list of voice connections. - These are usually - VoiceClientinstances.- Type:
- List[ - VoiceProtocol]
 
 - property application_id[source]¶
- The client’s application ID. - If this is not passed via - __init__then this is retrieved through the gateway when an event contains the data. Usually after- on_connect()is called.- New in version 2.0. - Type:
- Optional[ - int]
 
 - property global_application_commands[source]¶
- The client’s global application commands. - Type:
- List[Union[ - APIUserCommand,- APIMessageCommand,- APISlashCommand]
 
 - property global_slash_commands[source]¶
- The client’s global slash commands. - Type:
- List[ - APISlashCommand]
 
 - property global_user_commands[source]¶
- The client’s global user commands. - Type:
- List[ - APIUserCommand]
 
 - property global_message_commands[source]¶
- The client’s global message commands. - Type:
- List[ - APIMessageCommand]
 
 - await get_or_fetch_user(user_id, *, strict=False)[source]¶
- This function is a coroutine. - Tries to get the user from the cache. If it fails, fetches the user from the API. - This only propagates exceptions when the - strictparameter is enabled.- Parameters:
- user_id ( - int) – The ID to search for.
- strict ( - bool) – Whether to propagate exceptions from- fetch_user()instead of returning- Nonein case of failure (e.g. if the user wasn’t found). Defaults to- False.
 
- Returns:
- The user with the given ID, or - Noneif not found and- strictis set to- False.
- Return type:
- Optional[ - User]
 
 - await getch_user(user_id, *, strict=False)[source]¶
- This function is a coroutine. - Tries to get the user from the cache. If it fails, fetches the user from the API. - This only propagates exceptions when the - strictparameter is enabled.- Parameters:
- user_id ( - int) – The ID to search for.
- strict ( - bool) – Whether to propagate exceptions from- fetch_user()instead of returning- Nonein case of failure (e.g. if the user wasn’t found). Defaults to- False.
 
- Returns:
- The user with the given ID, or - Noneif not found and- strictis set to- False.
- Return type:
- Optional[ - User]
 
 - add_listener(func, name=...)[source]¶
- The non decorator alternative to - listen().- Changed in version 2.10: The definition of this method was moved from - ext.commands.Botto the- Clientclass.- Parameters:
 - Example - async def on_ready(): pass async def my_message(message): pass async def another_message(message): pass client.add_listener(on_ready) client.add_listener(my_message, 'on_message') client.add_listener(another_message, Event.message) 
 - remove_listener(func, name=...)[source]¶
- Removes a listener from the pool of listeners. - Changed in version 2.10: The definition of this method was moved from - ext.commands.Botto the- Clientclass.
 - get_listeners()[source]¶
- Mapping[ - str, List[Callable]]: A read-only mapping of event names to listeners.- Note - To add or remove a listener you should use - add_listener()and- remove_listener().- Changed in version 2.10: The definition of this method was moved from - ext.commands.Botto the- Clientclass.
 - await on_error(event_method, *args, **kwargs)[source]¶
- This function is a coroutine. - The default error handler provided by the client. - By default this prints to - sys.stderrhowever it could be overridden to have a different implementation. Check- on_error()for more details.
 - await on_gateway_error(event, data, shard_id, exc, /)[source]¶
- This function is a coroutine. - The default gateway error handler provided by the client. - By default this prints to - sys.stderrhowever it could be overridden to have a different implementation. Check- on_gateway_error()for more details.- New in version 2.6. - Note - Unlike - on_error(), the exception is available as the- excparameter and cannot be obtained through- sys.exc_info().
 - await before_identify_hook(shard_id, *, initial=False)[source]¶
- This function is a coroutine. - A hook that is called before IDENTIFYing a session. This is useful if you wish to have more control over the synchronization of multiple IDENTIFYing clients. - The default implementation sleeps for 5 seconds. - New in version 1.4. 
 - await login(token)[source]¶
- This function is a coroutine. - Logs in the client with the specified credentials. - Parameters:
- token ( - str) – The authentication token. Do not prefix this token with anything as the library will do it for you.
- Raises:
- LoginFailure – The wrong credentials are passed. 
- HTTPException – An unknown HTTP related error occurred, usually when it isn’t 200 or the known incorrect credentials passing status code. 
 
 
 - await connect(*, reconnect=True, ignore_session_start_limit=False)[source]¶
- This function is a coroutine. - Creates a websocket connection and lets the websocket listen to messages from Discord. This is a loop that runs the entire event system and miscellaneous aspects of the library. Control is not resumed until the WebSocket connection is terminated. - Changed in version 2.6: Added usage of - SessionStartLimitwhen connecting to the API. Added the- ignore_session_start_limitparameter.- Parameters:
- reconnect ( - bool) – Whether reconnecting should be attempted, either due to internet failure or a specific failure on Discord’s part. Certain disconnects that lead to bad state will not be handled (such as invalid sharding payloads or bad tokens).
- ignore_session_start_limit ( - bool) –- Whether the API provided session start limit should be ignored when connecting to the API. - New in version 2.6. 
 
- Raises:
- GatewayNotFound – If the gateway to connect to Discord is not found. Usually if this is thrown then there is a Discord API outage. 
- ConnectionClosed – The websocket connection has been terminated. 
- SessionStartLimitReached – If the client doesn’t have enough connects remaining in the current 24-hour window and - ignore_session_start_limitis- Falsethis will be raised rather than connecting to the gateawy and Discord resetting the token. However, if- ignore_session_start_limitis- True, the client will connect regardless and this exception will not be raised.
 
 
 - clear()[source]¶
- Clears the internal state of the bot. - After this, the bot can be considered “re-opened”, i.e. - is_closed()and- is_ready()both return- Falsealong with the bot’s internal cache cleared.
 - await start(token, *, reconnect=True, ignore_session_start_limit=False)[source]¶
- This function is a coroutine. - A shorthand coroutine for - login()+- connect().- Raises:
- TypeError – An unexpected keyword argument was received. 
 
 - run(*args, **kwargs)[source]¶
- A blocking call that abstracts away the event loop initialisation from you. - If you want more control over the event loop then this function should not be used. Use - start()coroutine or- connect()+- login().- Roughly Equivalent to: - try: loop.run_until_complete(start(*args, **kwargs)) except KeyboardInterrupt: loop.run_until_complete(close()) # cancel all tasks lingering finally: loop.close() - Warning - This function must be the last function to call due to the fact that it is blocking. That means that registration of events or anything being called after this function call will not execute until it returns - Parameters:
- token ( - str) – The discord token of the bot that is being ran.
 
 - property activity[source]¶
- The activity being used upon logging in. - Type:
- Optional[ - BaseActivity]
 
 - property status[source]¶
- The status being used upon logging on to Discord. - New in version 2.0. - Type:
 
 - property allowed_mentions[source]¶
- The allowed mention configuration. - New in version 1.4. - Type:
- Optional[ - AllowedMentions]
 
 - get_channel(id, /)[source]¶
- Returns a channel or thread with the given ID. - Parameters:
- id ( - int) – The ID to search for.
- Returns:
- The returned channel or - Noneif not found.
- Return type:
- Optional[Union[ - abc.GuildChannel,- Thread,- abc.PrivateChannel]]
 
 - get_partial_messageable(id, *, type=None)[source]¶
- Returns a partial messageable with the given channel ID. - This is useful if you have a channel_id but don’t want to do an API call to send messages to it. - New in version 2.0. - Parameters:
- id ( - int) – The channel ID to create a partial messageable for.
- type (Optional[ - ChannelType]) – The underlying channel type for the partial messageable.
 
- Returns:
- The partial messageable 
- Return type:
 
 - get_stage_instance(id, /)[source]¶
- Returns a stage instance with the given stage channel ID. - New in version 2.0. - Parameters:
- id ( - int) – The ID to search for.
- Returns:
- The returns stage instance or - Noneif not found.
- Return type:
- Optional[ - StageInstance]
 
 - get_sticker(id, /)[source]¶
- Returns a guild sticker with the given ID. - New in version 2.0. - Note - To retrieve standard stickers, use - fetch_sticker()or- fetch_sticker_packs().- Returns:
- The sticker or - Noneif not found.
- Return type:
- Optional[ - GuildSticker]
 
 - get_soundboard_sound(id, /)[source]¶
- Returns a guild soundboard sound with the given ID. - New in version 2.10. - Note - To retrieve standard soundboard sounds, use - fetch_default_soundboard_sounds().- Returns:
- The soundboard sound or - Noneif not found.
- Return type:
- Optional[ - GuildSoundboardSound]
 
 - for ... in get_all_channels()[source]¶
- A generator that retrieves every - abc.GuildChannelthe client can ‘access’.- This is equivalent to: - for guild in client.guilds: for channel in guild.channels: yield channel - Note - Just because you receive a - abc.GuildChanneldoes not mean that you can communicate in said channel.- abc.GuildChannel.permissions_for()should be used for that.- Yields:
- abc.GuildChannel– A channel the client can ‘access’.
 
 - for ... in get_all_members()[source]¶
- Returns a generator with every - Memberthe client can see.- This is equivalent to: - for guild in client.guilds: for member in guild.members: yield member - Yields:
- Member– A member the client can see.
 
 - get_guild_application_commands(guild_id)[source]¶
- Returns a list of all application commands in the guild with the given ID. - Parameters:
- guild_id ( - int) – The ID to search for.
- Returns:
- The list of application commands. 
- Return type:
- List[Union[ - APIUserCommand,- APIMessageCommand,- APISlashCommand]]
 
 - get_guild_slash_commands(guild_id)[source]¶
- Returns a list of all slash commands in the guild with the given ID. - Parameters:
- guild_id ( - int) – The ID to search for.
- Returns:
- The list of slash commands. 
- Return type:
- List[ - APISlashCommand]
 
 - get_guild_user_commands(guild_id)[source]¶
- Returns a list of all user commands in the guild with the given ID. - Parameters:
- guild_id ( - int) – The ID to search for.
- Returns:
- The list of user commands. 
- Return type:
- List[ - APIUserCommand]
 
 - get_guild_message_commands(guild_id)[source]¶
- Returns a list of all message commands in the guild with the given ID. - Parameters:
- guild_id ( - int) – The ID to search for.
- Returns:
- The list of message commands. 
- Return type:
- List[ - APIMessageCommand]
 
 - get_global_command(id)[source]¶
- Returns a global application command with the given ID. - Parameters:
- id ( - int) – The ID to search for.
- Returns:
- The application command. 
- Return type:
- Optional[Union[ - APIUserCommand,- APIMessageCommand,- APISlashCommand]]
 
 - get_guild_command(guild_id, id)[source]¶
- Returns a guild application command with the given guild ID and application command ID. - Parameters:
- Returns:
- The application command. 
- Return type:
- Optional[Union[ - APIUserCommand,- APIMessageCommand,- APISlashCommand]]
 
 - get_global_command_named(name, cmd_type=None)[source]¶
- Returns a global application command matching the given name. - Parameters:
- name ( - str) – The name to look for.
- cmd_type ( - ApplicationCommandType) – The type to look for. By default, no types are checked.
 
- Returns:
- The application command. 
- Return type:
- Optional[Union[ - APIUserCommand,- APIMessageCommand,- APISlashCommand]]
 
 - get_guild_command_named(guild_id, name, cmd_type=None)[source]¶
- Returns a guild application command matching the given name. - Parameters:
- guild_id ( - int) – The guild ID to search for.
- name ( - str) – The command name to search for.
- cmd_type ( - ApplicationCommandType) – The type to look for. By default, no types are checked.
 
- Returns:
- The application command. 
- Return type:
- Optional[Union[ - APIUserCommand,- APIMessageCommand,- APISlashCommand]]
 
 - await wait_until_ready()[source]¶
- This function is a coroutine. - Waits until the client’s internal cache is all ready. 
 - await wait_until_first_connect()[source]¶
- This function is a coroutine. - Waits until the first connect. 
 - wait_for(event, *, check=None, timeout=None)[source]¶
- This function is a coroutine. - Waits for a WebSocket event to be dispatched. - This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way. - The - timeoutparameter is passed onto- asyncio.wait_for(). By default, it does not timeout. Note that this does propagate the- asyncio.TimeoutErrorfor you in case of timeout and is provided for ease of use.- In case the event returns multiple arguments, a - tuplecontaining those arguments is returned instead. Please check the documentation for a list of events and their parameters.- This function returns the first event that meets the requirements. - Examples - Waiting for a user reply: - @client.event async def on_message(message): if message.content.startswith('$greet'): channel = message.channel await channel.send('Say hello!') def check(m): return m.content == 'hello' and m.channel == channel msg = await client.wait_for('message', check=check) await channel.send(f'Hello {msg.author}!') # using events enums: @client.event async def on_message(message): if message.content.startswith('$greet'): channel = message.channel await channel.send('Say hello!') def check(m): return m.content == 'hello' and m.channel == channel msg = await client.wait_for(Event.message, check=check) await channel.send(f'Hello {msg.author}!') - Waiting for a thumbs up reaction from the message author: - @client.event async def on_message(message): if message.content.startswith('$thumb'): channel = message.channel await channel.send('Send me that 👍 reaction, mate') def check(reaction, user): return user == message.author and str(reaction.emoji) == '👍' try: reaction, user = await client.wait_for('reaction_add', timeout=60.0, check=check) except asyncio.TimeoutError: await channel.send('👎') else: await channel.send('👍') - Parameters:
- event (Union[ - str,- Event]) – The event name, similar to the event reference, but without the- on_prefix, to wait for. It’s recommended to use- Event.
- check (Optional[Callable[…, - bool]]) – A predicate to check what to wait for. The arguments must meet the parameters of the event being waited for.
- timeout (Optional[ - float]) – The number of seconds to wait before timing out and raising- asyncio.TimeoutError.
 
- Raises:
- asyncio.TimeoutError – If a timeout is provided and it was reached. 
- Returns:
- Returns no arguments, a single argument, or a - tupleof multiple arguments that mirrors the parameters passed in the event.
- Return type:
- Any 
 
 - await change_presence(*, activity=None, status=None)[source]¶
- This function is a coroutine. - Changes the client’s presence. - Changed in version 2.0: Removed the - afkkeyword-only parameter.- Changed in version 2.6: Raises - TypeErrorinstead of- InvalidArgument.- Example - game = disnake.Game("with the API") await client.change_presence(status=disnake.Status.idle, activity=game) - Parameters:
- activity (Optional[ - BaseActivity]) – The activity being done.- Noneif no currently active activity is done.
- status (Optional[ - Status]) – Indicates what status to change to. If- None, then- Status.onlineis used.
 
- Raises:
- TypeError – If the - activityparameter is not the proper type.
 
 - await fetch_template(code)[source]¶
- This function is a coroutine. - Retrieves a - Templatefrom a discord.new URL or code.- Parameters:
- code (Union[ - Template,- str]) – The Discord Template Code or URL (must be a discord.new URL).
- Raises:
- NotFound – The template is invalid. 
- HTTPException – Retrieving the template failed. 
 
- Returns:
- The template from the URL/code. 
- Return type:
 
 - await fetch_guild(guild_id, /, *, with_counts=True)[source]¶
- This function is a coroutine. - Retrieves a - Guildfrom the given ID.- Note - Using this, you will not receive - Guild.channels,- Guild.members,- Member.activityand- Member.voiceper- Member.- Note - This method is an API call. For general usage, consider - get_guild()instead.- Parameters:
- Raises:
- Forbidden – You do not have access to the guild. 
- HTTPException – Retrieving the guild failed. 
 
- Returns:
- The guild from the given ID. 
- Return type:
 
 - await fetch_guild_preview(guild_id, /)[source]¶
- This function is a coroutine. - Retrieves a - GuildPreviewfrom the given ID. Your bot does not have to be in this guild.- Note - This method may fetch any guild that has - DISCOVERABLEin- Guild.features, but this information can not be known ahead of time.- This will work for any guild that you are in. 
 - await create_guild(*, name, icon=..., code=...)[source]¶
- This function is a coroutine. - Creates a - Guild.- See - guild_builder()for a more comprehensive alternative.- Bot accounts in 10 or more guilds are not allowed to create guilds. - Note - Using this, you will not receive - Guild.channels,- Guild.members,- Member.activityand- Member.voiceper- Member.- Changed in version 2.5: Removed the - regionparameter.- Changed in version 2.6: Raises - ValueErrorinstead of- InvalidArgument.- Parameters:
- name ( - str) – The name of the guild.
- icon (Union[ - bytes,- Asset,- Emoji,- PartialEmoji,- StickerItem,- Sticker]) –- The icon of the guild. See - ClientUser.edit()for more details on what is expected.- Changed in version 2.5: Now accepts various resource types in addition to - bytes.
- code ( - str) –- The code for a template to create the guild with. - New in version 1.4. 
 
- Raises:
- NotFound – The - iconasset couldn’t be found.
- HTTPException – Guild creation failed. 
- ValueError – Invalid icon image format given. Must be PNG or JPG. 
- TypeError – The - iconasset is a lottie sticker (see- Sticker.read).
 
- Returns:
- The created guild. This is not the same guild that is added to cache. 
- Return type:
 
 - guild_builder(name)[source]¶
- Creates a builder object that can be used to create more complex guilds. - This is a more comprehensive alternative to - create_guild(). See- GuildBuilderfor details and examples.- Bot accounts in 10 or more guilds are not allowed to create guilds. - Note - Using this, you will not receive - Guild.channels,- Guild.members,- Member.activityand- Member.voiceper- Member.- New in version 2.8. - Parameters:
- name ( - str) – The name of the guild.
- Returns:
- The guild builder object for configuring and creating a new guild. 
- Return type:
 
 - await fetch_stage_instance(channel_id, /)[source]¶
- This function is a coroutine. - Retrieves a - StageInstancewith the given ID.- Note - This method is an API call. For general usage, consider - get_stage_instance()instead.- New in version 2.0. - Parameters:
- channel_id ( - int) – The stage channel ID.
- Raises:
- NotFound – The stage instance or channel could not be found. 
- HTTPException – Retrieving the stage instance failed. 
 
- Returns:
- The stage instance from the given ID. 
- Return type:
 
 - await fetch_invite(url, *, with_counts=True, guild_scheduled_event_id=None, with_expiration=False)[source]¶
- This function is a coroutine. - Retrieves an - Invitefrom a discord.gg URL or ID.- Note - If the invite is for a guild you have not joined, the guild and channel attributes of the returned - Invitewill be- PartialInviteGuildand- PartialInviteChannelrespectively.- Parameters:
- url (Union[ - Invite,- str]) – The Discord invite ID or URL (must be a discord.gg URL).
- with_counts ( - bool) – Whether to include count information in the invite. This fills the- Invite.approximate_member_countand- Invite.approximate_presence_countfields.
- guild_scheduled_event_id ( - int) –- The ID of the scheduled event to include in the invite. If not provided, defaults to the - eventparameter in the URL if it exists, or the ID of the scheduled event contained in the provided invite object.- New in version 2.3. 
 
- Raises:
- NotFound – The invite has expired or is invalid. 
- HTTPException – Retrieving the invite failed. 
 
- Returns:
- The invite from the URL/ID. 
- Return type:
 
 - await delete_invite(invite)[source]¶
- This function is a coroutine. - Revokes an - Invite, URL, or ID to an invite.- You must have - manage_channelspermission in the associated guild to do this.- Parameters:
- Raises:
- Forbidden – You do not have permissions to revoke invites. 
- NotFound – The invite is invalid or expired. 
- HTTPException – Revoking the invite failed. 
 
 
 - await fetch_voice_regions(guild_id=None)[source]¶
- Retrieves a list of - VoiceRegions.- Retrieves voice regions for the user, or a guild if provided. - New in version 2.5. - Parameters:
- guild_id (Optional[ - int]) – The guild to get regions for, if provided.
- Raises:
- HTTPException – Retrieving voice regions failed. 
- NotFound – The provided - guild_idcould not be found.
 
 
 - await fetch_widget(guild_id, /)[source]¶
- This function is a coroutine. - Retrieves a - Widgetfor the given guild ID.- Note - The guild must have the widget enabled to get this information. - Parameters:
- guild_id ( - int) – The ID of the guild.
- Raises:
- Forbidden – The widget for this guild is disabled. 
- HTTPException – Retrieving the widget failed. 
 
- Returns:
- The guild’s widget. 
- Return type:
 
 - await fetch_default_soundboard_sounds()[source]¶
- This function is a coroutine. - Retrieves the list of default - SoundboardSounds provided by Discord.- New in version 2.10. - Raises:
- HTTPException – Retrieving the soundboard sounds failed. 
- Returns:
- The default soundboard sounds. 
- Return type:
- List[ - SoundboardSound]
 
 - await application_info()[source]¶
- This function is a coroutine. - Retrieves the bot’s application information. - Raises:
- HTTPException – Retrieving the information failed somehow. 
- Returns:
- The bot’s application information. 
- Return type:
 
 - await fetch_application_emoji(emoji_id)[source]¶
- This function is a coroutine. - Retrieves an application level - Emojibased on its ID.- New in version 2.12.0a. - Parameters:
- emoji_id ( - int) – The ID of the emoji to retrieve.
- Raises:
- NotFound – The app emoji couldn’t be found. 
- HTTPException – An error occurred fetching the app emoji. 
 
- Returns:
- The application emoji you requested. 
- Return type:
 
 - await create_application_emoji(*, name, image)[source]¶
- This function is a coroutine. - Creates an application emoji. - New in version 2.12.0a. - Parameters:
- name ( - str) – The emoji name. Must be at least 2 characters.
- image (Union[ - bytes,- Asset,- Emoji,- PartialEmoji,- StickerItem,- Sticker]) – The image data of the emoji. Only JPG, PNG and GIF images are supported.
 
- Raises:
- NotFound – The - imageasset couldn’t be found.
- HTTPException – An error occurred creating the app emoji. 
- TypeError – The - imageasset is a lottie sticker (see- Sticker.read).
- ValueError – Wrong image format passed for - image.
 
- Returns:
- The newly created application emoji. 
- Return type:
 
 - await fetch_application_emojis()[source]¶
- This function is a coroutine. - Retrieves all the - Emojiof the application.- New in version 2.12.0a. - Raises:
- HTTPException – An error occurred fetching the app emojis. 
- Returns:
- The list of application emojis you requested. 
- Return type:
- List[ - Emoji]
 
 - await fetch_user(user_id, /)[source]¶
- This function is a coroutine. - Retrieves a - Userbased on their ID. You do not have to share any guilds with the user to get this information, however many operations do require that you do.- Note - This method is an API call. If you have - disnake.Intents.membersand member cache enabled, consider- get_user()instead.- Parameters:
- user_id ( - int) – The ID of the user to retrieve.
- Raises:
- NotFound – A user with this ID does not exist. 
- HTTPException – Retrieving the user failed. 
 
- Returns:
- The user you requested. 
- Return type:
 
 - await fetch_channel(channel_id, /)[source]¶
- This function is a coroutine. - Retrieves a - abc.GuildChannel,- abc.PrivateChannel, or- Threadwith the specified ID.- Note - This method is an API call. For general usage, consider - get_channel()instead.- New in version 1.2. - Parameters:
- channel_id ( - int) – The ID of the channel to retrieve.
- Raises:
- InvalidData – An unknown channel type was received from Discord. 
- HTTPException – Retrieving the channel failed. 
- NotFound – Invalid Channel ID. 
- Forbidden – You do not have permission to fetch this channel. 
 
- Returns:
- The channel from the ID. 
- Return type:
- Union[ - abc.GuildChannel,- abc.PrivateChannel,- Thread]
 
 - await fetch_webhook(webhook_id, /)[source]¶
- This function is a coroutine. - Retrieves a - Webhookwith the given ID.- Parameters:
- webhook_id ( - int) – The ID of the webhook to retrieve.
- Raises:
- HTTPException – Retrieving the webhook failed. 
- NotFound – Invalid webhook ID. 
- Forbidden – You do not have permission to fetch this webhook. 
 
- Returns:
- The webhook you requested. 
- Return type:
 
 - await fetch_sticker(sticker_id, /)[source]¶
- This function is a coroutine. - Retrieves a - Stickerwith the given ID.- New in version 2.0. - Parameters:
- sticker_id ( - int) – The ID of the sticker to retrieve.
- Raises:
- HTTPException – Retrieving the sticker failed. 
- NotFound – Invalid sticker ID. 
 
- Returns:
- The sticker you requested. 
- Return type:
- Union[ - StandardSticker,- GuildSticker]
 
 - await fetch_sticker_pack(pack_id, /)[source]¶
- This function is a coroutine. - Retrieves a - StickerPackwith the given ID.- New in version 2.10. - Parameters:
- pack_id ( - int) – The ID of the sticker pack to retrieve.
- Raises:
- HTTPException – Retrieving the sticker pack failed. 
- NotFound – Invalid sticker pack ID. 
 
- Returns:
- The sticker pack you requested. 
- Return type:
 
 - await fetch_sticker_packs()[source]¶
- This function is a coroutine. - Retrieves all available sticker packs. - New in version 2.0. - Changed in version 2.10: Renamed from - fetch_premium_sticker_packs.- Raises:
- HTTPException – Retrieving the sticker packs failed. 
- Returns:
- All available sticker packs. 
- Return type:
- List[ - StickerPack]
 
 - An alias of - fetch_sticker_packs().- Deprecated since version 2.10. 
 - await create_dm(user)[source]¶
- This function is a coroutine. - Creates a - DMChannelwith the given user.- This should be rarely called, as this is done transparently for most people. - New in version 2.0. 
 - add_view(view, *, message_id=None)[source]¶
- Registers a - Viewfor persistent listening.- This method should be used for when a view is comprised of components that last longer than the lifecycle of the program. - New in version 2.0. - Parameters:
- view ( - disnake.ui.View) – The view to register for dispatching.
- message_id (Optional[ - int]) – The message ID that the view is attached to. This is currently used to refresh the view’s state during message update events. If not given then message update events are not propagated for the view.
 
- Raises:
- TypeError – A view was not passed. 
- ValueError – The view is not persistent. A persistent view has no timeout and all their components have an explicitly provided custom_id. 
 
 
 - property persistent_views[source]¶
- A sequence of persistent views added to the client. - New in version 2.0. - Type:
- Sequence[ - View]
 
 - await fetch_global_commands(*, with_localizations=True)[source]¶
- This function is a coroutine. - Retrieves a list of global application commands. - New in version 2.1. - Parameters:
- with_localizations ( - bool) –- Whether to include localizations in the response. Defaults to - True.- New in version 2.5. 
- Returns:
- A list of application commands. 
- Return type:
- List[Union[ - APIUserCommand,- APIMessageCommand,- APISlashCommand]]
 
 - await fetch_global_command(command_id)[source]¶
- This function is a coroutine. - Retrieves a global application command. - New in version 2.1. - Parameters:
- command_id ( - int) – The ID of the command to retrieve.
- Returns:
- The requested application command. 
- Return type:
 
 - await create_global_command(application_command)[source]¶
- This function is a coroutine. - Creates a global application command. - New in version 2.1. - Parameters:
- application_command ( - ApplicationCommand) – An object representing the application command to create.
- Returns:
- The application command that was created. 
- Return type:
 
 - await edit_global_command(command_id, new_command)[source]¶
- This function is a coroutine. - Edits a global application command. - New in version 2.1. - Parameters:
- command_id ( - int) – The ID of the application command to edit.
- new_command ( - ApplicationCommand) – An object representing the edited application command.
 
- Returns:
- The edited application command. 
- Return type:
 
 - await delete_global_command(command_id)[source]¶
- This function is a coroutine. - Deletes a global application command. - New in version 2.1. - Parameters:
- command_id ( - int) – The ID of the application command to delete.
 
 - await bulk_overwrite_global_commands(application_commands)[source]¶
- This function is a coroutine. - Overwrites several global application commands in one API request. - New in version 2.1. - Parameters:
- application_commands (List[ - ApplicationCommand]) – A list of application commands to insert instead of the existing commands.
- Returns:
- A list of registered application commands. 
- Return type:
- List[Union[ - APIUserCommand,- APIMessageCommand,- APISlashCommand]]
 
 - await fetch_guild_commands(guild_id, *, with_localizations=True)[source]¶
- This function is a coroutine. - Retrieves a list of guild application commands. - New in version 2.1. - Parameters:
- Returns:
- A list of application commands. 
- Return type:
- List[Union[ - APIUserCommand,- APIMessageCommand,- APISlashCommand]]
 
 - await fetch_guild_command(guild_id, command_id)[source]¶
- This function is a coroutine. - Retrieves a guild application command. - New in version 2.1. - Parameters:
- Returns:
- The requested application command. 
- Return type:
 
 - await create_guild_command(guild_id, application_command)[source]¶
- This function is a coroutine. - Creates a guild application command. - New in version 2.1. - Parameters:
- guild_id ( - int) – The ID of the guild where the application command should be created.
- application_command ( - ApplicationCommand) – The application command.
 
- Returns:
- The newly created application command. 
- Return type:
 
 - await edit_guild_command(guild_id, command_id, new_command)[source]¶
- This function is a coroutine. - Edits a guild application command. - New in version 2.1. - Parameters:
- guild_id ( - int) – The ID of the guild where the application command should be edited.
- command_id ( - int) – The ID of the application command to edit.
- new_command ( - ApplicationCommand) – An object representing the edited application command.
 
- Returns:
- The newly edited application command. 
- Return type:
 
 - await delete_guild_command(guild_id, command_id)[source]¶
- This function is a coroutine. - Deletes a guild application command. - New in version 2.1. 
 - await bulk_overwrite_guild_commands(guild_id, application_commands)[source]¶
- This function is a coroutine. - Overwrites several guild application commands in one API request. - New in version 2.1. - Parameters:
- guild_id ( - int) – The ID of the guild where the application commands should be overwritten.
- application_commands (List[ - ApplicationCommand]) – A list of application commands to insert instead of the existing commands.
 
- Returns:
- A list of registered application commands. 
- Return type:
- List[Union[ - APIUserCommand,- APIMessageCommand,- APISlashCommand]]
 
 - await bulk_fetch_command_permissions(guild_id)[source]¶
- This function is a coroutine. - Retrieves a list of - GuildApplicationCommandPermissionsconfigured for the guild with the given ID.- New in version 2.1. - Parameters:
- guild_id ( - int) – The ID of the guild to inspect.
 
 - await fetch_command_permissions(guild_id, command_id)[source]¶
- This function is a coroutine. - Retrieves - GuildApplicationCommandPermissionsfor a specific application command in the guild with the given ID.- New in version 2.1. - Parameters:
- Returns:
- The permissions configured for the specified application command. 
- Return type:
 
 - await fetch_role_connection_metadata()[source]¶
- This function is a coroutine. - Retrieves the - ApplicationRoleConnectionMetadatarecords for the application.- New in version 2.8. - Raises:
- HTTPException – Retrieving the metadata records failed. 
- Returns:
- The list of metadata records. 
- Return type:
 
 - await edit_role_connection_metadata(records)[source]¶
- This function is a coroutine. - Edits the - ApplicationRoleConnectionMetadatarecords for the application.- An application can have up to 5 metadata records. - Warning - This will overwrite all existing metadata records. Consider - fetchingthem first, and constructing the new list of metadata records based off of the returned list.- New in version 2.8. - Parameters:
- records (Sequence[ - ApplicationRoleConnectionMetadata]) – The new metadata records.
- Raises:
- HTTPException – Editing the metadata records failed. 
- Returns:
- The list of newly edited metadata records. 
- Return type:
 
 - await skus()[source]¶
- This function is a coroutine. - Retrieves the - SKUs for the application.- To manage application subscription entitlements, you should use the SKU with - SKUType.subscription(not the- subscription_groupone).- New in version 2.10. - Raises:
- HTTPException – Retrieving the SKUs failed. 
- Returns:
- The list of SKUs. 
- Return type:
- List[ - SKU]
 
 - entitlements(*, limit=100, before=None, after=None, user=None, guild=None, skus=None, exclude_ended=False, exclude_deleted=True, oldest_first=False)[source]¶
- Retrieves an - AsyncIteratorthat enables receiving entitlements for the application.- Note - This method is an API call. To get the entitlements of the invoking user/guild in interactions, consider using - Interaction.entitlements.- Entries are returned in order from newest to oldest by default; pass - oldest_first=Trueto reverse the iteration order.- All parameters are optional. - New in version 2.10. - Parameters:
- limit (Optional[ - int]) – The number of entitlements to retrieve. If- None, retrieves every entitlement. Note, however, that this would make it a slow operation. Defaults to- 100.
- before (Union[ - abc.Snowflake,- datetime.datetime]) – Retrieves entitlements created before this date or object. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.
- after (Union[ - abc.Snowflake,- datetime.datetime]) – Retrieve entitlements created after this date or object. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.
- user (Optional[ - abc.Snowflake]) – The user to retrieve entitlements for.
- guild (Optional[ - abc.Snowflake]) – The guild to retrieve entitlements for.
- skus (Optional[Sequence[ - abc.Snowflake]]) – The SKUs for which entitlements are retrieved.
- exclude_ended ( - bool) – Whether to exclude ended/expired entitlements. Defaults to- False.
- exclude_deleted ( - bool) – Whether to exclude deleted entitlements. Defaults to- True.
- oldest_first ( - bool) – If set to- True, return entries in oldest->newest order. Defaults to- False.
 
- Raises:
- HTTPException – Retrieving the entitlements failed. 
- Yields:
- Entitlement– The entitlements for the given parameters.
 
 - await fetch_entitlement(entitlement_id, /)[source]¶
- This function is a coroutine. - Retrieves a - Entitlementfor the given ID.- Note - This method is an API call. To get the entitlements of the invoking user/guild in interactions, consider using - Interaction.entitlements.- New in version 2.10. - Parameters:
- entitlement_id ( - int) – The ID of the entitlement to retrieve.
- Raises:
- HTTPException – Retrieving the entitlement failed. 
- Returns:
- The retrieved entitlement. 
- Return type:
 
 - await create_entitlement(sku, owner)[source]¶
- This function is a coroutine. - Creates a new test - Entitlementfor the given user or guild, with no expiry.- Note - This is only meant to be used with subscription SKUs. To test one-time purchases, use Application Test Mode. - Parameters:
- sku ( - abc.Snowflake) – The- SKUto grant the entitlement for.
- owner (Union[ - abc.User,- Guild]) – The user or guild to grant the entitlement to.
 
- Raises:
- HTTPException – Creating the entitlement failed. 
- Returns:
- The newly created entitlement. 
- Return type:
 
 
AutoShardedClient¶
- asyncchange_presence
- asyncclose
- asyncconnect
- defget_shard
- defis_ws_ratelimited
- class disnake.AutoShardedClient(*args, shard_ids=None, **kwargs)[source]¶
- A client similar to - Clientexcept it handles the complications of sharding for the user into a more manageable and transparent single process bot.- When using this client, you will be able to use it as-if it was a regular - Clientwith a single shard when implementation wise internally it is split up into multiple shards. This allows you to not have to deal with IPC or other complicated infrastructure.- It is recommended to use this client only if you have surpassed at least 1000 guilds. - If no - shard_countis provided, then the library will use the Bot Gateway endpoint call to figure out how many shards to use.- If a - shard_idsparameter is given, then those shard IDs will be used to launch the internal shards. Note that- shard_countmust be provided if this is used. By default, when omitted, the client will launch shards from 0 to- shard_count - 1.- property latency[source]¶
- Measures latency between a HEARTBEAT and a HEARTBEAT_ACK in seconds. - This operates similarly to - Client.latency()except it uses the average latency of every shard’s latency. To get a list of shard latency, check the- latenciesproperty. Returns- nanif there are no shards ready.- Type:
 
 - property latencies[source]¶
- A list of latencies between a HEARTBEAT and a HEARTBEAT_ACK in seconds. - This returns a list of tuples with elements - (shard_id, latency).
 - get_shard(shard_id)[source]¶
- Gets the shard information of a given shard ID, or - Noneif not found.- Return type:
- Optional[ - ShardInfo]
 
 - property shards[source]¶
- Returns a mapping of shard IDs to their respective info object. - Type:
- Mapping[int, - ShardInfo]
 
 - await connect(*, reconnect=True, ignore_session_start_limit=False)[source]¶
- This function is a coroutine. - Creates a websocket connection and lets the websocket listen to messages from Discord. This is a loop that runs the entire event system and miscellaneous aspects of the library. Control is not resumed until the WebSocket connection is terminated. - Changed in version 2.6: Added usage of - SessionStartLimitwhen connecting to the API. Added the- ignore_session_start_limitparameter.- Parameters:
- reconnect ( - bool) – Whether reconnecting should be attempted, either due to internet failure or a specific failure on Discord’s part. Certain disconnects that lead to bad state will not be handled (such as invalid sharding payloads or bad tokens).
- ignore_session_start_limit ( - bool) –- Whether the API provided session start limit should be ignored when connecting to the API. - New in version 2.6. 
 
- Raises:
- GatewayNotFound – If the gateway to connect to Discord is not found. Usually if this is thrown then there is a Discord API outage. 
- ConnectionClosed – The websocket connection has been terminated. 
- SessionStartLimitReached – If the client doesn’t have enough connects remaining in the current 24-hour window and - ignore_session_start_limitis- Falsethis will be raised rather than connecting to the gateawy and Discord resetting the token. However, if- ignore_session_start_limitis- True, the client will connect regardless and this exception will not be raised.
 
 
 - await change_presence(*, activity=None, status=None, shard_id=None)[source]¶
- This function is a coroutine. - Changes the client’s presence. - Example: - game = disnake.Game("with the API") await client.change_presence(status=disnake.Status.idle, activity=game) - Changed in version 2.0: Removed the - afkkeyword-only parameter.- Changed in version 2.6: Raises - TypeErrorinstead of- InvalidArgument.- Parameters:
- activity (Optional[ - BaseActivity]) – The activity being done.- Noneif no currently active activity is done.
- status (Optional[ - Status]) – Indicates what status to change to. If- None, then- Status.onlineis used.
- shard_id (Optional[ - int]) – The shard_id to change the presence to. If not specified or- None, then it will change the presence of every shard the bot can see.
 
- Raises:
- TypeError – If the - activityparameter is not of proper type.
 
 - is_ws_ratelimited()[source]¶
- Whether the websocket is currently rate limited. - This can be useful to know when deciding whether you should query members using HTTP or via the gateway. - This implementation checks if any of the shards are rate limited. For more granular control, consider - ShardInfo.is_ws_ratelimited().- New in version 1.6. - Return type:
 
 
Discord Models¶
ClientUser¶
- asyncedit
- defmentioned_in
- class disnake.ClientUser[source]¶
- Represents your Discord user. - x == y
- Checks if two users are equal. 
 - x != y
- Checks if two users are not equal. 
 - hash(x)
- Return the user’s hash. 
 - str(x)
- Returns the user’s username (with discriminator, if not migrated to new system yet). 
 - global_name¶
- The user’s global display name, if set. This takes precedence over - namewhen shown.- New in version 2.9. - Type:
- Optional[ - str]
 
 - system¶
- Specifies if the user is a system user (i.e. represents Discord officially). - New in version 1.3. - Type:
 
 - locale¶
- The IETF language tag used to identify the language the user is using. - Type:
- Optional[ - Locale]
 
 - await edit(*, username=..., avatar=..., banner=...)[source]¶
- This function is a coroutine. - Edits the current profile of the client. - Changed in version 2.0: The edit is no longer in-place, instead the newly edited client user is returned. - Changed in version 2.6: Raises - ValueErrorinstead of- InvalidArgument.- Parameters:
- username ( - str) – The new username you wish to change to.
- avatar (Optional[Union[ - bytes,- Asset,- Emoji,- PartialEmoji,- StickerItem,- Sticker]]) –- A bytes-like object or asset representing the image to upload. Could be - Noneto denote no avatar.- Only JPG, PNG, WEBP (static), and GIF (static/animated) images are supported. - Changed in version 2.5: Now accepts various resource types in addition to - bytes.
- banner (Optional[Union[ - bytes,- Asset,- Emoji,- PartialEmoji,- StickerItem,- Sticker]]) –- A bytes-like object or asset representing the image to upload. Could be - Noneto denote no banner.- Only JPG, PNG, WEBP (static), and GIF (static/animated) images are supported. - New in version 2.10. 
 
- Raises:
- NotFound – The - avataror- bannerasset couldn’t be found.
- HTTPException – Editing your profile failed. 
- TypeError – The - avataror- bannerasset is a lottie sticker (see- Sticker.read()).
- ValueError – Wrong image format passed for - avataror- banner.
 
- Returns:
- The newly edited client user. 
- Return type:
 
 - property accent_color[source]¶
- Returns the user’s accent color, if applicable. - There is an alias for this named - accent_colour.- New in version 2.0. - Note - This information is only available via - Client.fetch_user().- Type:
- Optional[ - Colour]
 
 - property accent_colour[source]¶
- Returns the user’s accent colour, if applicable. - There is an alias for this named - accent_color.- New in version 2.0. - Note - This information is only available via - Client.fetch_user().- Type:
- Optional[ - Colour]
 
 - property avatar[source]¶
- Returns an - Assetfor the avatar the user has.- If the user does not have a traditional avatar, - Noneis returned. If you want the avatar that a user has displayed, consider- display_avatar.- Type:
- Optional[ - Asset]
 
 - property avatar_decoration[source]¶
- Returns the user’s avatar decoration asset, if available. - New in version 2.10. - Note - Since Discord always sends an animated PNG for animated avatar decorations, the following methods will not work as expected: - Type:
- Optional[ - Asset]
 
 - property banner[source]¶
- Returns the user’s banner asset, if available. - New in version 2.0. - Note - This information is only available via - Client.fetch_user().- Type:
- Optional[ - Asset]
 
 - property color[source]¶
- A property that returns a color denoting the rendered color for the user. This always returns - Colour.default().- There is an alias for this named - colour.- Type:
 
 - property colour[source]¶
- A property that returns a colour denoting the rendered colour for the user. This always returns - Colour.default().- There is an alias for this named - color.- Type:
 
 - property created_at[source]¶
- Returns the user’s creation time in UTC. - This is when the user’s Discord account was created. - Type:
 
 - property default_avatar[source]¶
- Returns the default avatar for a given user. - Changed in version 2.9: Added handling for users migrated to the new username system without discriminators. - Type:
 
 - property display_avatar[source]¶
- Returns the user’s display avatar. - For regular users this is just their default avatar or uploaded avatar. - New in version 2.0. - Type:
 
 - property display_name[source]¶
- Returns the user’s display name. - This is their - global nameif set, or their- usernameotherwise.- Changed in version 2.9: Added - global_name.- Type:
 
 - property primary_guild[source]¶
- Returns the user’s primary guild, if any. - New in version 2.11. - Type:
- Optional[ - PrimaryGuild]
 
 
SessionStartLimit¶
- class disnake.SessionStartLimit[source]¶
- A class that contains information about the current session start limit, at the time when the client connected for the first time. - New in version 2.5. - reset_after¶
- The number of milliseconds after which the - remaininglimit resets, relative to when the client connected. See also- reset_time.- Type:
 
 
Data Classes¶
GatewayParams¶
Intents¶
- automod
- automod_configuration
- automod_execution
- bans
- dm_messages
- dm_polls
- dm_reactions
- dm_typing
- emojis
- emojis_and_stickers
- expressions
- guild_messages
- guild_polls
- guild_reactions
- guild_scheduled_events
- guild_typing
- guilds
- integrations
- invites
- members
- message_content
- messages
- moderation
- polls
- presences
- reactions
- typing
- value
- voice_states
- webhooks
- clsIntents.all
- clsIntents.default
- clsIntents.none
- class disnake.Intents(value=None, **kwargs)[source]¶
- Wraps up a Discord gateway intent flag. - Similar to - Permissions, the properties provided are two way. You can set and retrieve individual bits using the properties as if they were regular bools.- To construct an object you can pass keyword arguments denoting the flags to enable or disable. Arguments are applied in order, similar to - Permissions.- This is used to disable certain gateway features that are unnecessary to run your bot. To make use of this, it is passed to the - intentskeyword argument of- Client.- New in version 1.5. - x == y
- Checks if two Intents instances are equal. 
 - x != y
- Checks if two Intents instances are not equal. 
 - x <= y
- Checks if an Intents instance is a subset of another Intents instance. - New in version 2.6. 
 - x >= y
- Checks if an Intents instance is a superset of another Intents instance. - New in version 2.6. 
 - x < y
- Checks if an Intents instance is a strict subset of another Intents instance. - New in version 2.6. 
 - x > y
- Checks if an Intents instance is a strict superset of another Intents instance. - New in version 2.6. 
 - x | y, x |= y
- Returns a new Intents instance with all enabled intents from both x and y. (Using - |=will update in place).- New in version 2.6. 
 - x & y, x &= y
- Returns a new Intents instance with only intents enabled on both x and y. (Using - &=will update in place).- New in version 2.6. 
 - x ^ y, x ^= y
- Returns a new Intents instance with only intents enabled on one of x or y, but not both. (Using - ^=will update in place).- New in version 2.6. 
 - ~x
- Returns a new Intents instance with all intents inverted from x. - 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.
 - Additionally supported are a few operations on class attributes. - Intents.y | Intents.z, Intents(y=True) | Intents.z
- Returns an Intents instance with all provided flags enabled. - New in version 2.6. 
 - ~Intents.y
- Returns an Intents instance with all flags except - yinverted from their default value.- New in version 2.6. 
 - value¶
- The raw value. You should query flags via the properties rather than using this raw value. - Changed in version 2.6: This can be now be provided on initialisation. - Type:
 
 - classmethod all()[source]¶
- A factory method that creates an - Intentsinstance with everything enabled.
 - classmethod none()[source]¶
- A factory method that creates an - Intentsinstance with everything disabled.
 - classmethod default()[source]¶
- A factory method that creates an - Intentsinstance with everything enabled except- presences,- members, and- message_content.
 - guilds¶
- Whether guild related events are enabled. - This corresponds to the following events: - This also corresponds to the following attributes and classes in terms of cache: 
- Guildand all its attributes.
 - It is highly advisable to leave this intent enabled for your bot to function. - Type:
 
 - members¶
- Whether guild member related events are enabled. - This corresponds to the following events: - This also corresponds to the following attributes and classes in terms of cache: - For more information go to the member intent documentation. - Note - Currently, this requires opting in explicitly via the developer portal as well. Bots in over 100 guilds will need to apply to Discord for verification. - Type:
 
 - moderation¶
- Whether guild moderation related events are enabled. - This corresponds to the following events: - This does not correspond to any attributes or classes in the library in terms of cache. - Type:
 
 - bans¶
- Alias of - moderation.- Changed in version 2.8: Changed to an alias. - Type:
 
 - expressions¶
- Whether events related to guild emojis, stickers, and soundboard sounds are enabled. - New in version 2.10. - This corresponds to the following events: - This also corresponds to the following attributes and classes in terms of cache: - Type:
 
 - emojis_and_stickers¶
- Alias of - expressions.- New in version 2.0. - Changed in version 2.10: Changed to an alias. - Type:
 
 - emojis¶
- Alias of - expressions.- Changed in version 2.0: Changed to an alias. - Type:
 
 - integrations¶
- Whether guild integration related events are enabled. - This corresponds to the following events: - This does not correspond to any attributes or classes in the library in terms of cache. - Type:
 
 - webhooks¶
- Whether guild webhook related events are enabled. - This corresponds to the following events: - This does not correspond to any attributes or classes in the library in terms of cache. - Type:
 
 - invites¶
- Whether guild invite related events are enabled. - This corresponds to the following events: - This does not correspond to any attributes or classes in the library in terms of cache. - Type:
 
 - voice_states¶
- Whether guild voice state related events are enabled. - This corresponds to the following events: - This also corresponds to the following attributes and classes in terms of cache: - Note - This intent is required to connect to voice. - Type:
 
 - presences¶
- Whether guild presence related events are enabled. - This corresponds to the following events: - This also corresponds to the following attributes and classes in terms of cache: - For more information go to the presence intent documentation. - Note - Currently, this requires opting in explicitly via the developer portal as well. Bots in over 100 guilds will need to apply to Discord for verification. - Type:
 
 - messages¶
- Whether guild and direct message related events are enabled. - This is a shortcut to set or get both - guild_messagesand- dm_messages.- This corresponds to the following events: - on_message()(both guilds and DMs)
- on_message_edit()(both guilds and DMs)
- on_message_delete()(both guilds and DMs)
- on_raw_message_delete()(both guilds and DMs)
- on_raw_message_edit()(both guilds and DMs)
 - This also corresponds to the following attributes and classes in terms of cache: - Note that due to an implicit relationship this also corresponds to the following events: - on_reaction_add()(both guilds and DMs)
- on_reaction_remove()(both guilds and DMs)
- on_reaction_clear()(both guilds and DMs)
 - Note - Intents.message_contentis required to receive the content of messages.- Type:
 
 - guild_messages¶
- Whether guild message related events are enabled. - See also - dm_messagesfor DMs or- messagesfor both.- This corresponds to the following events: - on_message()(only for guilds)
- on_message_edit()(only for guilds)
- on_message_delete()(only for guilds)
- on_raw_message_delete()(only for guilds)
- on_raw_message_edit()(only for guilds)
 - This also corresponds to the following attributes and classes in terms of cache: 
- Client.cached_messages(only for guilds)
 - Note that due to an implicit relationship this also corresponds to the following events: - on_reaction_add()(only for guilds)
- on_reaction_remove()(only for guilds)
- on_reaction_clear()(only for guilds)
 - Type:
 
 - dm_messages¶
- Whether direct message related events are enabled. - See also - guild_messagesfor guilds or- messagesfor both.- This corresponds to the following events: - on_message()(only for DMs)
- on_message_edit()(only for DMs)
- on_message_delete()(only for DMs)
- on_raw_message_delete()(only for DMs)
- on_raw_message_edit()(only for DMs)
 - This also corresponds to the following attributes and classes in terms of cache: 
- Client.cached_messages(only for DMs)
 - Note that due to an implicit relationship this also corresponds to the following events: - on_reaction_add()(only for DMs)
- on_reaction_remove()(only for DMs)
- on_reaction_clear()(only for DMs)
 - Type:
 
 - message_content¶
- Whether messages will have access to message content. - New in version 2.5. - This applies to the following fields on - Messageinstances:- The following cases will always have the above fields: - Messages the bot sends 
- Messages the bot receives as a direct message 
- Messages in which the bot is mentioned 
- Messages received from an interaction payload, these will typically be attributes on - MessageInteractioninstances.
 - In addition, this also corresponds to the following fields: - For more information go to the message content intent documentation. - Note - Currently, this requires opting in explicitly via the developer portal as well. Bots in over 100 guilds will need to apply to Discord for verification. - Type:
 
 - reactions¶
- Whether guild and direct message reaction related events are enabled. - This is a shortcut to set or get both - guild_reactionsand- dm_reactions.- This corresponds to the following events: - on_reaction_add()(both guilds and DMs)
- on_reaction_remove()(both guilds and DMs)
- on_reaction_clear()(both guilds and DMs)
- on_raw_reaction_add()(both guilds and DMs)
- on_raw_reaction_remove()(both guilds and DMs)
- on_raw_reaction_clear()(both guilds and DMs)
 - This also corresponds to the following attributes and classes in terms of cache: - Message.reactions(both guild and DM messages)
 - Type:
 
 - guild_reactions¶
- Whether guild reaction related events are enabled. - See also - dm_reactionsfor DMs or- reactionsfor both.- This corresponds to the following events: - on_reaction_add()(only for guilds)
- on_reaction_remove()(only for guilds)
- on_reaction_clear()(only for guilds)
- on_raw_reaction_add()(only for guilds)
- on_raw_reaction_remove()(only for guilds)
- on_raw_reaction_clear()(only for guilds)
 - This also corresponds to the following attributes and classes in terms of cache: - Message.reactions(only for guild messages)
 - Type:
 
 - dm_reactions¶
- Whether direct message reaction related events are enabled. - See also - guild_reactionsfor guilds or- reactionsfor both.- This corresponds to the following events: - on_reaction_add()(only for DMs)
- on_reaction_remove()(only for DMs)
- on_reaction_clear()(only for DMs)
- on_raw_reaction_add()(only for DMs)
- on_raw_reaction_remove()(only for DMs)
- on_raw_reaction_clear()(only for DMs)
 - This also corresponds to the following attributes and classes in terms of cache: - Message.reactions(only for DM messages)
 - Type:
 
 - typing¶
- Whether guild and direct message typing related events are enabled. - This is a shortcut to set or get both - guild_typingand- dm_typing.- This corresponds to the following events: - on_typing()(both guilds and DMs)
 - This does not correspond to any attributes or classes in the library in terms of cache. - Type:
 
 - guild_typing¶
- Whether guild typing related events are enabled. - See also - dm_typingfor DMs or- typingfor both.- This corresponds to the following events: - on_typing()(only for guilds)
 - This does not correspond to any attributes or classes in the library in terms of cache. - Type:
 
 - dm_typing¶
- Whether direct message typing related events are enabled. - See also - guild_typingfor guilds or- typingfor both.- This corresponds to the following events: - on_typing()(only for DMs)
 - This does not correspond to any attributes or classes in the library in terms of cache. - Type:
 
 - guild_scheduled_events¶
- Whether guild scheduled event related events are enabled. - New in version 2.3. - This corresponds to the following events: - This also corresponds to the following attributes and classes in terms of cache: - Type:
 
 - automod_configuration¶
- Whether auto moderation configuration related events are enabled. - New in version 2.6. - This corresponds to the following events: - This does not correspond to any attributes or classes in the library in terms of cache. - Type:
 
 - automod_execution¶
- Whether auto moderation execution related events are enabled. - New in version 2.6. - This corresponds to the following events: - This does not correspond to any attributes or classes in the library in terms of cache. - Type:
 
 - automod¶
- Whether auto moderation related events are enabled. - New in version 2.6. - This is a shortcut to set or get both - automod_configurationand- automod_execution.- This corresponds to the following events: - This does not correspond to any attributes or classes in the library in terms of cache. - Type:
 
 - polls¶
- Whether guild and direct message polls related events are enabled. - This is a shortcut to set or get both - guild_pollsand- dm_polls.- This corresponds to the following events: - on_poll_vote_add()(both guilds and DMs)
- on_poll_vote_remove()(both guilds and DMs)
- on_raw_poll_vote_add()(both guilds and DMs)
- on_raw_poll_vote_remove()(both guilds and DMs)
 - Type:
 
 - guild_polls¶
- Whether guild polls related events are enabled. - New in version 2.10. - This corresponds to the following events: - on_poll_vote_add()(only for guilds)
- on_poll_vote_remove()(only for guilds)
- on_raw_poll_vote_add()(only for guilds)
- on_raw_poll_vote_remove()(only for guilds)
 - This also corresponds to the following attributes and classes in terms of cache: - Message.poll(only for guild messages)
- Polland all its attributes.
 - Type:
 
 - dm_polls¶
- Whether direct message polls related events are enabled. - New in version 2.10. - This corresponds to the following events: - on_poll_vote_add()(only for DMs)
- on_poll_vote_remove()(only for DMs)
- on_raw_poll_vote_add()(only for DMs)
- on_raw_poll_vote_remove()(only for DMs)
 - This also corresponds to the following attributes and classes in terms of cache: - Message.poll(only for DM messages)
- Polland all its attributes.
 - Type:
 
 
MemberCacheFlags¶
- class disnake.MemberCacheFlags(**kwargs)[source]¶
- Controls the library’s cache policy when it comes to members. - This allows for finer grained control over what members are cached. Note that the bot’s own member is always cached. This class is passed to the - member_cache_flagsparameter in- Client.- Due to a quirk in how Discord works, in order to ensure proper cleanup of cache resources it is recommended to have - Intents.membersenabled. Otherwise the library cannot know when a member leaves a guild and is thus unable to cleanup after itself.- To construct an object you can pass keyword arguments denoting the flags to enable or disable. Arguments are applied in order, similar to - Permissions.- The default value is all flags enabled. - New in version 1.5. - x == y
- Checks if two MemberCacheFlags instances are equal. 
 - x != y
- Checks if two MemberCacheFlags instances are not equal. 
 - x <= y
- Checks if a MemberCacheFlags instance is a subset of another MemberCacheFlags instance. - New in version 2.6. 
 - x >= y
- Checks if a MemberCacheFlags instance is a superset of another MemberCacheFlags instance. - New in version 2.6. 
 - x < y
- Checks if a MemberCacheFlags instance is a strict subset of another MemberCacheFlags instance. - New in version 2.6. 
 - x > y
- Checks if a MemberCacheFlags instance is a strict superset of another MemberCacheFlags instance. - New in version 2.6. 
 - x | y, x |= y
- Returns a new MemberCacheFlags 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 MemberCacheFlags 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 MemberCacheFlags 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 MemberCacheFlags 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.
 - Additionally supported are a few operations on class attributes. - MemberCacheFlags.y | MemberCacheFlags.z, MemberCacheFlags(y=True) | MemberCacheFlags.z
- Returns a MemberCacheFlags instance with all provided flags enabled. - New in version 2.6. 
 - ~MemberCacheFlags.y
- Returns a MemberCacheFlags instance with all flags except - yinverted from their default value.- New in version 2.6. 
 - value¶
- The raw value. You should query flags via the properties rather than using this raw value. - Type:
 
 - classmethod all()[source]¶
- A factory method that creates a - MemberCacheFlagsinstance with everything enabled.
 - classmethod none()[source]¶
- A factory method that creates a - MemberCacheFlagsinstance with everything disabled.
 - voice¶
- Whether to cache members that are in voice. - This requires - Intents.voice_states.- Members that leave voice are no longer cached. - Type:
 
 - joined¶
- Whether to cache members that joined the guild or are chunked as part of the initial log in flow. - This requires - Intents.members.- Members that leave the guild are no longer cached. - Type:
 
 - classmethod from_intents(intents)[source]¶
- A factory method that creates a - MemberCacheFlagsinstance based on the currently selected- Intents.- Parameters:
- intents ( - Intents) – The intents to select from.
- Returns:
- The resulting member cache flags. 
- Return type: