Context¶
This section documents command context for Prefix Commands.
Classes¶
Context¶
- asyncfetch_message
- defhistory
- asyncinvoke
- asyncpins
- 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.Messageable
ABC.- 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 theon_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:
Optional[
inspect.Parameter
]
- invoked_with¶
The command name that triggered this invocation. Useful for finding out which alias called the command.
- Type:
Optional[
str
]
- 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.
- Type:
List[
str
]
- invoked_subcommand¶
The subcommand that was invoked. If no valid subcommand was invoked then this is equal to
None
.- Type:
Optional[
Command
]
- 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
.- Type:
Optional[
str
]
- async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)[source]¶
Returns an
AsyncIterator
that enables receiving the destination’s message history.You must have
Permissions.read_message_history
permission 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 toTrue
ifafter
is 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
with
andasync with
work 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
Command
holds 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
UserInputError
derived exceptions, it is recommended to use the regularinvoke()
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
@name
instead of<@id>
.New in version 2.0.
- Type:
- property cog[source]¶
Returns the cog associated with this context’s command. Returns
None
if it does not exist.- Type:
Optional[
Cog
]
- guild¶
Returns the guild associated with this context’s command. Returns
None
if not available.- Type:
Optional[
Guild
]
- channel¶
Returns the channel associated with this context’s command. Shorthand for
Message.channel
.- Type:
Union[
abc.Messageable
]
- author¶
Union[
User
,Member
]: Returns the author associated with this context’s command. Shorthand forMessage.author
- me¶
Union[
Member
,ClientUser
]: Similar toGuild.me
except it may return theClientUser
in private message contexts.
- property voice_client[source]¶
A shortcut to
Guild.voice_client
, if applicable.- Type:
Optional[
VoiceProtocol
]
- 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
Cog
or aCommand
.Note
Due to the way this function works, instead of returning something similar to
command_not_found()
this returnsNone
on 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 theMessage
.New in version 1.6.
Changed in version 2.3: Added
fail_if_not_exists
keyword argument. Defaults toTrue
.Changed in version 2.6: Raises
TypeError
orValueError
instead ofInvalidArgument
.- Parameters:
fail_if_not_exists (
bool
) –Whether replying using the message reference should raise
HTTPException
if 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
embed
andembeds
, orfile
andfiles
, orview
andcomponents
.ValueError – The
files
orembeds
list is too large.
- Returns:
The message that was sent.
- Return type:
- await fetch_message(id, /)[source]¶
This function is a coroutine.
Retrieves a single
Message
from 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
Message
objects returned by this method do not contain completeMessage.reactions
data.- 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=None, flags=None, 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
, orview
must be provided.To upload a single file, the
file
parameter should be used with a singleFile
object. To upload multiple files, thefiles
parameter should be used with alist
ofFile
objects. Specifying both parameters will lead to an exception.To upload a single embed, the
embed
parameter should be used with a singleEmbed
object. To upload multiple embeds, theembeds
parameter should be used with alist
ofEmbed
objects. Specifying both parameters will lead to an exception.Changed in version 2.6: Raises
TypeError
orValueError
instead 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 theembeds
parameter.embeds (List[
Embed
]) –A list of embeds to send with the content. Must be a maximum of 10. This cannot be mixed with the
embed
parameter.New in version 2.0.
file (
File
) – The file to upload. This cannot be mixed with thefiles
parameter.files (List[
File
]) – A list of files to upload. Must be a maximum of 10. This cannot be mixed with thefile
parameter.stickers (Sequence[Union[
GuildSticker
,StandardSticker
,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_mentions
are used instead.New in version 1.4.
reference (Union[
Message
,MessageReference
,PartialMessage
]) –A reference to the
Message
to 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_user
attribute ofallowed_mentions
or by settingmention_author
.New in version 1.6.
mention_author (Optional[
bool
]) –If set, overrides the
AllowedMentions.replied_user
attribute 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 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
andsuppress_notifications
are supported.If parameter
suppress_embeds
is provided, that will override the setting ofMessageFlags.suppress_embeds
.New in version 2.9.
- Raises:
HTTPException – Sending the message failed.
Forbidden – You do not have the proper permissions to send the message.
TypeError – Specified both
file
andfiles
, or you specified bothembed
andembeds
, or you specified bothview
andcomponents
, or thereference
object is not aMessage
,MessageReference
orPartialMessage
.ValueError – The
files
orembeds
list is too large.
- Returns:
The message that was sent.
- Return type: