Context¶
This section documents command context for Prefix Commands.
Classes¶
Context¶
- asyncfetch_message
- defhistory
- asyncinvoke
- defpins
- asyncreinvoke
- asyncreply
- asyncsend
- asyncsend_help
- asynctrigger_typing
- deftyping
- class disnake.ext.commands.Context(*, message, bot, view, args=..., kwargs=..., prefix=None, command=None, invoked_with=None, invoked_parents=..., invoked_subcommand=None, subcommand_passed=None, command_failed=False, current_parameter=None)[source]¶
- Represents the context in which a command is being invoked under. - This class contains a lot of meta data to help you understand more about the invocation context. This class is not created manually and is instead passed around to commands as the first parameter. - This class implements the - abc.MessageableABC.- args¶
- The list of transformed arguments that were passed into the command. If this is accessed during the - on_command_error()event then this list could be incomplete.- Type:
 
 - kwargs¶
- A dictionary of transformed arguments that were passed into the command. Similar to - args, if this is accessed in the- on_command_error()event then this dict could be incomplete.- Type:
 
 - current_parameter¶
- The parameter that is currently being inspected and converted. This is only of use for within converters. - New in version 2.0. - Type:
 
 - invoked_with¶
- The command name that triggered this invocation. Useful for finding out which alias called the command. 
 - invoked_parents¶
- The command names of the parents that triggered this invocation. Useful for finding out which aliases called the command. - For example in commands - ?a b c test, the invoked parents are- ['a', 'b', 'c'].- New in version 1.7. 
 - invoked_subcommand¶
- The subcommand that was invoked. If no valid subcommand was invoked then this is equal to - None.
 - subcommand_passed¶
- The string that was attempted to call a subcommand. This does not have to point to a valid registered subcommand and could just point to a nonsense string. If nothing was passed to attempt a call to a subcommand then this is set to - None.
 - async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)[source]¶
- Returns an - AsyncIteratorthat enables receiving the destination’s message history.- You must have - Permissions.read_message_historypermission to use this.- Examples - Usage - counter = 0 async for message in channel.history(limit=200): if message.author == client.user: counter += 1 - Flattening into a list: - messages = await channel.history(limit=123).flatten() # messages is now a list of Message... - All parameters are optional. - Parameters:
- limit ( - int|- None) – The number of messages to retrieve. If- None, retrieves every message in the channel. Note, however, that this would make it a slow operation.
- before ( - abc.Snowflake|- datetime.datetime|- None) – Retrieve messages before this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.
- after ( - abc.Snowflake|- datetime.datetime|- None) – Retrieve messages after this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.
- around ( - abc.Snowflake|- datetime.datetime|- None) – Retrieve messages around this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time. When using this argument, the maximum limit is 101. Note that if the limit is an even number then this will return at most limit + 1 messages.
- oldest_first ( - bool|- None) – If set to- True, return messages in oldest->newest order. Defaults to- Trueif- afteris specified, otherwise- False.
 
- 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 - withand- async withwork with this.- Example Usage: - async with channel.typing(): # simulate something heavy await asyncio.sleep(10) await channel.send('done!') 
 - await invoke(command, /, *args, **kwargs)[source]¶
- This function is a coroutine. - Calls a command with the arguments given. - This is useful if you want to just call the callback that a - Commandholds internally.- Note - This does not handle converters, checks, cooldowns, pre-invoke, or after-invoke hooks in any matter. It calls the internal callback directly as-if it was a regular function. - You must take care in passing the proper arguments when using this function. 
 - await reinvoke(*, call_hooks=False, restart=True)[source]¶
- This function is a coroutine. - Calls the command again. - This is similar to - invoke()except that it bypasses checks, cooldowns, and error handlers.- Note - If you want to bypass - UserInputErrorderived exceptions, it is recommended to use the regular- invoke()as it will work more naturally. After all, this will end up using the old arguments the user has used and will thus just fail again.- Parameters:
- Raises:
- ValueError – The context to reinvoke is not valid. 
 
 - property clean_prefix[source]¶
- The cleaned up invoke prefix. i.e. mentions are - @nameinstead of- <@id>.- New in version 2.0. - Type:
 
 - property cog[source]¶
- Returns the cog associated with this context’s command. Returns - Noneif it does not exist.
 - channel¶
- Returns the channel associated with this context’s command. Shorthand for - Message.channel.- Type:
 
 - author¶
- User|- Member: Returns the author associated with this context’s command. Shorthand for- Message.author
 - me¶
- Member|- ClientUser: Similar to- Guild.meexcept it may return the- ClientUserin private message contexts.
 - property voice_client[source]¶
- A shortcut to - Guild.voice_client, if applicable.- Type:
 
 - await send_help(*args)[source]¶
- This function is a coroutine. - Shows the help command for the specified entity if given. The entity can be a command or a cog. - If no entity is given, then it’ll show help for the entire bot. - If the entity is a string, then it looks up whether it’s a - Cogor a- Command.- Note - Due to the way this function works, instead of returning something similar to - command_not_found()this returns- Noneon bad input or no help command.
 - await reply(content=None, *, fail_if_not_exists=True, **kwargs)[source]¶
- This function is a coroutine. - A shortcut method to - abc.Messageable.send()to reply to the- Message.- New in version 1.6. - Changed in version 2.3: Added - fail_if_not_existskeyword argument. Defaults to- True.- Changed in version 2.6: Raises - TypeErroror- ValueErrorinstead of- InvalidArgument.- Parameters:
- fail_if_not_exists ( - bool) –- Whether replying using the message reference should raise - HTTPExceptionif the message no longer exists or Discord could not fetch the message.- New in version 2.3. 
- Raises:
- HTTPException – Sending the message failed. 
- Forbidden – You do not have the proper permissions to send the message. 
- TypeError – You specified both - embedand- embeds, or- fileand- files, or- viewand- components.
- ValueError – The - filesor- embedslist is too large.
 
- Returns:
- The message that was sent. 
- Return type:
 
 - await fetch_message(id, /)[source]¶
- This function is a coroutine. - Retrieves a single - Messagefrom the destination.- Parameters:
- id ( - int) – The message ID to look for.
- Raises:
- NotFound – The specified message was not found. 
- Forbidden – You do not have the permissions required to get a message. 
- HTTPException – Retrieving the message failed. 
 
- Returns:
- The message asked for. 
- Return type:
 
 - pins(*, limit=50, before=None)[source]¶
- Returns an - AsyncIteratorthat enables receiving the destination’s pinned messages.- You must have the - Permissions.read_message_historyand- Permissions.view_channelpermissions to use this.- Note - Due to a limitation with the Discord API, the - Messageobjects returned by this method do not contain complete- Message.reactionsdata.- Changed in version 2.11: Now returns an - AsyncIteratorto support changes in Discord’s API.- awaiting the result of this method remains supported, but only returns the last 50 pins and is deprecated in favor of- async for msg in channel.pins().- Examples - Usage - counter = 0 async for message in channel.pins(limit=100): if message.author == client.user: counter += 1 - Flattening to a list - pinned_messages = await channel.pins(limit=100).flatten() # pinned_messages is now a list of Message... - All parameters are optional. - Parameters:
- limit ( - int|- None) – The number of pinned messages to retrieve. If- None, retrieves every pinned message in the channel. Note, however, that this would make it a slow operation.
- before ( - abc.Snowflake|- datetime.datetime|- None) – Retrieve messages pinned before this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.
 
- Raises:
- HTTPException – Retrieving the pinned messages failed. 
- Yields:
- Message– The pinned message from the parsed message data.
 
 - await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, suppress_embeds=None, flags=None, allowed_mentions=None, reference=None, mention_author=None, view=None, components=None, poll=None)[source]¶
- This function is a coroutine. - Sends a message to the destination with the content given. - The content must be a type that can convert to a string through - str(content).- At least one of - content,- embed/- embeds,- file/- files,- stickers,- components,- pollor- viewmust be provided.- To upload a single file, the - fileparameter should be used with a single- Fileobject. To upload multiple files, the- filesparameter should be used with a- listof- Fileobjects. Specifying both parameters will lead to an exception.- To upload a single embed, the - embedparameter should be used with a single- Embedobject. To upload multiple embeds, the- embedsparameter should be used with a- listof- Embedobjects. Specifying both parameters will lead to an exception.- Changed in version 2.6: Raises - TypeErroror- ValueErrorinstead of- InvalidArgument.- Parameters:
- tts ( - bool) – Whether the message should be sent using text-to-speech.
- embed ( - Embed) – The rich embed for the content to send. This cannot be mixed with the- embedsparameter.
- 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 the- filesparameter.
- files ( - list[- File]) – A list of files to upload. Must be a maximum of 10. This cannot be mixed with the- fileparameter.
- stickers ( - Sequence[- GuildSticker|- StandardSticker|- StickerItem]) –- A list of stickers to upload. Must be a maximum of 3. - New in version 2.0. 
- nonce ( - str|- int) – The nonce to use for sending this message. If the message was successfully sent, then the message will have a nonce with this value.
- delete_after ( - float) – If provided, the number of seconds to wait in the background before deleting the message we just sent. If the deletion fails, then it is silently ignored.
- allowed_mentions ( - AllowedMentions) –- Controls the mentions being processed in this message. If this is passed, then the object is merged with - Client.allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set in- Client.allowed_mentions. If no object is passed at all then the defaults given by- Client.allowed_mentionsare used instead.- New in version 1.4. 
- reference ( - Message|- MessageReference|- PartialMessage) –- A reference to the - Messageto which you are replying, this can be created using- Message.to_reference()or passed directly as a- Message. You can control whether this mentions the author of the referenced message using the- AllowedMentions.replied_userattribute of- allowed_mentionsor by setting- mention_author.- New in version 1.6. - Note - Passing a - Messageor- PartialMessagewill only allow replies. To forward a message you must explicitly transform the message to a- MessageReferenceusing- Message.to_reference()and specify the- MessageReferenceType, or use- Message.forward().
- mention_author ( - bool|- None) –- If set, overrides the - AllowedMentions.replied_userattribute of- allowed_mentions.- New in version 1.6. 
- view ( - ui.View) –- A Discord UI View to add to the message. This cannot be mixed with - components.- New in version 2.0. 
- components ( - UIComponent|- list[- UIComponent|- list[- WrappedComponent]]) –- A list of components to include in the message. This cannot be mixed with - view.- New in version 2.4. - Note - Passing v2 components here automatically sets the - is_components_v2flag. Setting this flag cannot be reverted. Note that this also disables the- content,- embeds,- stickers, and- pollfields.
- suppress_embeds ( - bool) –- Whether to suppress embeds for the message. This hides all the embeds from the UI if set to - True.- New in version 2.5. 
- flags ( - MessageFlags) –- The flags to set for this message. Only - suppress_embeds,- suppress_notifications, and- is_components_v2are supported.- If parameter - suppress_embedsis provided, that will override the setting of- MessageFlags.suppress_embeds.- New in version 2.9. 
- poll ( - Poll) –- The poll to send with the message. - New in version 2.10. 
 
- Raises:
- HTTPException – Sending the message failed. 
- Forbidden – You do not have the proper permissions to send the message. 
- TypeError – Specified both - fileand- files, or you specified both- embedand- embeds, or you specified both- viewand- components, or the- referenceobject is not a- Message,- MessageReferenceor- PartialMessage.
- ValueError – The - filesor- embedslist is too large, or you tried to send v2 components together with- content,- embeds,- stickers, or- poll.
 
- Returns:
- The message that was sent. 
- Return type: