Context

This section documents command context for Prefix Commands.

Classes

Context

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.

message

The message that triggered the command being executed.

Type:

Message

bot

The bot that contains the command being executed.

Type:

Bot

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:

list

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:

dict

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]

prefix

The prefix that was used to invoke the command.

Type:

Optional[str]

command

The command that is being invoked currently.

Type:

Optional[Command]

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]

command_failed

Whether the command failed to be parsed, checked, or invoked.

Type:

bool

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. If None, 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 to True, return messages in oldest->newest order. Defaults to True if after is 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 with and async 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.

Parameters:
  • command (Command) – The command that is going to be called.

  • *args – The arguments to use.

  • **kwargs – The keyword arguments to use.

Raises:

TypeError – The command argument to invoke is missing.

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 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:
  • call_hooks (bool) – Whether to call the before and after invoke hooks.

  • restart (bool) – Whether to start the call chain from the very beginning or where we left off (i.e. the command that caused the error). The default is to start where we left off.

Raises:

ValueError – The context to reinvoke is not valid.

property valid[source]

Whether the invocation context is valid to be invoked with.

Type:

bool

property clean_prefix[source]

The cleaned up invoke prefix. i.e. mentions are @name instead of <@id>.

New in version 2.0.

Type:

str

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 for Message.author

me

Union[Member, ClientUser]: Similar to Guild.me except it may return the ClientUser 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 a Command.

Note

Due to the way this function works, instead of returning something similar to command_not_found() this returns None on bad input or no help command.

Parameters:

entity (Optional[Union[Command, Cog, str]]) – The entity to show help for.

Returns:

The result of the help command, if any.

Return type:

Any

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_exists keyword argument. Defaults to True.

Changed in version 2.6: Raises TypeError or ValueError instead of InvalidArgument.

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 and embeds, or file and files, or view and components.

  • ValueError – The files or embeds list is too large.

Returns:

The message that was sent.

Return type:

Message

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:

Message

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 complete Message.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, or view must be provided.

To upload a single file, the file parameter should be used with a single File object. To upload multiple files, the files parameter should be used with a list of File objects. Specifying both parameters will lead to an exception.

To upload a single embed, the embed parameter should be used with a single Embed object. To upload multiple embeds, the embeds parameter should be used with a list of Embed objects. Specifying both parameters will lead to an exception.

Changed in version 2.6: Raises TypeError or ValueError instead of InvalidArgument.

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 the embeds 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 the files parameter.

  • files (List[File]) – A list of files to upload. Must be a maximum of 10. This cannot be mixed with the file 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 in Client.allowed_mentions. If no object is passed at all then the defaults given by Client.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 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_user attribute of allowed_mentions or by setting mention_author.

    New in version 1.6.

  • mention_author (Optional[bool]) –

    If set, overrides the AllowedMentions.replied_user attribute 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 (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 and suppress_notifications are supported.

    If parameter suppress_embeds is provided, that will override the setting of MessageFlags.suppress_embeds.

    New in version 2.9.

Raises:
Returns:

The message that was sent.

Return type:

Message

await trigger_typing()[source]

This function is a coroutine.

Triggers a typing indicator to the destination.

Typing indicator will go away after 10 seconds, or after a message is sent.