API Reference

The following section outlines the API of Pycord's prefixed command extension module.

注釈

Using prefixed commands in guilds requires Intents.message_content to be enabled.

Bots

Bot

Methods
class discord.ext.commands.Bot(command_prefix=<function when_mentioned>, help_command=..., **options)[ソース]

Represents a discord bot.

This class is a subclass of discord.Bot and as a result anything that you can do with a discord.Bot you can do with this bot.

This class also subclasses GroupMixin to provide the functionality to manage commands.

注釈

Using prefixed commands requires discord.Intents.message_content to be enabled.

command_prefix

The command prefix is what the message content must contain initially to have a command invoked. This prefix could either be a string to indicate what the prefix should be, or a callable that takes in the bot as its first parameter and discord.Message as its second parameter and returns the prefix. This is to facilitate "dynamic" command prefixes. This callable can be either a regular function or a coroutine.

An empty string as the prefix always matches, enabling prefix-less command invocation. While this may be useful in DMs it should be avoided in servers, as it's likely to cause performance issues and unintended command invocations.

The command prefix could also be an iterable of strings indicating that multiple checks for the prefix should be used and the first one to match will be the invocation prefix. You can get this prefix via Context.prefix. To avoid confusion empty iterables are not allowed.

注釈

When passing multiple prefixes be careful to not pass a prefix that matches a longer prefix occurring later in the sequence. For example, if the command prefix is ('!', '!?') the '!?' prefix will never be matched to any message as the previous one matches messages starting with !?. This is especially important when passing an empty string, it should always be last as no prefix after it will be matched.

case_insensitive

Whether the commands should be case-insensitive. Defaults to False. This attribute does not carry over to groups. You must set it to every group if you require group commands to be case-insensitive as well.

Type:

bool

help_command

The help command implementation to use. This can be dynamically set at runtime. To remove the help command pass None. For more information on implementing a help command, see Help Commands.

Type:

Optional[HelpCommand]

strip_after_prefix

Whether to strip whitespace characters after encountering the command prefix. This allows for !   hello and !hello to both work if the command_prefix is set to !. Defaults to False.

Added in version 1.7.

Type:

bool

パラメータ:
@after_invoke

A decorator that registers a coroutine as a post-invoke hook. A post-invoke hook is called directly after the command is called. This makes it a useful function to clean-up database connections or any type of clean up required. This post-invoke hook takes a sole parameter, a Context.

注釈

Similar to before_invoke(), this is not called unless checks and argument parsing procedures succeed. This hook is, however, always called regardless of the internal command callback raising an error (i.e. CommandInvokeError). This makes it ideal for clean-up scenarios.

パラメータ:

coro (coroutine) -- The coroutine to register as the post-invoke hook.

例外:

TypeError -- The coroutine passed is not actually a coroutine.

@before_invoke

A decorator that registers a coroutine as a pre-invoke hook. A pre-invoke hook is called directly before the command is called. This makes it a useful function to set up database connections or any type of set up required. This pre-invoke hook takes a sole parameter, a Context.

注釈

The before_invoke() and after_invoke() hooks are only called if all checks and argument parsing procedures pass without error. If any check or argument parsing procedures fail then the hooks are not called.

パラメータ:

coro (coroutine) -- The coroutine to register as the pre-invoke hook.

例外:

TypeError -- The coroutine passed is not actually a coroutine.

@check

A decorator that adds a global check to the bot. A global check is similar to a check() that is applied on a per-command basis except it is run before any command checks have been verified and applies to every command the bot has.

注釈

This function can either be a regular function or a coroutine. Similar to a command check(), this takes a single parameter of type Context and can only raise exceptions inherited from ApplicationCommandError.

サンプル

@bot.check
def check_commands(ctx):
    return ctx.command.qualified_name in allowed_commands
@check_once

A decorator that adds a "call once" global check to the bot. Unlike regular global checks, this one is called only once per Bot.invoke() call. Regular global checks are called whenever a command is called or Command.can_run() is called. This type of check bypasses that and ensures that it's called only once, even inside the default help command.

注釈

When using this function the Context sent to a group subcommand may only parse the parent command and not the subcommands due to it being invoked once per Bot.invoke() call.

注釈

This function can either be a regular function or a coroutine. Similar to a command check(), this takes a single parameter of type Context and can only raise exceptions inherited from ApplicationCommandError.

サンプル

@bot.check_once
def whitelist(ctx):
    return ctx.message.author.id in my_whitelist
@command(name=..., cls=..., *args, **kwargs)

A shortcut decorator that invokes command() and adds it to the internal command list via add_command().

戻り値:

A decorator that converts the provided method into a Command, adds it to the bot, then returns it.

戻り値の型:

Callable[[Callable[[Concatenate[TypeVar(ContextT, bound= Context), ParamSpec(P, bound= None)]], Coroutine[Any, Any, Any]]], TypeVar(CommandT, bound= Command)]

パラメータ:
@event(coro)

A decorator that registers an event to listen to.

You can find more info about the events on the documentation below.

The events must be a coroutine, if not, TypeError is raised.

注釈

This replaces any default handlers. Developers are encouraged to use listen() for adding additional handlers instead of event() unless default method replacement is intended.

例外:

TypeError -- The coroutine passed is not actually a coroutine.

サンプル

@client.event
async def on_ready():
    print('Ready!')
パラメータ:

coro (TypeVar(Coro, bound= Callable[..., Coroutine[Any, Any, Any]]))

戻り値の型:

TypeVar(Coro, bound= Callable[..., Coroutine[Any, Any, Any]])

@group(name=..., cls=..., *args, **kwargs)

A shortcut decorator that invokes group() and adds it to the internal command list via add_command().

戻り値:

A decorator that converts the provided method into a Group, adds it to the bot, then returns it.

戻り値の型:

Callable[[Callable[[Concatenate[TypeVar(ContextT, bound= Context), ParamSpec(P, bound= None)]], Coroutine[Any, Any, Any]]], TypeVar(GroupT, bound= Group)]

パラメータ:
@listen(name=..., once=False)

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.

例外:
  • TypeError -- The function being listened to is not a coroutine.

  • ValueError -- The name (event name) does not start with on_.

サンプル

@client.listen()
async def on_message(message):
    print('one')

# in some other file...

@client.listen('on_message')
async def my_message(message):
    print('two')

# listen to the first event only
@client.listen('on_ready', once=True)
async def on_ready():
    print('ready!')

Would print one and two in an unspecified order.

パラメータ:
戻り値の型:

Callable[[TypeVar(Coro, bound= Callable[..., Coroutine[Any, Any, Any]])], TypeVar(Coro, bound= Callable[..., Coroutine[Any, Any, Any]])]

property activity: Activity | Game | CustomActivity | Streaming | Spotify | None

The activity being used upon logging in.

戻り値の型:

Optional[BaseActivity]

add_application_command(command)

Adds an ApplicationCommand into the internal list of commands.

This is usually not called, instead the command() or other shortcut decorators are used instead.

Added in version 2.0.

パラメータ:

command (ApplicationCommand) -- The command to add.

戻り値の型:

None

add_check(func, *, call_once=False)

Adds a global check to the bot. This is the non-decorator interface to check() and check_once().

パラメータ:
  • func -- The function that was used as a global check.

  • call_once (bool) -- If the function should only be called once per Bot.invoke() call.

戻り値の型:

None

add_cog(cog, *, override=False)

Adds a "cog" to the bot.

A cog is a class that has its own event listeners and commands.

バージョン 2.0 で変更: ClientException is raised when a cog with the same name is already loaded.

パラメータ:
  • cog (Cog) -- The cog to register to the bot.

  • override (bool) --

    If a previously loaded cog with the same name should be ejected instead of raising an error.

    Added in version 2.0.

例外:
戻り値の型:

None

add_command(command)

Adds a Command into the internal list of commands.

This is usually not called, instead the command() or group() shortcut decorators are used instead.

バージョン 1.4 で変更: Raise CommandRegistrationError instead of generic ClientException

パラメータ:

command (Command[TypeVar(CogT, bound= Cog), Any, Any]) -- The command to add.

例外:
  • .CommandRegistrationError -- If the command or its alias is already registered by different command.

  • TypeError -- If the command passed is not a subclass of Command.

戻り値の型:

None

add_listener(func, name=...)

The non decorator alternative to listen().

パラメータ:
例外:
  • TypeError -- The func parameter is not a coroutine function.

  • ValueError -- The name (event name) does not start with on_.

戻り値の型:

None

サンプル

async def on_ready(): pass
async def my_message(message): pass

client.add_listener(on_ready)
client.add_listener(my_message, 'on_message')
add_view(view, *, message_id=None)

Registers a BaseView for persistent listening.

This method should be used for when a view is comprised of components that last longer than the lifecycle of the program.

Added in version 2.0.

パラメータ:
  • view (BaseView) -- The view to register for dispatching.

  • message_id (int | None) -- 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.

例外:
  • 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.

戻り値の型:

None

property allowed_mentions: AllowedMentions | None

The allowed mention configuration.

Added in version 1.4.

property app_emojis: list[AppEmoji]

The AppEmoji that the connected client has.

注釈

This is only available if cache_app_emojis is True.

application_command(*, cls=<class 'discord.commands.core.SlashCommand'>, checks=..., cog=..., contexts=..., cooldown=..., default_member_permissions=..., description=..., description_localizations=..., guild_ids=..., guild_only=..., integration_types=..., name=..., name_localizations=..., nsfw=..., options=..., parent=..., **kwargs)

A shortcut decorator that converts the provided function into an application command via command() and adds it to the internal command list via add_application_command().

Added in version 2.0.

パラメータ:
戻り値:

A decorator that converts the provided function into an ApplicationCommand, adds it to the bot, and returns it.

戻り値の型:

Callable[..., TypeVar(C, bound= MessageCommand | SlashCommand | UserCommand)]

property application_flags: ApplicationFlags

The client's application flags.

Added in version 2.0.

property application_id: int | None

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.

Added in version 2.0.

await application_info()

This function is a coroutine.

Retrieves the bot's application information.

戻り値:

The bot's application information.

戻り値の型:

AppInfo

例外:

HTTPException -- Retrieving the information failed somehow.

await before_identify_hook(shard_id, *, initial=False)

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.

Added in version 1.4.

パラメータ:
  • shard_id (int | None) -- The shard ID that requested being IDENTIFY'd

  • initial (bool) -- Whether this IDENTIFY is the first initial IDENTIFY.

戻り値の型:

None

property cached_messages: Sequence[Message]

Read-only list of messages the connected client has cached.

Added in version 1.1.

await change_presence(*, activity=None, status=None)

This function is a coroutine.

Changes the client's presence.

パラメータ:
  • activity (BaseActivity | None) -- The activity being done. None if no currently active activity is done.

  • status (Status | None) -- Indicates what status to change to. If None, then Status.online is used.

例外:

InvalidArgument -- If the activity parameter is not the proper type.

サンプル

game = discord.Game("with the API")
await client.change_presence(status=discord.Status.idle, activity=game)

バージョン 2.0 で変更: Removed the afk keyword-only parameter.

clear()

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 False along with the bot's internal cache cleared.

戻り値の型:

None

await close()

This function is a coroutine.

Closes the connection to Discord.

戻り値の型:

None

property cogs: Mapping[str, Cog]

A read-only mapping of cog name to cog.

property commands: set[Command[CogT, Any, Any]]

A unique set of commands without aliases that are registered.

await connect(*, reconnect=True)

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.

パラメータ:

reconnect (bool) -- If we should attempt reconnecting, 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).

例外:
  • GatewayNotFound -- 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.

戻り値の型:

None

await create_dm(user)

This function is a coroutine.

Creates a DMChannel with this user.

This should be rarely called, as this is done transparently for most people.

Added in version 2.0.

パラメータ:

user (Snowflake) -- The user to create a DM with.

戻り値:

The channel that was created.

戻り値の型:

DMChannel

await create_emoji(*, name, image)

This function is a coroutine.

Creates a custom AppEmoji for the application.

There is currently a limit of 2000 emojis per application.

パラメータ:
  • name (str) -- The emoji name. Must be at least 2 characters.

  • image (bytes) -- The bytes-like object representing the image data to use. Only JPG, PNG and GIF images are supported.

例外:

HTTPException -- An error occurred creating an emoji.

戻り値:

The created emoji.

戻り値の型:

AppEmoji

create_group(name, description=None, guild_ids=None, **kwargs)

A shortcut method that creates a slash command group with no subcommands and adds it to the internal command list via add_application_command().

Added in version 2.0.

パラメータ:
  • name (str) -- The name of the group to create.

  • description (str | None) -- The description of the group to create.

  • guild_ids (list[int] | None) -- A list of the IDs of each guild this group should be added to, making it a guild command. This will be a global command if None is passed.

  • kwargs -- Any additional keyword arguments to pass to SlashCommandGroup.

戻り値:

The slash command group that was created.

戻り値の型:

SlashCommandGroup

await delete_emoji(emoji)

This function is a coroutine.

Deletes the custom AppEmoji from the application.

パラメータ:

emoji (Snowflake) -- The emoji you are deleting.

例外:

HTTPException -- An error occurred deleting the emoji.

戻り値の型:

None

await delete_invite(invite)

This function is a coroutine.

Revokes an Invite, URL, or ID to an invite.

You must have the manage_channels permission in the associated guild to do this.

パラメータ:

invite (Invite | str) -- The invite to revoke.

例外:
  • Forbidden -- You do not have permissions to revoke invites.

  • NotFound -- The invite is invalid or expired.

  • HTTPException -- Revoking the invite failed.

戻り値の型:

None

property emojis: list[GuildEmoji | AppEmoji]

The emojis that the connected client has.

注釈

This only includes the application's emojis if cache_app_emojis is True.

entitlements(user=None, skus=None, before=None, after=None, limit=100, guild=None, exclude_ended=False)

Returns an AsyncIterator that enables fetching the application's entitlements.

Added in version 2.6.

パラメータ:
  • user (Snowflake | None) -- Limit the fetched entitlements to entitlements owned by this user.

  • skus (list[Snowflake] | None) -- Limit the fetched entitlements to entitlements that are for these SKUs.

  • before (Snowflake | datetime | None) -- 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 (Snowflake | datetime | None) -- 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.

  • limit (int | None) -- The number of entitlements to retrieve. If None, retrieves every entitlement, which may be slow. Defaults to 100.

  • guild (Snowflake | None) -- Limit the fetched entitlements to entitlements owned by this guild.

  • exclude_ended (bool) -- Whether to limit the fetched entitlements to those that have not ended. Defaults to False.

列挙:

Entitlement -- The application's entitlements.

例外:

HTTPException -- Retrieving the entitlements failed.

戻り値の型:

EntitlementIterator

サンプル

Usage

async for entitlement in client.entitlements():
    print(entitlement.user_id)

Flattening into a list

entitlements = await user.entitlements().flatten()

All parameters are optional.

property extensions: Mapping[str, ModuleType]

A read-only mapping of extension name to extension.

await fetch_application(application_id, /)

This function is a coroutine. Retrieves a PartialAppInfo from an application ID.

パラメータ:

application_id (int) -- The application ID to retrieve information from.

戻り値:

The application information.

戻り値の型:

PartialAppInfo

例外:
  • NotFound -- An application with this ID does not exist.

  • HTTPException -- Retrieving the application failed.

await fetch_channel(channel_id, /)

This function is a coroutine.

Retrieves a abc.GuildChannel, abc.PrivateChannel, or Thread with the specified ID.

注釈

This method is an API call. For general usage, consider get_channel() instead.

Added in version 1.2.

戻り値:

The channel from the ID.

戻り値の型:

GuildChannel | PrivateChannel | Thread

例外:
  • 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.

パラメータ:

channel_id (int)

await fetch_default_sounds()

This function is a coroutine.

Fetches the bot's default sounds.

Added in version 2.7.

戻り値:

The bot's default sounds.

戻り値の型:

list[SoundboardSound]

await fetch_emoji(emoji_id, /)

This function is a coroutine.

Retrieves a custom AppEmoji from the application.

パラメータ:

emoji_id (int) -- The emoji's ID.

戻り値:

The retrieved emoji.

戻り値の型:

AppEmoji

例外:
  • NotFound -- The emoji requested could not be found.

  • HTTPException -- An error occurred fetching the emoji.

await fetch_emojis()

This function is a coroutine.

Retrieves all custom AppEmojis from the application.

例外:

HTTPException -- An error occurred fetching the emojis.

戻り値:

The retrieved emojis.

戻り値の型:

list[AppEmoji]

await fetch_guild(guild_id, /, *, with_counts=True)

This function is a coroutine.

Retrieves a Guild from an ID.

注釈

Using this, you will not receive Guild.channels, Guild.members, Member.activity and Member.voice per Member.

注釈

This method is an API call. For general usage, consider get_guild() instead.

パラメータ:
戻り値:

The guild from the ID.

戻り値の型:

Guild

例外:
fetch_guilds(*, limit=100, before=None, after=None, with_counts=True)

Retrieves an AsyncIterator that enables receiving your guilds.

注釈

Using this, you will only receive Guild.owner, Guild.icon, Guild.id, and Guild.name per Guild.

注釈

This method is an API call. For general usage, consider guilds instead.

パラメータ:
  • limit (int | None) -- 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 (Snowflake | 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 (Snowflake | 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 member count information in guilds. This fills the Guild.approximate_member_count and Guild.approximate_presence_count fields. Defaults to True.

列挙:

Guild -- The guild with the guild data parsed.

例外:

HTTPException -- Getting the guilds failed.

戻り値の型:

GuildIterator

サンプル

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.

await fetch_invite(url, *, with_counts=True, with_expiration=True, event_id=None)

This function is a coroutine.

Gets an Invite from a discord.gg URL or ID.

注釈

If the invite is for a guild you have not joined, the guild and channel attributes of the returned Invite will be PartialInviteGuild and PartialInviteChannel respectively.

パラメータ:
  • url (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_count and Invite.approximate_presence_count fields.

  • with_expiration (bool) --

    Whether to include the expiration date of the invite. This fills the Invite.expires_at field.

    Added in version 2.0.

  • event_id (int | None) --

    The ID of the scheduled event to be associated with the event.

    See Invite.set_scheduled_event() for more info on event invite linking.

    Added in version 2.0.

戻り値:

The invite from the URL/ID.

戻り値の型:

Invite

例外:
await fetch_premium_sticker_packs()

This function is a coroutine.

Retrieves all available premium sticker packs.

Added in version 2.0.

戻り値:

All available premium sticker packs.

戻り値の型:

list[StickerPack]

例外:

HTTPException -- Retrieving the sticker packs failed.

await fetch_role_connection_metadata_records()

This function is a coroutine.

Fetches the bot's role connection metadata records.

Added in version 2.4.

戻り値:

The bot's role connection metadata records.

戻り値の型:

list[ApplicationRoleConnectionMetadata]

await fetch_skus()

This function is a coroutine.

Fetches the bot's SKUs.

Added in version 2.5.

戻り値:

The bot's SKUs.

戻り値の型:

list[SKU]

await fetch_stage_instance(channel_id, /)

This function is a coroutine.

Gets a StageInstance for a stage channel id.

Added in version 2.0.

パラメータ:

channel_id (int) -- The stage channel ID.

戻り値:

The stage instance from the stage channel ID.

戻り値の型:

StageInstance

例外:
  • NotFound -- The stage instance or channel could not be found.

  • HTTPException -- Getting the stage instance failed.

await fetch_sticker(sticker_id, /)

This function is a coroutine.

Retrieves a Sticker with the specified ID.

Added in version 2.0.

戻り値:

The sticker you requested.

戻り値の型:

StandardSticker | GuildSticker

例外:
パラメータ:

sticker_id (int)

await fetch_template(code)

This function is a coroutine.

Gets a Template from a discord.new URL or code.

パラメータ:

code (Template | str) -- The Discord Template Code or URL (must be a discord.new URL).

戻り値:

The template from the URL/code.

戻り値の型:

Template

例外:
await fetch_user(user_id, /)

This function is a coroutine.

Retrieves a User based 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.

注釈

This method is an API call. If you have discord.Intents.members and member cache enabled, consider get_user() instead.

パラメータ:

user_id (int) -- The user's ID to fetch from.

戻り値:

The user you requested.

戻り値の型:

User

例外:
await fetch_webhook(webhook_id, /)

This function is a coroutine.

Retrieves a Webhook with the specified ID.

戻り値:

The webhook you requested.

戻り値の型:

Webhook

例外:
パラメータ:

webhook_id (int)

await fetch_widget(guild_id, /)

This function is a coroutine.

Gets a Widget from a guild ID.

注釈

The guild must have the widget enabled to get this information.

パラメータ:

guild_id (int) -- The ID of the guild.

戻り値:

The guild's widget.

戻り値の型:

Widget

例外:
get_all_channels()

A generator that retrieves every abc.GuildChannel the client can 'access'.

This is equivalent to:

for guild in client.guilds:
    for channel in guild.channels:
        yield channel

注釈

Just because you receive a abc.GuildChannel does not mean that you can communicate in said channel. abc.GuildChannel.permissions_for() should be used for that.

列挙:

abc.GuildChannel -- A channel the client can 'access'.

戻り値の型:

Generator[GuildChannel, None, None]

get_all_members()

Returns a generator with every Member the client can see.

This is equivalent to:

for guild in client.guilds:
    for member in guild.members:
        yield member
列挙:

Member -- A member the client can see.

戻り値の型:

Generator[Member, None, None]

get_application_command(name, guild_ids=None, type=<class 'discord.commands.core.ApplicationCommand'>)

Get an ApplicationCommand from the internal list of commands.

Added in version 2.0.

パラメータ:
戻り値:

The command that was requested. If not found, returns None.

戻り値の型:

ApplicationCommand | None

await get_application_context(interaction, cls=<class 'discord.commands.context.ApplicationContext'>)

This function is a coroutine.

Returns the invocation context from the interaction.

This is a more low-level counter-part for process_application_commands() to allow users more fine-grained control over the processing.

パラメータ:
  • interaction (Interaction) -- The interaction to get the invocation context from.

  • cls (Any) -- The factory class that will be used to create the context. By default, this is ApplicationContext. Should a custom class be provided, it must be similar enough to ApplicationContext's interface.

戻り値:

The invocation context. The type of this can change via the cls parameter.

戻り値の型:

ApplicationContext

await get_autocomplete_context(interaction, cls=<class 'discord.commands.context.AutocompleteContext'>)

This function is a coroutine.

Returns the autocomplete context from the interaction.

This is a more low-level counter-part for process_application_commands() to allow users more fine-grained control over the processing.

パラメータ:
  • interaction (Interaction) -- The interaction to get the invocation context from.

  • cls (Any) -- The factory class that will be used to create the context. By default, this is AutocompleteContext. Should a custom class be provided, it must be similar enough to AutocompleteContext's interface.

戻り値:

The autocomplete context. The type of this can change via the cls parameter.

戻り値の型:

AutocompleteContext

get_channel(id, /)

Returns a channel or thread with the given ID.

パラメータ:

id (int) -- The ID to search for.

戻り値:

The returned channel or None if not found.

戻り値の型:

GuildChannel | Thread | PrivateChannel | None

get_cog(name)

Gets the cog instance requested.

If the cog is not found, None is returned instead.

パラメータ:

name (str) -- The name of the cog you are requesting. This is equivalent to the name passed via keyword argument in class creation or the class name if unspecified.

戻り値:

The cog that was requested. If not found, returns None.

戻り値の型:

Cog | None

get_command(name)

Get a Command from the internal list of commands.

This could also be used as a way to get aliases.

The name could be fully qualified (e.g. 'foo bar') will get the subcommand bar of the group command foo. If a subcommand is not found then None is returned just as usual.

パラメータ:

name (str) -- The name of the command to get.

戻り値:

The command that was requested. If not found, returns None.

戻り値の型:

Command[TypeVar(CogT, bound= Cog), Any, Any] | None

await get_context(message, *, cls=<class 'discord.ext.commands.context.Context'>)

This function is a coroutine.

Returns the invocation context from the message.

This is a more low-level counter-part for process_commands() to allow users more fine-grained control over the processing.

The returned context is not guaranteed to be a valid invocation context, Context.valid must be checked to make sure it is. If the context is not valid then it is not a valid candidate to be invoked under invoke().

パラメータ:
  • message (Message) -- The message to get the invocation context from.

  • cls (type[TypeVar(CXT, bound= Context)]) -- The factory class that will be used to create the context. By default, this is Context. Should a custom class be provided, it must be similar enough to Context's interface.

戻り値:

The invocation context. The type of this can change via the cls parameter.

戻り値の型:

TypeVar(CXT, bound= Context)

await get_desynced_commands(guild_id=None, prefetched=None)

This function is a coroutine.

Gets the list of commands that are desynced from discord. If guild_id is specified, it will only return guild commands that are desynced from said guild, else it will return global commands.

注釈

This function is meant to be used internally, and should only be used if you want to override the default command registration behavior.

Added in version 2.0.

パラメータ:
  • guild_id (int | None) -- The guild id to get the desynced commands for, else global commands if unspecified.

  • prefetched (list[ApplicationCommand] | None) -- If you already fetched the commands, you can pass them here to be used. Not recommended for typical usage.

戻り値:

A list of the desynced commands. Each will come with at least the cmd and action keys, which respectively contain the command and the action to perform. Other keys may also be present depending on the action, including id.

戻り値の型:

list[dict[str, Any]]

get_emoji(id, /)

Returns an emoji with the given ID.

パラメータ:

id (int) -- The ID to search for.

戻り値:

The custom emoji or None if not found.

戻り値の型:

GuildEmoji | AppEmoji | None

get_guild(id, /)

Returns a guild with the given ID.

パラメータ:

id (int) -- The ID to search for.

戻り値:

The guild or None if not found.

戻り値の型:

Guild | None

get_message(id, /)

Returns a message the given ID.

This is useful if you have a message_id but don't want to do an API call to access the message.

パラメータ:

id (int) -- The ID to search for.

戻り値:

The returned message or None if not found.

戻り値の型:

Message | None

await get_or_fetch(object_type, object_id, default=None)

Shortcut method to get data from an object either by returning the cached version, or if it does not exist, attempting to fetch it from the API.

パラメータ:
  • object_type (type[TypeVar(_FETCHABLE, bound= VoiceChannel | TextChannel | ForumChannel | StageChannel | CategoryChannel | Thread | Member | User | Guild | Role | GuildEmoji | AppEmoji)]) -- Type of object to fetch or get.

  • object_id (int | None) -- ID of object to get. If None, returns default if provided, else None.

  • default (TypeVar(_D)) -- A default to return instead of raising if fetch fails.

  • self (Client)

戻り値:

The object if found, or default if provided when not found.

戻り値の型:

TypeVar(_FETCHABLE, bound= VoiceChannel | TextChannel | ForumChannel | StageChannel | CategoryChannel | Thread | Member | User | Guild | Role | GuildEmoji | AppEmoji) | TypeVar(_D) | None

例外:
  • TypeError -- Raised when required parameters are missing or invalid types are provided.

  • InvalidArgument -- Raised when an unsupported or incompatible object type is used.

await get_or_fetch_user(id, /)

This function is a coroutine.

Looks up a user in the user cache or fetches if not found.

パラメータ:

id (int) -- The ID to search for.

戻り値:

The user or None if not found.

戻り値の型:

User | None

get_partial_messageable(id, *, type=None)

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.

Added in version 2.0.

パラメータ:
  • id (int) -- The channel ID to create a partial messageable for.

  • type (ChannelType | None) -- The underlying channel type for the partial messageable.

戻り値:

The partial messageable

戻り値の型:

PartialMessageable

get_poll(id, /)

Returns a poll attached to the given message ID.

パラメータ:

id (int) -- The message ID of the poll to search for.

戻り値:

The poll or None if not found.

戻り値の型:

Poll | None

await get_prefix(message)

This function is a coroutine.

Retrieves the prefix the bot is listening to with the message as a context.

パラメータ:

message (Message) -- The message context to get the prefix of.

戻り値:

A list of prefixes or a single prefix that the bot is listening for.

戻り値の型:

list[str] | str

get_sound(sound_id)

Gets a Sound from the bot's sound cache.

Added in version 2.7.

パラメータ:

sound_id (int) -- The ID of the sound to get.

戻り値:

The sound with the given ID.

戻り値の型:

SoundboardSound | None

get_stage_instance(id, /)

Returns a stage instance with the given stage channel ID.

Added in version 2.0.

パラメータ:

id (int) -- The ID to search for.

戻り値:

The stage instance or None if not found.

戻り値の型:

StageInstance | None

get_sticker(id, /)

Returns a guild sticker with the given ID.

Added in version 2.0.

注釈

To retrieve standard stickers, use fetch_sticker(). or fetch_premium_sticker_packs().

戻り値:

The sticker or None if not found.

戻り値の型:

GuildSticker | None

パラメータ:

id (int)

get_user(id, /)

Returns a user with the given ID.

パラメータ:

id (int) -- The ID to search for.

戻り値:

The user or None if not found.

戻り値の型:

User | None

property guild_emojis: list[GuildEmoji]

The GuildEmoji that the connected client has.

property guilds: list[Guild]

The guilds that the connected client is a member of.

property intents: Intents

The intents configured for this connection.

Added in version 1.5.

await invoke(ctx)

This function is a coroutine.

Invokes the command given under the invocation context and handles all the internal event dispatch mechanisms.

パラメータ:

ctx (Context) -- The invocation context to invoke.

戻り値の型:

None

await invoke_application_command(ctx)

This function is a coroutine.

Invokes the application command given under the invocation context and handles all the internal event dispatch mechanisms.

パラメータ:

ctx (ApplicationContext) -- The invocation context to invoke.

戻り値の型:

None

is_closed()

Indicates if the WebSocket connection is closed.

戻り値の型:

bool

await is_owner(user)

This function is a coroutine.

Checks if a User or Member is the owner of this bot.

If an owner_id is not set, it is fetched automatically through the use of application_info(), returning the application owner, or all non read-only team members.

バージョン 1.3 で変更: The function also checks if the application is team-owned if owner_ids is not set.

パラメータ:

user (User | Member) -- The user to check for.

戻り値:

Whether the user is the owner.

戻り値の型:

bool

is_ready()

Specifies if the client's internal cache is ready for use.

戻り値の型:

bool

is_ws_ratelimited()

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.

Added in version 1.6.

戻り値の型:

bool

property latency: float

Measures latency between a HEARTBEAT and a HEARTBEAT_ACK in seconds. If no websocket is present, this returns nan, and if no heartbeat has been received yet, this returns float('inf').

This could be referred to as the Discord WebSocket protocol latency.

load_extension(name, *, package=None, recursive=False, store=False)

Loads an extension.

An extension is a python module that contains commands, cogs, or listeners.

An extension must have a global function, setup defined as the entry point on what to do when the extension is loaded. This entry point must have a single argument, the bot.

The extension passed can either be the direct name of a file within the current working directory or a folder that contains multiple extensions.

パラメータ:
  • name (str) -- The extension or folder name to load. It must be dot separated like regular Python imports if accessing a submodule. e.g. foo.test if you want to import foo/test.py.

  • package (Optional[str]) --

    The package name to resolve relative imports with. This is required when loading an extension using a relative path, e.g .foo.test. Defaults to None.

    Added in version 1.7.

  • recursive (Optional[bool]) --

    If subdirectories under the given head directory should be recursively loaded. Defaults to False.

    Added in version 2.0.

  • store (Optional[bool]) --

    If exceptions should be stored or raised. If set to True, all exceptions encountered will be stored in a returned dictionary as a load status. If set to False, if any exceptions are encountered they will be raised and the bot will be closed. If no exceptions are encountered, a list of loaded extension names will be returned. Defaults to False.

    Added in version 2.0.

戻り値:

If the store parameter is set to True, a dictionary will be returned that contains keys to represent the loaded extension names. The values bound to each key can either be an exception that occurred when loading that extension or a True boolean representing a successful load. If the store parameter is set to False, either a list containing a list of loaded extensions or nothing due to an encountered exception.

戻り値の型:

dict[str, Exception | bool] | list[str] | None

例外:
  • ExtensionNotFound -- The extension could not be imported. This is also raised if the name of the extension could not be resolved using the provided package parameter.

  • ExtensionAlreadyLoaded -- The extension is already loaded.

  • NoEntryPointError -- The extension does not have a setup function.

  • ExtensionFailed -- The extension or its setup function had an execution error.

load_extensions(*names, package=None, recursive=False, store=False)

Loads multiple extensions at once.

This method simplifies the process of loading multiple extensions by handling the looping of load_extension.

パラメータ:
  • names (str) -- The extension or folder names to load. It must be dot separated like regular Python imports if accessing a submodule. e.g. foo.test if you want to import foo/test.py.

  • package (Optional[str]) --

    The package name to resolve relative imports with. This is required when loading an extension using a relative path, e.g .foo.test. Defaults to None.

    Added in version 1.7.

  • recursive (Optional[bool]) --

    If subdirectories under the given head directory should be recursively loaded. Defaults to False.

    Added in version 2.0.

  • store (Optional[bool]) --

    If exceptions should be stored or raised. If set to True, all exceptions encountered will be stored in a returned dictionary as a load status. If set to False, if any exceptions are encountered they will be raised and the bot will be closed. If no exceptions are encountered, a list of loaded extension names will be returned. Defaults to False.

    Added in version 2.0.

戻り値:

If the store parameter is set to True, a dictionary will be returned that contains keys to represent the loaded extension names. The values bound to each key can either be an exception that occurred when loading that extension or a True boolean representing a successful load. If the store parameter is set to False, either a list containing names of loaded extensions or nothing due to an encountered exception.

戻り値の型:

dict[str, Exception | bool] | list[str] | None

例外:
  • ExtensionNotFound -- A given extension could not be imported. This is also raised if the name of the extension could not be resolved using the provided package parameter.

  • ExtensionAlreadyLoaded -- A given extension is already loaded.

  • NoEntryPointError -- A given extension does not have a setup function.

  • ExtensionFailed -- A given extension or its setup function had an execution error.

await login(token)

This function is a coroutine.

Logs in the client with the specified credentials.

パラメータ:

token (str) -- The authentication token. Do not prefix this token with anything as the library will do it for you.

例外:
  • TypeError -- The token was in invalid type.

  • 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.

戻り値の型:

None

message_command(*, checks=..., cog=..., contexts=..., cooldown=..., default_member_permissions=..., guild_ids=..., guild_only=..., integration_types=..., name=..., name_localizations=..., nsfw=..., **kwargs)

A shortcut decorator for adding a message command to the bot. This is equivalent to using application_command(), providing the MessageCommand class.

Added in version 2.0.

戻り値:

A decorator that converts the provided function into a MessageCommand, adds it to the bot, and returns it.

戻り値の型:

Callable[..., MessageCommand]

パラメータ:
await on_application_command_error(context, exception)

This function is a coroutine.

The default command error handler provided by the bot.

By default, this prints to sys.stderr however it could be overridden to have a different implementation.

This only fires if you do not specify any listeners for command error.

パラメータ:
戻り値の型:

None

await on_command_error(context, exception)

This function is a coroutine.

The default command error handler provided by the bot.

By default, this prints to sys.stderr however it could be overridden to have a different implementation.

This only fires if you do not specify any listeners for command error.

パラメータ:
戻り値の型:

None

await on_error(event_method, *args, **kwargs)

This function is a coroutine.

The default error handler provided by the client.

By default, this prints to sys.stderr however it could be overridden to have a different implementation. Check on_error() for more details.

パラメータ:
戻り値の型:

None

await on_modal_error(error, interaction)

This function is a coroutine.

The default modal error handler provided by the client. The default implementation prints the traceback to stderr.

This only fires for a modal if you did not define its on_error().

パラメータ:
  • error (Exception) -- The exception that was raised.

  • interaction (Interaction) -- The interaction that was received.

戻り値の型:

None

await on_view_error(error, item, interaction)

This function is a coroutine.

The default view error handler provided by the client.

This only fires for a view if you did not define its on_error().

パラメータ:
  • error (Exception) -- The exception that was raised.

  • item (ViewItem) -- The item that the user interacted with.

  • interaction (Interaction) -- The interaction that was received.

戻り値の型:

None

property persistent_views: Sequence[BaseView]

A sequence of persistent views added to the client.

Added in version 2.0.

property polls: list[Poll]

The polls that the connected client has.

Added in version 2.6.

property private_channels: list[PrivateChannel]

The private channels that the connected client is participating on.

注釈

This returns only up to 128 most recent private channels due to an internal working on how Discord deals with private channels.

await process_application_commands(interaction, auto_sync=None)

This function is a coroutine.

This function processes the commands that have been registered to the bot and other groups. Without this coroutine, none of the commands will be triggered.

By default, this coroutine is called inside the on_interaction() event. If you choose to override the on_interaction() event, then you should invoke this coroutine as well.

This function finds a registered command matching the interaction id from application commands and invokes it. If no matching command was found, it replies to the interaction with a default message.

Added in version 2.0.

パラメータ:
  • interaction (Interaction) -- The interaction to process

  • auto_sync (bool | None) -- Whether to automatically sync and unregister the command if it is not found in the internal cache. This will invoke the sync_commands() method on the context of the command, either globally or per-guild, based on the type of the command, respectively. Defaults to Bot.auto_sync_commands.

戻り値の型:

None

await process_commands(message)

This function is a coroutine.

This function processes the commands that have been registered to the bot and other groups. Without this coroutine, none of the commands will be triggered.

By default, this coroutine is called inside the on_message() event. If you choose to override the on_message() event, then you should invoke this coroutine as well.

This is built using other low level tools, and is equivalent to a call to get_context() followed by a call to invoke().

This also checks if the message's author is a bot and doesn't call get_context() or invoke() if so.

パラメータ:

message (Message) -- The message to process commands for.

戻り値の型:

None

await register_command(command, force=True, guild_ids=None)

This function is a coroutine.

Registers a command. If the command has guild_ids set, or if the guild_ids parameter is passed, the command will be registered as a guild command for those guilds.

パラメータ:
  • command (ApplicationCommand) -- The command to register.

  • force (bool) -- Whether to force the command to be registered. If this is set to False, the command will only be registered if it seems to already be registered and up to date with our internal cache. Defaults to True.

  • guild_ids (list[int] | None) -- A list of guild ids to register the command for. If this is not set, the command's ApplicationCommand.guild_ids attribute will be used.

戻り値:

The command that was registered

戻り値の型:

None

await register_commands(commands=None, guild_id=None, method='bulk', force=False, delete_existing=True)

This function is a coroutine.

Register a list of commands.

Added in version 2.0.

パラメータ:
  • commands (list[ApplicationCommand] | None) -- A list of commands to register. If this is not set (None), then all commands will be registered.

  • guild_id (int | None) -- If this is set, the commands will be registered as a guild command for the respective guild. If it is not set, the commands will be registered according to their ApplicationCommand.guild_ids attribute.

  • method (Literal['individual', 'bulk', 'auto']) -- The method to use when registering the commands. If this is set to "individual", then each command will be registered individually. If this is set to "bulk", then all commands will be registered in bulk. If this is set to "auto", then the method will be determined automatically. Defaults to "bulk".

  • force (bool) -- Registers the commands regardless of the state of the command on Discord. This uses one less API call, but can result in hitting rate limits more often. Defaults to False.

  • delete_existing (bool) -- Whether to delete existing commands that are not in the list of commands to register. Defaults to True.

戻り値の型:

list[ApplicationCommand]

reload_extension(name, *, package=None)

Atomically reloads an extension.

This replaces the extension with the same extension, only refreshed. This is equivalent to a unload_extension() followed by a load_extension() except done in an atomic way. That is, if an operation fails mid-reload then the bot will roll back to the prior working state.

パラメータ:
  • name (str) -- The extension name to reload. It must be dot separated like regular Python imports if accessing a submodule. e.g. foo.test if you want to import foo/test.py.

  • package (str | None) --

    The package name to resolve relative imports with. This is required when reloading an extension using a relative path, e.g .foo.test. Defaults to None.

    Added in version 1.7.

例外:
  • ExtensionNotLoaded -- The extension was not loaded.

  • ExtensionNotFound -- The extension could not be imported. This is also raised if the name of the extension could not be resolved using the provided package parameter.

  • NoEntryPointError -- The extension does not have a setup function.

  • ExtensionFailed -- The extension setup function had an execution error.

戻り値の型:

None

remove_application_command(command)

Remove an ApplicationCommand from the internal list of commands.

Added in version 2.0.

パラメータ:

command (ApplicationCommand) -- The command to remove.

戻り値:

The command that was removed. If the command has not been added, None is returned instead.

戻り値の型:

ApplicationCommand | None

remove_check(func, *, call_once=False)

Removes a global check from the bot. This function is idempotent and will not raise an exception if the function is not in the global checks.

パラメータ:
  • func -- The function to remove from the global checks.

  • call_once (bool) -- If the function was added with call_once=True in the Bot.add_check() call or using check_once().

戻り値の型:

None

remove_cog(name)

Removes a cog from the bot and returns it.

All registered commands and event listeners that the cog has registered will be removed as well.

If no cog is found then this method has no effect.

パラメータ:

name (str) -- The name of the cog to remove.

戻り値:

The cog that was removed. None if not found.

戻り値の型:

Cog | None

remove_command(name)

Remove a Command from the internal list of commands.

This could also be used as a way to remove aliases.

パラメータ:

name (str) -- The name of the command to remove.

戻り値:

The command that was removed. If the name is not valid then None is returned instead.

戻り値の型:

Command[TypeVar(CogT, bound= Cog), Any, Any] | None

remove_listener(func, name=...)

Removes a listener from the pool of listeners.

パラメータ:
  • func (TypeVar(Coro, bound= Callable[..., Coroutine[Any, Any, Any]])) -- The function that was used as a listener to remove.

  • name (str) -- The name of the event we want to remove. Defaults to func.__name__.

戻り値の型:

None

run(*args, **kwargs)

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()

警告

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.

パラメータ:
戻り値の型:

None

slash_command(*, checks=..., cog=..., contexts=..., cooldown=..., default_member_permissions=..., description=..., description_localizations=..., guild_ids=..., guild_only=..., integration_types=..., name=..., name_localizations=..., nsfw=..., options=..., parent=..., **kwargs)

A shortcut decorator for adding a slash command to the bot. This is equivalent to using application_command(), providing the SlashCommand class.

Added in version 2.0.

戻り値:

A decorator that converts the provided function into a SlashCommand, adds it to the bot, and returns it.

戻り値の型:

Callable[..., SlashCommand]

パラメータ:
slash_group(name=None, description=None, guild_ids=None)

A shortcut decorator that initializes the provided subclass of SlashCommandGroup and adds it to the internal command list via add_application_command().

Added in version 2.0.

パラメータ:
  • name (str | None) -- The name of the group to create. This will resolve to the name of the decorated class if None is passed.

  • description (str | None) -- The description of the group to create.

  • guild_ids (list[int] | None) -- A list of the IDs of each guild this group should be added to, making it a guild command. This will be a global command if None is passed.

戻り値:

The slash command group that was created.

戻り値の型:

Callable[[type[SlashCommandGroup]], SlashCommandGroup]

property sounds: list[SoundboardSound]

A list of all the sounds the bot can see.

Added in version 2.7.

await start(token, *, reconnect=True)

This function is a coroutine.

A shorthand coroutine for login() + connect().

例外:

TypeError -- An unexpected keyword argument was received.

パラメータ:
戻り値の型:

None

property status: Status

The status being used upon logging on to Discord.

property stickers: list[GuildSticker]

The stickers that the connected client has.

Added in version 2.0.

property store_url: str

The URL that leads to the application's store page for monetization.

Added in version 2.6.

Type:

str

await sync_commands(commands=None, method='bulk', force=False, guild_ids=None, register_guild_commands=True, check_guilds=[], delete_existing=True)

This function is a coroutine.

Registers all commands that have been added through add_application_command(). This method cleans up all commands over the API and should sync them with the internal cache of commands. It attempts to register the commands in the most efficient way possible, unless force is set to True, in which case it will always register all commands.

By default, this coroutine is called inside the on_connect() event. If you choose to override the on_connect() event, then you should invoke this coroutine as well such as the following:

@bot.event
async def on_connect():
    if bot.auto_sync_commands:
        await bot.sync_commands()
    print(f"{bot.user.name} connected.")

注釈

If you remove all guild commands from a particular guild, the library may not be able to detect and update the commands accordingly, as it would have to individually check for each guild. To force the library to unregister a guild's commands, call this function with commands=[] and guild_ids=[guild_id].

Added in version 2.0.

パラメータ:
  • commands (list[ApplicationCommand] | None) -- A list of commands to register. If this is not set (None), then all commands will be registered.

  • method (Literal['individual', 'bulk', 'auto']) -- The method to use when registering the commands. If this is set to "individual", then each command will be registered individually. If this is set to "bulk", then all commands will be registered in bulk. If this is set to "auto", then the method will be determined automatically. Defaults to "bulk".

  • force (bool) -- Registers the commands regardless of the state of the command on Discord. This uses one less API call, but can result in hitting rate limits more often. Defaults to False.

  • guild_ids (list[int] | None) -- A list of guild ids to register the commands for. If this is not set, the commands' guild_ids attribute will be used.

  • register_guild_commands (bool) -- Whether to register guild commands. Defaults to True.

  • check_guilds (list[int] | None) -- A list of guilds ids to check for commands to unregister, since the bot would otherwise have to check all guilds. Unlike guild_ids, this does not alter the commands' guild_ids attribute, instead it adds the guild ids to a list of guilds to sync commands for. If register_guild_commands is set to False, then this parameter is ignored.

  • delete_existing (bool) -- Whether to delete existing commands that are not in the list of commands to register. Defaults to True.

戻り値の型:

None

unload_extension(name, *, package=None)

Unloads an extension.

When the extension is unloaded, all commands, listeners, and cogs are removed from the bot and the module is un-imported.

The extension can provide an optional global function, teardown, to do miscellaneous clean-up if necessary. This function takes a single parameter, the bot, similar to setup from load_extension().

パラメータ:
  • name (str) -- The extension name to unload. It must be dot separated like regular Python imports if accessing a submodule. e.g. foo.test if you want to import foo/test.py.

  • package (str | None) --

    The package name to resolve relative imports with. This is required when unloading an extension using a relative path, e.g .foo.test. Defaults to None.

    Added in version 1.7.

例外:
戻り値の型:

None

await update_role_connection_metadata_records(*role_connection_metadata)

This function is a coroutine.

Updates the bot's role connection metadata records.

Added in version 2.4.

パラメータ:

*role_connection_metadata (ApplicationRoleConnectionMetadata) -- The new metadata records to send to Discord.

戻り値:

The updated role connection metadata records.

戻り値の型:

list[ApplicationRoleConnectionMetadata]

property user: ClientUser | None

Represents the connected client. None if not logged in.

user_command(*, checks=..., cog=..., contexts=..., cooldown=..., default_member_permissions=..., guild_ids=..., guild_only=..., integration_types=..., name=..., name_localizations=..., nsfw=..., **kwargs)

A shortcut decorator for adding a user command to the bot. This is equivalent to using application_command(), providing the UserCommand class.

Added in version 2.0.

戻り値:

A decorator that converts the provided function into a UserCommand, adds it to the bot, and returns it.

戻り値の型:

Callable[..., UserCommand]

パラメータ:
property users: list[User]

Returns a list of all the users the bot can see.

property voice_clients: list[VoiceProtocol[Self]]

Represents a list of voice connections.

These are usually VoiceClient instances.

wait_for(event, *, check=None, timeout=None)

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 timeout parameter is passed onto asyncio.wait_for(). By default, it does not timeout. Note that this does propagate the asyncio.TimeoutError for you in case of timeout and is provided for ease of use.

In case the event returns multiple arguments, a tuple containing 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.

パラメータ:
  • event (str) -- The event name, similar to the event reference, but without the on_ prefix, to wait for.

  • check (Callable[..., bool] | None) -- A predicate to check what to wait for. The arguments must meet the parameters of the event being waited for.

  • timeout (float | None) -- The number of seconds to wait before timing out and raising asyncio.TimeoutError.

戻り値:

Returns no arguments, a single argument, or a tuple of multiple arguments that mirrors the parameters passed in the event reference.

戻り値の型:

Any

例外:

asyncio.TimeoutError -- Raised if a timeout is provided and reached.

サンプル

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}!')

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('👍')
await wait_until_ready()

This function is a coroutine.

Waits until the client's internal cache is all ready.

戻り値の型:

None

walk_application_commands()

An iterator that recursively walks through all application commands and subcommands.

列挙:

ApplicationCommand -- An application command from the internal list of application commands.

戻り値の型:

Generator[ApplicationCommand, None, None]

walk_commands()

An iterator that recursively walks through all commands and subcommands.

バージョン 1.4 で変更: Duplicates due to aliases are no longer returned

列挙:

Union[Command, Group] -- A command or group from the internal list of commands.

戻り値の型:

Generator[Command[TypeVar(CogT, bound= Cog), Any, Any], None, None]

AutoShardedBot

class discord.ext.commands.AutoShardedBot(command_prefix=<function when_mentioned>, help_command=..., **options)[ソース]

This is similar to Bot except that it is inherited from discord.AutoShardedBot instead.

パラメータ:

Prefix Helpers

discord.ext.commands.when_mentioned(bot, msg)[ソース]

A callable that implements a command prefix equivalent to being mentioned.

These are meant to be passed into the Bot.command_prefix attribute.

パラメータ:
戻り値の型:

list[str]

discord.ext.commands.when_mentioned_or(*prefixes)[ソース]

A callable that implements when mentioned or other prefixes provided.

These are meant to be passed into the Bot.command_prefix attribute.

サンプル

bot = commands.Bot(command_prefix=commands.when_mentioned_or('!'))

注釈

This callable returns another callable, so if this is done inside a custom callable, you must call the returned callable, for example:

async def get_prefix(bot, message):
    extras = await prefixes_for(message.guild) # returns a list
    return commands.when_mentioned_or(*extras)(bot, message)
パラメータ:

prefixes (str)

戻り値の型:

Callable[[Bot | AutoShardedBot, Message], list[str]]

Event Reference

These events function similar to the regular events, except they are custom to the command extension module.

discord.ext.commands.on_command_error(ctx, error)

An error handler that is called when an error is raised inside a command either through user input error, check failure, or an error in your own code.

A default one is provided (Bot.on_command_error()).

パラメータ:
  • ctx (Context) -- The invocation context.

  • error (CommandError derived) -- The error that was raised.

discord.ext.commands.on_command(ctx)

An event that is called when a command is found and is about to be invoked.

This event is called regardless of whether the command itself succeeds via error or completes.

パラメータ:

ctx (Context) -- The invocation context.

discord.ext.commands.on_command_completion(ctx)

An event that is called when a command has completed its invocation.

This event is called only if the command succeeded, i.e. all checks have passed and the user input it correctly.

パラメータ:

ctx (Context) -- The invocation context.

Commands

Decorators

@discord.ext.commands.command(name=..., cls=..., **attrs)[ソース]

A decorator that transforms a function into a Command or if called with group(), Group.

By default the help attribute is received automatically from the docstring of the function and is cleaned up with the use of inspect.cleandoc. If the docstring is bytes, then it is decoded into str using utf-8 encoding.

All checks added using the check() & co. decorators are added into the function. There is no way to supply your own checks through this decorator.

パラメータ:
  • name (str) -- The name to create the command with. By default, this uses the function name unchanged.

  • cls (type[TypeVar(CommandT, bound= Command)]) -- The class to construct with. By default, this is Command. You usually do not change this.

  • attrs (Any) -- Keyword arguments to pass into the construction of the class denoted by cls.

例外:

TypeError -- If the function is not a coroutine or is already a command.

戻り値の型:

Callable[[Callable[[Concatenate[TypeVar(ContextT, bound= Context), ParamSpec(P, bound= None)]], Coroutine[Any, Any, Any]] | Callable[[Concatenate[TypeVar(CogT, bound= Cog), TypeVar(ContextT, bound= Context), ParamSpec(P, bound= None)]], Coroutine[Any, Any, TypeVar(T)]]], Command[TypeVar(CogT, bound= Cog), ParamSpec(P, bound= None), TypeVar(T)] | TypeVar(CommandT, bound= Command)]

@discord.ext.commands.group(name=..., cls=..., **attrs)[ソース]

A decorator that transforms a function into a Group.

This is similar to the command() decorator but the cls parameter is set to Group by default.

バージョン 1.1 で変更: The cls parameter can now be passed.

パラメータ:
戻り値の型:

Callable[[Callable[[Concatenate[TypeVar(ContextT, bound= Context), ParamSpec(P, bound= None)]], Coroutine[Any, Any, Any]] | Callable[[Concatenate[TypeVar(CogT, bound= Cog), TypeVar(ContextT, bound= Context), ParamSpec(P, bound= None)]], Coroutine[Any, Any, TypeVar(T)]]], Group[TypeVar(CogT, bound= Cog), ParamSpec(P, bound= None), TypeVar(T)] | TypeVar(GroupT, bound= Group)]

Command

class discord.ext.commands.Command(func, **kwargs)[ソース]

A class that implements the protocol for a bot text command.

These are not created manually, instead they are created via the decorator or functional interface.

name

The name of the command.

Type:

str

callback

The coroutine that is executed when the command is called.

Type:

coroutine

help

The long help text for the command.

Type:

Optional[str]

brief

The short help text for the command.

Type:

Optional[str]

usage

A replacement for arguments in the default help text.

Type:

Optional[str]

aliases

The list of aliases the command can be invoked under.

Type:

Union[List[str], Tuple[str]]

enabled

A boolean that indicates if the command is currently enabled. If the command is invoked while it is disabled, then DisabledCommand is raised to the on_command_error() event. Defaults to True.

Type:

bool

parent

The parent group that this command belongs to. None if there isn't one.

Type:

Optional[Group]

cog

The cog that this command belongs to. None if there isn't one.

Type:

Optional[Cog]

checks

A list of predicates that verifies if the command could be executed with the given Context as the sole parameter. If an exception is necessary to be thrown to signal failure, then one inherited from CommandError should be used. Note that if the checks fail then CheckFailure exception is raised to the on_command_error() event.

Type:

List[Callable[[Context], bool]]

description

The message prefixed into the default help command.

Type:

str

hidden

If True, the default help command does not show this in the help output.

Type:

bool

rest_is_raw

If False and a keyword-only argument is provided then the keyword only argument is stripped and handled as if it was a regular argument that handles MissingRequiredArgument and default values in a regular matter rather than passing the rest completely raw. If True then the keyword-only argument will pass in the rest of the arguments in a completely raw matter. Defaults to False.

Type:

bool

invoked_subcommand

The subcommand that was invoked, if any.

Type:

Optional[Command]

require_var_positional

If True and a variadic positional argument is specified, requires the user to specify at least one argument. Defaults to False.

Added in version 1.5.

Type:

bool

ignore_extra

If True, ignores extraneous strings passed to a command if all its requirements are met (e.g. ?foo a b c when only expecting a and b). Otherwise on_command_error() and local error handlers are called with TooManyArguments. Defaults to True.

Type:

bool

cooldown_after_parsing

If True, cooldown processing is done after argument parsing, which calls converters. If False then cooldown processing is done first and then the converters are called second. Defaults to False.

Type:

bool

extras

A dict of user provided extras to attach to the Command.

注釈

This object may be copied by the library.

Type:

dict

Added in version 2.0.

cooldown: Optional[Cooldown]

The cooldown applied when the command is invoked. None if the command doesn't have a cooldown.

Added in version 2.0.

パラメータ:
@after_invoke(coro)[ソース]

A decorator that registers a coroutine as a post-invoke hook.

A post-invoke hook is called directly after the command is called. This makes it a useful function to clean-up database connections or any type of clean up required.

This post-invoke hook takes a sole parameter, a Context.

See Bot.after_invoke() for more info.

パラメータ:

coro (TypeVar(HookT, bound= Hook)) -- The coroutine to register as the post-invoke hook.

例外:

TypeError -- The coroutine passed is not actually a coroutine.

戻り値の型:

TypeVar(HookT, bound= Hook)

@before_invoke(coro)[ソース]

A decorator that registers a coroutine as a pre-invoke hook.

A pre-invoke hook is called directly before the command is called. This makes it a useful function to set up database connections or any type of set up required.

This pre-invoke hook takes a sole parameter, a Context.

See Bot.before_invoke() for more info.

パラメータ:

coro (TypeVar(HookT, bound= Hook)) -- The coroutine to register as the pre-invoke hook.

例外:

TypeError -- The coroutine passed is not actually a coroutine.

戻り値の型:

TypeVar(HookT, bound= Hook)

@error(coro)[ソース]

A decorator that registers a coroutine as a local error handler.

A local error handler is an on_command_error() event limited to a single command. However, the on_command_error() is still invoked afterwards as the catch-all.

パラメータ:

coro (TypeVar(ErrorT, bound= Error)) -- The coroutine to register as the local error handler.

例外:

TypeError -- The coroutine passed is not actually a coroutine.

戻り値の型:

TypeVar(ErrorT, bound= Error)

add_check(func)[ソース]

Adds a check to the command.

This is the non-decorator interface to check().

Added in version 1.3.

パラメータ:

func (Callable[[Cog, Context[Any]], bool | Coroutine[Any, Any, bool]] | Callable[[Context[Any]], bool | Coroutine[Any, Any, bool]]) -- The function that will be used as a check.

戻り値の型:

None

remove_check(func)[ソース]

Removes a check from the command.

This function is idempotent and will not raise an exception if the function is not in the command's checks.

Added in version 1.3.

パラメータ:

func (Callable[[Cog, Context[Any]], bool | Coroutine[Any, Any, bool]] | Callable[[Context[Any]], bool | Coroutine[Any, Any, bool]]) -- The function to remove from the checks.

戻り値の型:

None

update(**kwargs)[ソース]

Updates Command instance with updated attribute.

This works similarly to the command() decorator in terms of parameters in that they are passed to the Command or subclass constructors, sans the name and callback.

パラメータ:

kwargs (Any)

戻り値の型:

None

await __call__(context, *args, **kwargs)[ソース]

This function is a coroutine.

Calls the internal callback that the command holds.

注釈

This bypasses all mechanisms -- including checks, converters, invoke hooks, cooldowns, etc. You must take care to pass the proper arguments and types to this function.

Added in version 1.3.

パラメータ:
  • context (Context)

  • args (ParamSpecArgs)

  • kwargs (ParamSpecKwargs)

戻り値の型:

TypeVar(T)

copy()[ソース]

Creates a copy of this command.

戻り値:

A new instance of this command.

戻り値の型:

TypeVar(CommandT, bound= Command)

パラメータ:

self (TypeVar(CommandT, bound= Command))

property clean_params: dict[str, Parameter]

Dict[str, inspect.Parameter]: Retrieves the parameter dictionary without the context or self parameters.

Useful for inspecting signature.

property full_parent_name: str

Retrieves the fully qualified parent command name.

This the base command name required to execute it. For example, in ?one two three the parent name would be one two.

property parents: list[Group]

Retrieves the parents of this command.

If the command has no parents then it returns an empty list.

For example in commands ?a b c test, the parents are [c, b, a].

Added in version 1.1.

property root_parent: Group | None

Retrieves the root parent of this command.

If the command has no parents then it returns None.

For example in commands ?a b c test, the root parent is a.

property qualified_name: str

Retrieves the fully qualified command name.

This is the full parent name with the command name as well. For example, in ?one two three the qualified name would be one two three.

is_on_cooldown(ctx)[ソース]

Checks whether the command is currently on cooldown.

パラメータ:

ctx (Context) -- The invocation context to use when checking the command's cooldown status.

戻り値:

A boolean indicating if the command is on cooldown.

戻り値の型:

bool

reset_cooldown(ctx)[ソース]

Resets the cooldown on this command.

パラメータ:

ctx (Context) -- The invocation context to reset the cooldown under.

戻り値の型:

None

get_cooldown_retry_after(ctx)[ソース]

Retrieves the amount of seconds before this command can be tried again.

Added in version 1.4.

パラメータ:

ctx (Context) -- The invocation context to retrieve the cooldown from.

戻り値:

The amount of time left on this command's cooldown in seconds. If this is 0.0 then the command isn't on cooldown.

戻り値の型:

float

has_error_handler()[ソース]

Checks whether the command has an error handler registered.

Added in version 1.7.

戻り値の型:

bool

property cog_name: str | None

The name of the cog this command belongs to, if any.

property short_doc: str

Gets the "short" documentation of a command.

By default, this is the brief attribute. If that lookup leads to an empty string then the first line of the help attribute is used instead.

property signature: str

Returns a POSIX-like signature useful for help command output.

await can_run(ctx)[ソース]

This function is a coroutine.

Checks if the command can be executed by checking all the predicates inside the checks attribute. This also checks whether the command is disabled.

バージョン 1.3 で変更: Checks whether the command is disabled or not

パラメータ:

ctx (Context) -- The ctx of the command currently being invoked.

戻り値:

A boolean indicating if the command can be invoked.

戻り値の型:

bool

例外:

CommandError -- Any command error that was raised during a check call will be propagated by this function.

Group

class discord.ext.commands.Group(*args, **attrs)[ソース]

A class that implements a grouping protocol for commands to be executed as subcommands.

This class is a subclass of Command and thus all options valid in Command are valid in here as well.

invoke_without_command

Indicates if the group callback should begin parsing and invocation only if no subcommand was found. Useful for making it an error handling function to tell the user that no subcommand was found or to have different functionality in case no subcommand was found. If this is False, then the group callback will always be invoked first. This means that the checks and the parsing dictated by its parameters will be executed. Defaults to False.

Type:

bool

case_insensitive

Indicates if the group's commands should be case-insensitive. Defaults to False.

Type:

bool

パラメータ:
@after_invoke(coro)

A decorator that registers a coroutine as a post-invoke hook.

A post-invoke hook is called directly after the command is called. This makes it a useful function to clean-up database connections or any type of clean up required.

This post-invoke hook takes a sole parameter, a Context.

See Bot.after_invoke() for more info.

パラメータ:

coro (TypeVar(HookT, bound= Hook)) -- The coroutine to register as the post-invoke hook.

例外:

TypeError -- The coroutine passed is not actually a coroutine.

戻り値の型:

TypeVar(HookT, bound= Hook)

@before_invoke(coro)

A decorator that registers a coroutine as a pre-invoke hook.

A pre-invoke hook is called directly before the command is called. This makes it a useful function to set up database connections or any type of set up required.

This pre-invoke hook takes a sole parameter, a Context.

See Bot.before_invoke() for more info.

パラメータ:

coro (TypeVar(HookT, bound= Hook)) -- The coroutine to register as the pre-invoke hook.

例外:

TypeError -- The coroutine passed is not actually a coroutine.

戻り値の型:

TypeVar(HookT, bound= Hook)

@command(name=..., cls=..., *args, **kwargs)

A shortcut decorator that invokes command() and adds it to the internal command list via add_command().

戻り値:

A decorator that converts the provided method into a Command, adds it to the bot, then returns it.

戻り値の型:

Callable[[Callable[[Concatenate[TypeVar(ContextT, bound= Context), ParamSpec(P, bound= None)]], Coroutine[Any, Any, Any]]], TypeVar(CommandT, bound= Command)]

パラメータ:
@error(coro)

A decorator that registers a coroutine as a local error handler.

A local error handler is an on_command_error() event limited to a single command. However, the on_command_error() is still invoked afterwards as the catch-all.

パラメータ:

coro (TypeVar(ErrorT, bound= Error)) -- The coroutine to register as the local error handler.

例外:

TypeError -- The coroutine passed is not actually a coroutine.

戻り値の型:

TypeVar(ErrorT, bound= Error)

@group(name=..., cls=..., *args, **kwargs)

A shortcut decorator that invokes group() and adds it to the internal command list via add_command().

戻り値:

A decorator that converts the provided method into a Group, adds it to the bot, then returns it.

戻り値の型:

Callable[[Callable[[Concatenate[TypeVar(ContextT, bound= Context), ParamSpec(P, bound= None)]], Coroutine[Any, Any, Any]]], TypeVar(GroupT, bound= Group)]

パラメータ:
copy()[ソース]

Creates a copy of this Group.

戻り値:

A new instance of this group.

戻り値の型:

TypeVar(GroupT, bound= Group)

パラメータ:

self (TypeVar(GroupT, bound= Group))

add_check(func)

Adds a check to the command.

This is the non-decorator interface to check().

Added in version 1.3.

パラメータ:

func (Callable[[Cog, Context[Any]], bool | Coroutine[Any, Any, bool]] | Callable[[Context[Any]], bool | Coroutine[Any, Any, bool]]) -- The function that will be used as a check.

戻り値の型:

None

add_command(command)

Adds a Command into the internal list of commands.

This is usually not called, instead the command() or group() shortcut decorators are used instead.

バージョン 1.4 で変更: Raise CommandRegistrationError instead of generic ClientException

パラメータ:

command (Command[TypeVar(CogT, bound= Cog), Any, Any]) -- The command to add.

例外:
  • .CommandRegistrationError -- If the command or its alias is already registered by different command.

  • TypeError -- If the command passed is not a subclass of Command.

戻り値の型:

None

await can_run(ctx)

This function is a coroutine.

Checks if the command can be executed by checking all the predicates inside the checks attribute. This also checks whether the command is disabled.

バージョン 1.3 で変更: Checks whether the command is disabled or not

パラメータ:

ctx (Context) -- The ctx of the command currently being invoked.

戻り値:

A boolean indicating if the command can be invoked.

戻り値の型:

bool

例外:

CommandError -- Any command error that was raised during a check call will be propagated by this function.

property clean_params: dict[str, Parameter]

Dict[str, inspect.Parameter]: Retrieves the parameter dictionary without the context or self parameters.

Useful for inspecting signature.

property cog_name: str | None

The name of the cog this command belongs to, if any.

property commands: set[Command[CogT, Any, Any]]

A unique set of commands without aliases that are registered.

property full_parent_name: str

Retrieves the fully qualified parent command name.

This the base command name required to execute it. For example, in ?one two three the parent name would be one two.

get_command(name)

Get a Command from the internal list of commands.

This could also be used as a way to get aliases.

The name could be fully qualified (e.g. 'foo bar') will get the subcommand bar of the group command foo. If a subcommand is not found then None is returned just as usual.

パラメータ:

name (str) -- The name of the command to get.

戻り値:

The command that was requested. If not found, returns None.

戻り値の型:

Command[TypeVar(CogT, bound= Cog), Any, Any] | None

get_cooldown_retry_after(ctx)

Retrieves the amount of seconds before this command can be tried again.

Added in version 1.4.

パラメータ:

ctx (Context) -- The invocation context to retrieve the cooldown from.

戻り値:

The amount of time left on this command's cooldown in seconds. If this is 0.0 then the command isn't on cooldown.

戻り値の型:

float

has_error_handler()

Checks whether the command has an error handler registered.

Added in version 1.7.

戻り値の型:

bool

is_on_cooldown(ctx)

Checks whether the command is currently on cooldown.

パラメータ:

ctx (Context) -- The invocation context to use when checking the command's cooldown status.

戻り値:

A boolean indicating if the command is on cooldown.

戻り値の型:

bool

property parents: list[Group]

Retrieves the parents of this command.

If the command has no parents then it returns an empty list.

For example in commands ?a b c test, the parents are [c, b, a].

Added in version 1.1.

property qualified_name: str

Retrieves the fully qualified command name.

This is the full parent name with the command name as well. For example, in ?one two three the qualified name would be one two three.

remove_check(func)

Removes a check from the command.

This function is idempotent and will not raise an exception if the function is not in the command's checks.

Added in version 1.3.

パラメータ:

func (Callable[[Cog, Context[Any]], bool | Coroutine[Any, Any, bool]] | Callable[[Context[Any]], bool | Coroutine[Any, Any, bool]]) -- The function to remove from the checks.

戻り値の型:

None

remove_command(name)

Remove a Command from the internal list of commands.

This could also be used as a way to remove aliases.

パラメータ:

name (str) -- The name of the command to remove.

戻り値:

The command that was removed. If the name is not valid then None is returned instead.

戻り値の型:

Command[TypeVar(CogT, bound= Cog), Any, Any] | None

reset_cooldown(ctx)

Resets the cooldown on this command.

パラメータ:

ctx (Context) -- The invocation context to reset the cooldown under.

戻り値の型:

None

property root_parent: Group | None

Retrieves the root parent of this command.

If the command has no parents then it returns None.

For example in commands ?a b c test, the root parent is a.

property short_doc: str

Gets the "short" documentation of a command.

By default, this is the brief attribute. If that lookup leads to an empty string then the first line of the help attribute is used instead.

property signature: str

Returns a POSIX-like signature useful for help command output.

update(**kwargs)

Updates Command instance with updated attribute.

This works similarly to the command() decorator in terms of parameters in that they are passed to the Command or subclass constructors, sans the name and callback.

パラメータ:

kwargs (Any)

戻り値の型:

None

walk_commands()

An iterator that recursively walks through all commands and subcommands.

バージョン 1.4 で変更: Duplicates due to aliases are no longer returned

列挙:

Union[Command, Group] -- A command or group from the internal list of commands.

戻り値の型:

Generator[Command[TypeVar(CogT, bound= Cog), Any, Any], None, None]

GroupMixin

class discord.ext.commands.GroupMixin(*args, **kwargs)[ソース]

A mixin that implements common functionality for classes that behave similar to Group and are allowed to register commands.

all_commands

A mapping of command name to Command objects.

Type:

dict

case_insensitive

Whether the commands should be case-insensitive. Defaults to False.

Type:

bool

パラメータ:
@command(name=..., cls=..., *args, **kwargs)[ソース]

A shortcut decorator that invokes command() and adds it to the internal command list via add_command().

戻り値:

A decorator that converts the provided method into a Command, adds it to the bot, then returns it.

戻り値の型:

Callable[[Callable[[Concatenate[TypeVar(ContextT, bound= Context), ParamSpec(P, bound= None)]], Coroutine[Any, Any, Any]]], TypeVar(CommandT, bound= Command)]

パラメータ:
@group(name=..., cls=..., *args, **kwargs)[ソース]

A shortcut decorator that invokes group() and adds it to the internal command list via add_command().

戻り値:

A decorator that converts the provided method into a Group, adds it to the bot, then returns it.

戻り値の型:

Callable[[Callable[[Concatenate[TypeVar(ContextT, bound= Context), ParamSpec(P, bound= None)]], Coroutine[Any, Any, Any]]], TypeVar(GroupT, bound= Group)]

パラメータ:
property commands: set[Command[CogT, Any, Any]]

A unique set of commands without aliases that are registered.

add_command(command)[ソース]

Adds a Command into the internal list of commands.

This is usually not called, instead the command() or group() shortcut decorators are used instead.

バージョン 1.4 で変更: Raise CommandRegistrationError instead of generic ClientException

パラメータ:

command (Command[TypeVar(CogT, bound= Cog), Any, Any]) -- The command to add.

例外:
  • .CommandRegistrationError -- If the command or its alias is already registered by different command.

  • TypeError -- If the command passed is not a subclass of Command.

戻り値の型:

None

remove_command(name)[ソース]

Remove a Command from the internal list of commands.

This could also be used as a way to remove aliases.

パラメータ:

name (str) -- The name of the command to remove.

戻り値:

The command that was removed. If the name is not valid then None is returned instead.

戻り値の型:

Command[TypeVar(CogT, bound= Cog), Any, Any] | None

walk_commands()[ソース]

An iterator that recursively walks through all commands and subcommands.

バージョン 1.4 で変更: Duplicates due to aliases are no longer returned

列挙:

Union[Command, Group] -- A command or group from the internal list of commands.

戻り値の型:

Generator[Command[TypeVar(CogT, bound= Cog), Any, Any], None, None]

get_command(name)[ソース]

Get a Command from the internal list of commands.

This could also be used as a way to get aliases.

The name could be fully qualified (e.g. 'foo bar') will get the subcommand bar of the group command foo. If a subcommand is not found then None is returned just as usual.

パラメータ:

name (str) -- The name of the command to get.

戻り値:

The command that was requested. If not found, returns None.

戻り値の型:

Command[TypeVar(CogT, bound= Cog), Any, Any] | None

Cogs

Cog

Methods
class discord.ext.commands.Cog(*args: Any, **kwargs: Any)[ソース]
walk_commands()[ソース]

An iterator that recursively walks through this cog's commands and subcommands.

列挙:

Union[Command, Group] -- A command or group from the cog.

戻り値の型:

Generator[Command, None, None]

get_commands()[ソース]
戻り値:

A list of commands that are defined inside this cog.

注釈

This does not include subcommands.

戻り値の型:

list[ApplicationCommand | Command]

CogMeta

class discord.cog.CogMeta(*args, **kwargs)[ソース]

A metaclass for defining a cog.

Note that you should probably not use this directly. It is exposed purely for documentation purposes along with making custom metaclasses to intermix with other metaclasses such as the abc.ABCMeta metaclass.

For example, to create an abstract cog mixin class, the following would be done.

import abc

class CogABCMeta(discord.CogMeta, abc.ABCMeta):
    pass

class SomeMixin(metaclass=abc.ABCMeta):
    pass

class SomeCogMixin(SomeMixin, discord.Cog, metaclass=CogABCMeta):
    pass

注釈

When passing an attribute of a metaclass that is documented below, note that you must pass it as a keyword-only argument to the class creation like the following example:

class MyCog(discord.Cog, name='My Cog'):
    pass
name

The cog name. By default, it is the name of the class with no modification.

Type:

str

description

The cog description. By default, it is the cleaned docstring of the class.

Added in version 1.6.

Type:

str

command_attrs

A list of attributes to apply to every command inside this cog. The dictionary is passed into the Command options at __init__. If you specify attributes inside the command attribute in the class, it will override the one specified inside this attribute. For example:

class MyCog(discord.Cog, command_attrs=dict(hidden=True)):
    @discord.slash_command()
    async def foo(self, ctx):
        pass # hidden -> True

    @discord.slash_command(hidden=False)
    async def bar(self, ctx):
        pass # hidden -> False
Type:

dict

guild_ids

A shortcut to command_attrs, what guild_ids should all application commands have in the cog. You can override this by setting guild_ids per command.

Added in version 2.0.

Type:

Optional[List[int]]

パラメータ:

Help Commands

HelpCommand

class discord.ext.commands.HelpCommand(*args, **kwargs)[ソース]

The base implementation for help command formatting.

注釈

Internally instances of this class are deep copied every time the command itself is invoked to prevent a race condition mentioned in GH-2123.

This means that relying on the state of this class to be the same between command invocations would not work as expected.

context

The context that invoked this help formatter. This is generally set after the help command assigned, command_callback(), has been called.

Type:

Optional[Context]

show_hidden

Specifies if hidden commands should be shown in the output. Defaults to False.

Type:

bool

verify_checks

Specifies if commands should have their Command.checks called and verified. If True, always calls Command.checks. If None, only calls Command.checks in a guild setting. If False, never calls Command.checks. Defaults to True.

バージョン 1.7 で変更.

Type:

Optional[bool]

command_attrs

A dictionary of options to pass in for the construction of the help command. This allows you to change the command behaviour without actually changing the implementation of the command. The attributes will be the same as the ones passed in the Command constructor.

Type:

dict

add_check(func)[ソース]

Adds a check to the help command.

Added in version 1.4.

パラメータ:

func -- The function that will be used as a check.

remove_check(func)[ソース]

Removes a check from the help command.

This function is idempotent and will not raise an exception if the function is not in the command's checks.

Added in version 1.4.

パラメータ:

func -- The function to remove from the checks.

get_bot_mapping()[ソース]

Retrieves the bot mapping passed to send_bot_help().

property invoked_with

Similar to Context.invoked_with except properly handles the case where Context.send_help() is used.

If the help command was used regularly then this returns the Context.invoked_with attribute. Otherwise, if the help command was called using Context.send_help() then it returns the internal command name of the help command.

戻り値:

The command name that triggered this invocation.

戻り値の型:

str

get_command_signature(command)[ソース]

Retrieves the signature portion of the help page.

パラメータ:

command (Command) -- The command to get the signature of.

戻り値:

The signature for the command.

戻り値の型:

str

remove_mentions(string)[ソース]

Removes mentions from the string to prevent abuse.

This includes @everyone, @here, member mentions and role mentions.

戻り値:

The string with mentions removed.

戻り値の型:

str

property cog

A property for retrieving or setting the cog for the help command.

When a cog is set for the help command, it is as-if the help command belongs to that cog. All cog special methods will apply to the help command, and it will be automatically unset on unload.

To unbind the cog from the help command, you can set it to None.

戻り値:

The cog that is currently set for the help command.

戻り値の型:

Optional[Cog]

command_not_found(string)[ソース]

This function could be a coroutine.

A method called when a command is not found in the help command. This is useful to override for i18n.

Defaults to No command called {0} found.

パラメータ:

string (str) -- The string that contains the invalid command. Note that this has had mentions removed to prevent abuse.

戻り値:

The string to use when a command has not been found.

戻り値の型:

str

subcommand_not_found(command, string)[ソース]

This function could be a coroutine.

A method called when a command did not have a subcommand requested in the help command. This is useful to override for i18n.

Defaults to either:

  • 'Command "{command.qualified_name}" has no subcommands.'
    • If there is no subcommand in the command parameter.

  • 'Command "{command.qualified_name}" has no subcommand named {string}'
    • If the command parameter has subcommands but not one named string.

パラメータ:
  • command (Command) -- The command that did not have the subcommand requested.

  • string (str) -- The string that contains the invalid subcommand. Note that this has had mentions removed to prevent abuse.

戻り値:

The string to use when the command did not have the subcommand requested.

戻り値の型:

str

await filter_commands(commands, *, sort=False, key=None, exclude=None)[ソース]

This function is a coroutine.

Returns a filtered list of commands and optionally sorts them.

This takes into account the verify_checks and show_hidden attributes.

パラメータ:
  • commands (Iterable[Command]) -- An iterable of commands that are getting filtered.

  • sort (bool) -- Whether to sort the result.

  • key (Optional[Callable[Command, Any]]) -- An optional key function to pass to sorted() that takes a Command as its sole parameter. If sort is passed as True then this will default as the command name.

  • exclude (tuple[Any] | None) -- A tuple of command types to exclude from the filter.

戻り値:

A list of commands that passed the filter.

戻り値の型:

List[Command]

get_max_size(commands)[ソース]

Returns the largest name length of the specified command list.

パラメータ:

commands (Sequence[Command]) -- A sequence of commands to check for the largest size.

戻り値:

The maximum width of the commands.

戻り値の型:

int

get_destination()[ソース]

Returns the Messageable where the help command will be output.

You can override this method to customise the behaviour.

By default, this returns the context's channel.

戻り値:

The destination where the help command will be output.

戻り値の型:

abc.Messageable

await send_error_message(error)[ソース]

This function is a coroutine.

Handles the implementation when an error happens in the help command. For example, the result of command_not_found() will be passed here.

You can override this method to customise the behaviour.

By default, this sends the error message to the destination specified by get_destination().

注釈

You can access the invocation context with HelpCommand.context.

パラメータ:

error (str) -- The error message to display to the user. Note that this has had mentions removed to prevent abuse.

await on_help_command_error(ctx, error)[ソース]

This function is a coroutine.

The help command's error handler, as specified by Error Handling.

Useful to override if you need some specific behaviour when the error handler is called.

By default, this method does nothing and just propagates to the default error handlers.

パラメータ:
await send_bot_help(mapping)[ソース]

This function is a coroutine.

Handles the implementation of the bot command page in the help command. This function is called when the help command is called with no arguments.

It should be noted that this method does not return anything -- rather the actual message sending should be done inside this method. Well-behaved subclasses should use get_destination() to know where to send, as this is a customisation point for other users.

You can override this method to customise the behaviour.

注釈

You can access the invocation context with HelpCommand.context.

Also, the commands in the mapping are not filtered. To do the filtering you will have to call filter_commands() yourself.

パラメータ:

mapping (Mapping[Optional[Cog], List[Command]]) -- A mapping of cogs to commands that have been requested by the user for help. The key of the mapping is the Cog that the command belongs to, or None if there isn't one, and the value is a list of commands that belongs to that cog.

await send_cog_help(cog)[ソース]

This function is a coroutine.

Handles the implementation of the cog page in the help command. This function is called when the help command is called with a cog as the argument.

It should be noted that this method does not return anything -- rather the actual message sending should be done inside this method. Well-behaved subclasses should use get_destination() to know where to send, as this is a customisation point for other users.

You can override this method to customise the behaviour.

注釈

You can access the invocation context with HelpCommand.context.

To get the commands that belong to this cog see Cog.get_commands(). The commands returned not filtered. To do the filtering you will have to call filter_commands() yourself.

パラメータ:

cog (Cog) -- The cog that was requested for help.

await send_group_help(group)[ソース]

This function is a coroutine.

Handles the implementation of the group page in the help command. This function is called when the help command is called with a group as the argument.

It should be noted that this method does not return anything -- rather the actual message sending should be done inside this method. Well-behaved subclasses should use get_destination() to know where to send, as this is a customisation point for other users.

You can override this method to customise the behaviour.

注釈

You can access the invocation context with HelpCommand.context.

To get the commands that belong to this group without aliases see Group.commands. The commands returned not filtered. To do the filtering you will have to call filter_commands() yourself.

パラメータ:

group (Group) -- The group that was requested for help.

await send_command_help(command)[ソース]

This function is a coroutine.

Handles the implementation of the single command page in the help command.

It should be noted that this method does not return anything -- rather the actual message sending should be done inside this method. Well-behaved subclasses should use get_destination() to know where to send, as this is a customisation point for other users.

You can override this method to customise the behaviour.

注釈

You can access the invocation context with HelpCommand.context.

Showing Help

There are certain attributes and methods that are helpful for a help command to show such as the following:

There are more than just these attributes but feel free to play around with these to help you get started to get the output that you want.

パラメータ:

command (Command) -- The command that was requested for help.

await prepare_help_command(ctx, command=None)[ソース]

This function is a coroutine.

A low level method that can be used to prepare the help command before it does anything. For example, if you need to prepare some state in your subclass before the command does its processing then this would be the place to do it.

The default implementation does nothing.

注釈

This is called inside the help command callback body. So all the usual rules that happen inside apply here as well.

パラメータ:
  • ctx (Context) -- The invocation context.

  • command (Optional[str]) -- The argument passed to the help command.

await command_callback(ctx, *, command=None)[ソース]

This function is a coroutine.

The actual implementation of the help command.

It is not recommended to override this method and instead change the behaviour through the methods that actually get dispatched.

DefaultHelpCommand

class discord.ext.commands.DefaultHelpCommand(*args, **kwargs)[ソース]

The implementation of the default help command.

This inherits from HelpCommand.

It extends it with the following attributes.

width

The maximum number of characters that fit in a line. Defaults to 80.

Type:

int

sort_commands

Whether to sort the commands in the output alphabetically. Defaults to True.

Type:

bool

dm_help

A tribool that indicates if the help command should DM the user instead of sending it to the channel it received it from. If the boolean is set to True, then all help output is DM'd. If False, none of the help output is DM'd. If None, then the bot will only DM when the help message becomes too long (dictated by more than dm_help_threshold characters). Defaults to False.

Type:

Optional[bool]

dm_help_threshold

The number of characters the paginator must accumulate before getting DM'd to the user if dm_help is set to None. Defaults to 1000.

Type:

Optional[int]

indent

How much to indent the commands from a heading. Defaults to 2.

Type:

int

commands_heading

The command list's heading string used when the help command is invoked with a category name. Useful for i18n. Defaults to "Commands:"

Type:

str

no_category

The string used when there is a command which does not belong to any category(cog). Useful for i18n. Defaults to "No Category"

Type:

str

paginator

The paginator used to paginate the help command output.

Type:

Paginator

shorten_text(text)[ソース]

Shortens text to fit into the width.

パラメータ:

text (str)

戻り値の型:

str

get_ending_note()[ソース]

Returns help command's ending note. This is mainly useful to override for i18n purposes.

戻り値の型:

str

add_indented_commands(commands, *, heading, max_size=None)[ソース]

Indents a list of commands after the specified heading.

The formatting is added to the paginator.

The default implementation is the command name indented by indent spaces, padded to max_size followed by the command's Command.short_doc and then shortened to fit into the width.

パラメータ:
  • commands (Sequence[Command]) -- A list of commands to indent for output.

  • heading (str) -- The heading to add to the output. This is only added if the list of commands is greater than 0.

  • max_size (Optional[int]) -- The max size to use for the gap between indents. If unspecified, calls get_max_size() on the commands parameter.

await send_pages()[ソース]

A helper utility to send the page output from paginator to the destination.

add_command_formatting(command)[ソース]

A utility function to format the non-indented block of commands and groups.

パラメータ:

command (Command) -- The command to format.

get_destination()[ソース]

Returns the Messageable where the help command will be output.

You can override this method to customise the behaviour.

By default, this returns the context's channel.

戻り値:

The destination where the help command will be output.

戻り値の型:

abc.Messageable

MinimalHelpCommand

class discord.ext.commands.MinimalHelpCommand(*args, **kwargs)[ソース]

An implementation of a help command with minimal output.

This inherits from HelpCommand.

sort_commands

Whether to sort the commands in the output alphabetically. Defaults to True.

Type:

bool

commands_heading

The command list's heading string used when the help command is invoked with a category name. Useful for i18n. Defaults to "Commands"

Type:

str

aliases_heading

The alias list's heading string used to list the aliases of the command. Useful for i18n. Defaults to "Aliases:".

Type:

str

dm_help

A tribool that indicates if the help command should DM the user instead of sending it to the channel it received it from. If the boolean is set to True, then all help output is DM'd. If False, none of the help output is DM'd. If None, then the bot will only DM when the help message becomes too long (dictated by more than dm_help_threshold characters). Defaults to False.

Type:

Optional[bool]

dm_help_threshold

The number of characters the paginator must accumulate before getting DM'd to the user if dm_help is set to None. Defaults to 1000.

Type:

Optional[int]

no_category

The string used when there is a command which does not belong to any category(cog). Useful for i18n. Defaults to "No Category"

Type:

str

paginator

The paginator used to paginate the help command output.

Type:

Paginator

await send_pages()[ソース]

A helper utility to send the page output from paginator to the destination.

get_opening_note()[ソース]

Returns help command's opening note. This is mainly useful to override for i18n purposes.

The default implementation returns

Use `{prefix}{command_name} [command]` for more info on a command.
You can also use `{prefix}{command_name} [category]` for more info on a category.
戻り値:

The help command opening note.

戻り値の型:

str

get_command_signature(command)[ソース]

Retrieves the signature portion of the help page.

パラメータ:

command (Command) -- The command to get the signature of.

戻り値:

The signature for the command.

戻り値の型:

str

get_ending_note()[ソース]

Return the help command's ending note. This is mainly useful to override for i18n purposes.

The default implementation does nothing.

戻り値:

The help command ending note.

戻り値の型:

str

add_bot_commands_formatting(commands, heading)[ソース]

Adds the minified bot heading with commands to the output.

The formatting should be added to the paginator.

The default implementation is a bold underline heading followed by commands separated by an EN SPACE (U+2002) in the next line.

パラメータ:
  • commands (Sequence[Command]) -- A list of commands that belong to the heading.

  • heading (str) -- The heading to add to the line.

add_subcommand_formatting(command)[ソース]

Adds formatting information on a subcommand.

The formatting should be added to the paginator.

The default implementation is the prefix and the Command.qualified_name optionally followed by an En dash and the command's Command.short_doc.

パラメータ:

command (Command) -- The command to show information of.

add_aliases_formatting(aliases)[ソース]

Adds the formatting information on a command's aliases.

The formatting should be added to the paginator.

The default implementation is the aliases_heading bolded followed by a comma separated list of aliases.

This is not called if there are no aliases to format.

パラメータ:

aliases (Sequence[str]) -- A list of aliases to format.

add_command_formatting(command)[ソース]

A utility function to format commands and groups.

パラメータ:

command (Command) -- The command to format.

get_destination()[ソース]

Returns the Messageable where the help command will be output.

You can override this method to customise the behaviour.

By default, this returns the context's channel.

戻り値:

The destination where the help command will be output.

戻り値の型:

abc.Messageable

Paginator

Methods
class discord.ext.commands.Paginator(prefix='```', suffix='```', max_size=2000, linesep='\\n')[ソース]

A class that aids in paginating code blocks for Discord messages.

len(x)

Returns the total number of characters in the paginator.

prefix

The prefix inserted to every page. e.g. three backticks.

Type:

str

suffix

The suffix appended at the end of every page. e.g. three backticks.

Type:

str

max_size

The maximum amount of codepoints allowed in a page.

Type:

int

linesep
The character string inserted between lines. e.g. a newline character.

Added in version 1.7.

Type:

str

パラメータ:
clear()[ソース]

Clears the paginator to have no pages.

add_line(line='', *, empty=False)[ソース]

Adds a line to the current page.

If the line exceeds the max_size then an exception is raised.

パラメータ:
  • line (str) -- The line to add.

  • empty (bool) -- Indicates if another empty line should be added.

例外:

RuntimeError -- The line was too big for the current max_size.

close_page()[ソース]

Prematurely terminate a page.

property pages: list[str]

Returns the rendered list of pages.

Enums

class discord.ext.commands.BucketType[ソース]

Specifies a type of bucket for, e.g. a cooldown.

default

The default bucket operates on a global basis.

user

The user bucket operates on a per-user basis.

guild

The guild bucket operates on a per-guild basis.

channel

The channel bucket operates on a per-channel basis.

member

The member bucket operates on a per-member basis.

category

The category bucket operates on a per-category basis.

role

The role bucket operates on a per-role basis.

Added in version 1.3.

Checks

@discord.ext.commands.check(predicate)[ソース]

A decorator that adds a check to the Command or its subclasses. These checks could be accessed via Command.checks.

These checks should be predicates that take in a single parameter taking a Context. If the check returns a False-like value then during invocation a CheckFailure exception is raised and sent to the on_command_error() event.

If an exception should be thrown in the predicate then it should be a subclass of CommandError. Any exception not subclassed from it will be propagated while those subclassed will be sent to on_command_error().

A special attribute named predicate is bound to the value returned by this decorator to retrieve the predicate passed to the decorator. This allows the following introspection and chaining to be done:

def owner_or_permissions(**perms):
    original = commands.has_permissions(**perms).predicate
    async def extended_check(ctx):
        if ctx.guild is None:
            return False
        return ctx.guild.owner_id == ctx.author.id or await original(ctx)
    return commands.check(extended_check)

注釈

The function returned by predicate is always a coroutine, even if the original function was not a coroutine.

バージョン 1.3 で変更: The predicate attribute was added.

サンプル

Creating a basic check to see if the command invoker is you.

def check_if_it_is_me(ctx):
    return ctx.message.author.id == 85309593344815104

@bot.command()
@commands.check(check_if_it_is_me)
async def only_for_me(ctx):
    await ctx.send('I know you!')

Transforming common checks into its own decorator:

def is_me():
    def predicate(ctx):
        return ctx.message.author.id == 85309593344815104
    return commands.check(predicate)

@bot.command()
@is_me()
async def only_me(ctx):
    await ctx.send('Only you!')
パラメータ:

predicate (Callable[[Cog, Context[Any]], bool | Coroutine[Any, Any, bool]] | Callable[[Context[Any]], bool | Coroutine[Any, Any, bool]]) -- The predicate to check if the command should be invoked.

戻り値の型:

Callable[[TypeVar(T)], TypeVar(T)]

@discord.ext.commands.check_any(*checks)[ソース]

A check() that is added that checks if any of the checks passed will pass, i.e. using logical OR.

If all checks fail then CheckAnyFailure is raised to signal the failure. It inherits from CheckFailure.

注釈

The predicate attribute for this function is a coroutine.

Added in version 1.3.

サンプル

Creating a basic check to see if it's the bot owner or the server owner:

def is_guild_owner():
    def predicate(ctx):
        return ctx.guild is not None and ctx.guild.owner_id == ctx.author.id
    return commands.check(predicate)

@bot.command()
@commands.check_any(commands.is_owner(), is_guild_owner())
async def only_for_owners(ctx):
    await ctx.send('Hello mister owner!')
パラメータ:

*checks (Callable[[Cog, Context[Any]], bool | Coroutine[Any, Any, bool]] | Callable[[Context[Any]], bool | Coroutine[Any, Any, bool]]) -- An argument list of checks that have been decorated with the check() decorator.

例外:

TypeError -- A check passed has not been decorated with the check() decorator.

戻り値の型:

Callable[[TypeVar(T)], TypeVar(T)]

@discord.ext.commands.has_role(item)[ソース]

A check() that is added that checks if the member invoking the command has the role specified via the name or ID specified.

If a string is specified, you must give the exact name of the role, including caps and spelling.

If an integer is specified, you must give the exact snowflake ID of the role.

If the message is invoked in a private message context then the check will return False.

This check raises one of two special exceptions, MissingRole if the user is missing a role, or NoPrivateMessage if it is used in a private message. Both inherit from CheckFailure.

バージョン 1.1 で変更: Raise MissingRole or NoPrivateMessage instead of generic CheckFailure

パラメータ:

item (int | str) -- The name or ID of the role to check.

戻り値の型:

Callable[[TypeVar(T)], TypeVar(T)]

@discord.ext.commands.has_permissions(**perms)[ソース]

A check() that is added that checks if the member has all of the permissions necessary.

Note that this check operates on the current channel permissions, not the guild wide permissions.

The permissions passed in must be exactly like the properties shown under discord.Permissions.

This check raises a special exception, MissingPermissions that is inherited from CheckFailure.

If the command is executed within a DM, it returns True.

パラメータ:

**perms (bool) -- An argument list of permissions to check for.

戻り値の型:

Callable[[TypeVar(T)], TypeVar(T)]

サンプル

@bot.command()
@commands.has_permissions(manage_messages=True)
async def test(ctx):
    await ctx.send('You can manage messages.')
@discord.ext.commands.has_guild_permissions(**perms)[ソース]

Similar to has_permissions(), but operates on guild wide permissions instead of the current channel permissions.

If this check is called in a DM context, it will raise an exception, NoPrivateMessage.

Added in version 1.3.

パラメータ:

perms (bool)

戻り値の型:

Callable[[TypeVar(T)], TypeVar(T)]

@discord.ext.commands.has_any_role(*items)[ソース]

A check() that is added that checks if the member invoking the command has any of the roles specified. This means that if they have one out of the three roles specified, then this check will return True.

Similar to has_role(), the names or IDs passed in must be exact.

This check raises one of two special exceptions, MissingAnyRole if the user is missing all roles, or NoPrivateMessage if it is used in a private message. Both inherit from CheckFailure.

バージョン 1.1 で変更: Raise MissingAnyRole or NoPrivateMessage instead of generic CheckFailure

パラメータ:

items (int | str) -- An argument list of names or IDs to check that the member has roles wise.

戻り値の型:

Callable[[TypeVar(T)], TypeVar(T)]

サンプル

@bot.command()
@commands.has_any_role('Library Devs', 'Moderators', 492212595072434186)
async def cool(ctx):
    await ctx.send('You are cool indeed')
@discord.ext.commands.bot_has_role(item)[ソース]

Similar to has_role() except checks if the bot itself has the role.

This check raises one of two special exceptions, BotMissingRole if the bot is missing the role, or NoPrivateMessage if it is used in a private message. Both inherit from CheckFailure.

バージョン 1.1 で変更: Raise BotMissingRole or NoPrivateMessage instead of generic CheckFailure

パラメータ:

item (int)

戻り値の型:

Callable[[TypeVar(T)], TypeVar(T)]

@discord.ext.commands.bot_has_permissions(**perms)[ソース]

Similar to has_permissions() except checks if the bot itself has the permissions listed.

This check raises a special exception, BotMissingPermissions that is inherited from CheckFailure.

パラメータ:

perms (bool)

戻り値の型:

Callable[[TypeVar(T)], TypeVar(T)]

@discord.ext.commands.bot_has_guild_permissions(**perms)[ソース]

Similar to has_guild_permissions(), but checks the bot members guild permissions.

Added in version 1.3.

パラメータ:

perms (bool)

戻り値の型:

Callable[[TypeVar(T)], TypeVar(T)]

@discord.ext.commands.bot_has_any_role(*items)[ソース]

Similar to has_any_role() except checks if the bot itself has any of the roles listed.

This check raises one of two special exceptions, BotMissingAnyRole if the bot is missing all roles, or NoPrivateMessage if it is used in a private message. Both inherit from CheckFailure.

バージョン 1.1 で変更: Raise BotMissingAnyRole or NoPrivateMessage instead of generic CheckFailure.

パラメータ:

items (int)

戻り値の型:

Callable[[TypeVar(T)], TypeVar(T)]

@discord.ext.commands.cooldown(rate, per, type=('default', 0))[ソース]

A decorator that adds a cooldown to a command

A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of type which must be of enum type BucketType.

If a cooldown is triggered, then CommandOnCooldown is triggered in on_command_error() and the local error handler.

A command can only have a single cooldown.

パラメータ:
  • rate (int) -- The number of times a command can be used before triggering a cooldown.

  • per (float) -- The amount of seconds to wait for a cooldown when it's been triggered.

  • type (BucketType | Callable[[Message], Any]) --

    The type of cooldown to have. If callable, should return a key for the mapping.

    バージョン 1.7 で変更: Callables are now supported for custom bucket types.

戻り値の型:

Callable[[TypeVar(T)], TypeVar(T)]

@discord.ext.commands.dynamic_cooldown(cooldown, type=('default', 0))[ソース]

A decorator that adds a dynamic cooldown to a command

This differs from cooldown() in that it takes a function that accepts a single parameter of type discord.Message and must return a Cooldown or None. If None is returned then that cooldown is effectively bypassed.

A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of type which must be of enum type BucketType.

If a cooldown is triggered, then CommandOnCooldown is triggered in on_command_error() and the local error handler.

A command can only have a single cooldown.

Added in version 2.0.

パラメータ:
  • cooldown (BucketType | Callable[[Message], Any]) -- A function that takes a message and returns a cooldown that will apply to this invocation or None if the cooldown should be bypassed.

  • type (BucketType) -- The type of cooldown to have.

戻り値の型:

Callable[[TypeVar(T)], TypeVar(T)]

@discord.ext.commands.max_concurrency(number, per=('default', 0), *, wait=False)[ソース]

A decorator that adds a maximum concurrency to a command

This enables you to only allow a certain number of command invocations at the same time, for example if a command takes too long or if only one user can use it at a time. This differs from a cooldown in that there is no set waiting period or token bucket -- only a set number of people can run the command.

Added in version 1.3.

パラメータ:
  • number (int) -- The maximum number of invocations of this command that can be running at the same time.

  • per (BucketType) -- The bucket that this concurrency is based on, e.g. BucketType.guild would allow it to be used up to number times per guild.

  • wait (bool) -- Whether the command should wait for the queue to be over. If this is set to False then instead of waiting until the command can run again, the command raises MaxConcurrencyReached to its error handler. If this is set to True then the command waits until it can be executed.

戻り値の型:

Callable[[TypeVar(T)], TypeVar(T)]

@discord.ext.commands.before_invoke(coro)[ソース]

A decorator that registers a coroutine as a pre-invoke hook.

This allows you to refer to one before invoke hook for several commands that do not have to be within the same cog.

Added in version 1.4.

戻り値の型:

Callable[[TypeVar(T)], TypeVar(T)]

サンプル

async def record_usage(ctx):
    print(ctx.author, 'used', ctx.command, 'at', ctx.message.created_at)

@bot.command()
@commands.before_invoke(record_usage)
async def who(ctx): # Output: <User> used who at <Time>
    await ctx.send('I am a bot')

class What(commands.Cog):

    @commands.before_invoke(record_usage)
    @commands.command()
    async def when(self, ctx): # Output: <User> used when at <Time>
        await ctx.send(f'and I have existed since {ctx.bot.user.created_at}')

    @commands.command()
    async def where(self, ctx): # Output: <Nothing>
        await ctx.send('on Discord')

    @commands.command()
    async def why(self, ctx): # Output: <Nothing>
        await ctx.send('because someone made me')

bot.add_cog(What())
@discord.ext.commands.after_invoke(coro)[ソース]

A decorator that registers a coroutine as a post-invoke hook.

This allows you to refer to one after invoke hook for several commands that do not have to be within the same cog.

Added in version 1.4.

戻り値の型:

Callable[[TypeVar(T)], TypeVar(T)]

@discord.ext.commands.guild_only[ソース]

A check() that indicates this command must only be used in a guild context only. Basically, no private messages are allowed when using the command.

This check raises a special exception, NoPrivateMessage that is inherited from CheckFailure.

戻り値の型:

Callable[[TypeVar(T)], TypeVar(T)]

@discord.ext.commands.dm_only[ソース]

A check() that indicates this command must only be used in a DM context. Only private messages are allowed when using the command.

This check raises a special exception, PrivateMessageOnly that is inherited from CheckFailure.

Added in version 1.1.

戻り値の型:

Callable[[TypeVar(T)], TypeVar(T)]

@discord.ext.commands.is_owner[ソース]

A check() that checks if the person invoking this command is the owner of the bot.

This is powered by Bot.is_owner().

This check raises a special exception, NotOwner that is derived from CheckFailure.

戻り値の型:

Callable[[TypeVar(T)], TypeVar(T)]

@discord.ext.commands.is_nsfw[ソース]

A check() that checks if the channel is a NSFW channel.

This check raises a special exception, NSFWChannelRequired that is derived from CheckFailure.

バージョン 1.1 で変更: Raise NSFWChannelRequired instead of generic CheckFailure. DM channels will also now pass this check.

戻り値の型:

Callable[[TypeVar(T)], TypeVar(T)]

Cooldown

Attributes
class discord.ext.commands.Cooldown(rate, per)[ソース]

Represents a cooldown for a command.

rate

The total number of tokens available per per seconds.

Type:

int

per

The length of the cooldown period in seconds.

Type:

float

パラメータ:
get_tokens(current=None)[ソース]

Returns the number of available tokens before rate limiting is applied.

パラメータ:

current (float | None) -- The time in seconds since Unix epoch to calculate tokens at. If not supplied then time.time() is used.

戻り値:

The number of tokens available before the cooldown is to be applied.

戻り値の型:

int

get_retry_after(current=None)[ソース]

Returns the time in seconds until the cooldown will be reset.

パラメータ:

current (float | None) -- The current time in seconds since Unix epoch. If not supplied, then time.time() is used.

戻り値:

The number of seconds to wait before this cooldown will be reset.

戻り値の型:

float

update_rate_limit(current=None)[ソース]

Updates the cooldown rate limit.

パラメータ:

current (float | None) -- The time in seconds since Unix epoch to update the rate limit at. If not supplied, then time.time() is used.

戻り値:

The retry-after time in seconds if rate limited.

戻り値の型:

float | None

reset()[ソース]

Reset the cooldown to its initial state.

戻り値の型:

None

copy()[ソース]

Creates a copy of this cooldown.

戻り値:

A new instance of this cooldown.

戻り値の型:

Cooldown

Context

class discord.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)[ソース]

Represents the context in which a command is being invoked under.

This class contains a lot of metadata 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 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.

Added 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'].

Added 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

A boolean that indicates if 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)

Returns an AsyncIterator that enables receiving the destination's message history.

You must have read_message_history permissions to use this.

パラメータ:
  • 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 (Snowflake | 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 (Snowflake | 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 (Snowflake | 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 True if after is specified, otherwise False.

列挙:

Message -- The message with the message data parsed.

例外:
  • Forbidden -- You do not have permissions to get channel message history.

  • HTTPException -- The request to get message history failed.

戻り値の型:

HistoryIterator

サンプル

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.

async with typing()

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.

注釈

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!')
戻り値の型:

Typing

await invoke(command, /, *args, **kwargs)[ソース]

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.

注釈

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.

パラメータ:
  • command (Command[TypeVar(CogT, bound= Cog), ParamSpec(P, bound= None), TypeVar(T)]) -- The command that is going to be called.

  • *args (ParamSpecArgs) -- The arguments to use.

  • **kwargs (ParamSpecKwargs) -- The keyword arguments to use.

例外:

TypeError -- The command argument to invoke is missing.

戻り値の型:

TypeVar(T)

await reinvoke(*, call_hooks=False, restart=True)[ソース]

This function is a coroutine.

Calls the command again.

This is similar to invoke() except that it bypasses checks, cooldowns, and error handlers.

注釈

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.

パラメータ:
  • 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.

例外:

ValueError -- The context to reinvoke is not valid.

戻り値の型:

None

property valid: bool

Checks if the invocation context is valid to be invoked with.

property clean_prefix: str

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

Added in version 2.0.

property cog: Cog | None

Returns the cog associated with this context's command. None if it does not exist.

property guild: Guild | None

Returns the guild associated with this context's command. None if not available.

property channel: TextChannel | VoiceChannel | StageChannel | Thread | DMChannel | PartialMessageable | GroupChannel

Returns the channel associated with this context's command. Shorthand for Message.channel.

property author: User | Member

Union[User, Member]: Returns the author associated with this context's command. Shorthand for Message.author

property me: Member | ClientUser

Union[Member, ClientUser]: Similar to Guild.me except it may return the ClientUser in private message message contexts, or when Intents.guilds() is absent.

property voice_client: VoiceProtocol | None

A shortcut to Guild.voice_client, if applicable.

await send_help(*args)[ソース]

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.

注釈

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.

パラメータ:
  • entity (Optional[Union[Command, Cog, str]]) -- The entity to show help for.

  • args (Any)

戻り値:

The result of the help command, if any.

戻り値の型:

Any

await reply(content=None, **kwargs)[ソース]

This function is a coroutine.

A shortcut method to abc.Messageable.send() to reply to the Message.

Added in version 1.6.

戻り値:

The message that was sent.

戻り値の型:

Message

例外:
  • HTTPException -- Sending the message failed.

  • Forbidden -- You do not have the proper permissions to send the message.

  • InvalidArgument -- The files list is not of the appropriate size, or you specified both file and files.

パラメータ:
can_send(*objects)

Returns a bool indicating whether you have the permissions to send the object(s).

戻り値:

Indicates whether you have the permissions to send the object(s).

戻り値の型:

bool

例外:

TypeError -- An invalid type has been passed.

await fetch_message(id, /)

This function is a coroutine.

Retrieves a single Message from the destination.

パラメータ:

id (int) -- The message ID to look for.

戻り値:

The message asked for.

戻り値の型:

Message

例外:
  • NotFound -- The specified message was not found.

  • Forbidden -- You do not have the permissions required to get a message.

  • HTTPException -- Retrieving the message failed.

await forward_to(channel, **kwargs)[ソース]

This function is a coroutine.

A shortcut method to abc.Messageable.send() to forward the Message to a channel.

Added in version 2.7.

パラメータ:
  • channel (Messageable) -- The channel to forward this to.

  • kwargs (Any)

戻り値:

The message that was sent.

戻り値の型:

Message

例外:
  • HTTPException -- Sending the message failed.

  • Forbidden -- You do not have the proper permissions to send the message.

  • InvalidArgument -- The files list is not of the appropriate size, or you specified both file and files.

pins(*, limit=50, before=None)

Returns a MessagePinIterator that enables receiving the destination's pinned messages.

You must have read_message_history permissions to use this.

警告

Starting from version 3.0, await channel.pins() will no longer return a list of Message. See examples below for new usage instead.

パラメータ:
  • limit (int | None) -- The number of pinned messages to retrieve. If None, retrieves every pinned message in the channel.

  • before (Snowflake | datetime | None) -- Retrieve messages pinned before this datetime. 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.

列挙:

MessagePin -- The pinned message.

例外:
  • Forbidden -- You do not have permissions to get pinned messages.

  • HTTPException -- The request to get pinned messages failed.

戻り値の型:

MessagePinIterator

サンプル

Usage

counter = 0
async for pin in channel.pins(limit=250):
    if pin.message.author == client.user:
        counter += 1

Flattening into a list:

pins = await channel.pins(limit=None).flatten()
# pins is now a list of MessagePin...

All parameters are optional.

await send(content=None, *, tts=None, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, enforce_nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None, poll=None, suppress=None, suppress_embeds=None, silent=None)

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). If the content is set to None (the default), then the embed parameter 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.

パラメータ:
  • content (Optional[str]) -- The content of the message to send.

  • tts (bool) -- Indicates if the message should be sent using text-to-speech.

  • embed (Embed) -- The rich embed for the content.

  • file (File) -- The file to upload.

  • files (List[File]) -- A list of files to upload. Must be a maximum of 10.

  • 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.

  • enforce_nonce (Optional[bool]) --

    Whether nonce is enforced to be validated.

    Added in version 2.5.

  • 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 allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set in allowed_mentions. If no object is passed at all then the defaults given by allowed_mentions are used instead.

    Added in version 1.4.

  • reference (Union[Message, MessageReference, PartialMessage]) --

    A reference to the Message being replied to or forwarded. This can be created using to_reference(). When replying, you can control whether this mentions the author of the referenced message using the replied_user attribute of allowed_mentions or by setting mention_author.

    Added in version 1.6.

  • mention_author (Optional[bool]) --

    If set, overrides the replied_user attribute of allowed_mentions.

    Added in version 1.6.

  • view (discord.ui.BaseView) -- A Discord UI View to add to the message.

  • embeds (List[Embed]) --

    A list of embeds to upload. Must be a maximum of 10.

    Added in version 2.0.

  • stickers (Sequence[Union[GuildSticker, StickerItem]]) --

    A list of stickers to upload. Must be a maximum of 3.

    Added in version 2.0.

  • suppress (bool) --

    Whether to suppress embeds for the message.

    バージョン 2.8 で非推奨.

  • suppress_embeds (bool) --

    Whether to suppress embeds for the message.

    Added in version 2.8.

  • silent (bool) --

    Whether to suppress push and desktop notifications for the message.

    Added in version 2.4.

  • poll (Poll) --

    The poll to send.

    Added in version 2.6.

戻り値:

The message that was sent.

戻り値の型:

Message

例外:
await trigger_typing()

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.

戻り値の型:

None

Converters

class discord.ext.commands.Converter(*args, **kwargs)[ソース]

The base class of custom converters that require the Context to be passed to be useful.

This allows you to implement converters that function similar to the special cased discord classes.

Classes that derive from this should override the convert() method to do its conversion logic. This method must be a coroutine.

await convert(ctx, argument)[ソース]

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

パラメータ:
  • ctx (Context) -- The invocation context that the argument is being used in.

  • argument (str) -- The argument that is being converted.

例外:
  • .CommandError -- A generic exception occurred when converting the argument.

  • .BadArgument -- The converter failed to convert the argument.

戻り値の型:

TypeVar(T_co, covariant=True)

class discord.ext.commands.ObjectConverter(*args, **kwargs)[ソース]

Converts to a Object.

The argument must follow the valid ID or mention formats (e.g. <@80088516616269824>).

Added in version 2.0.

The lookup strategy is as follows (in order):

  1. Lookup by ID.

  2. Lookup by member, role, or channel mention.

await convert(ctx, argument)[ソース]

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

パラメータ:
  • ctx (Context) -- The invocation context that the argument is being used in.

  • argument (str) -- The argument that is being converted.

例外:
  • .CommandError -- A generic exception occurred when converting the argument.

  • .BadArgument -- The converter failed to convert the argument.

戻り値の型:

Object

class discord.ext.commands.MemberConverter(*args, **kwargs)[ソース]

Converts to a Member.

All lookups are via the local guild. If in a DM context, then the lookup is done by the global cache.

The lookup strategy is as follows (in order):

  1. Lookup by ID.

  2. Lookup by mention.

  3. Lookup by name#discrim

  4. Lookup by name

  5. Lookup by nickname

バージョン 1.5 で変更: Raise MemberNotFound instead of generic BadArgument

バージョン 1.5.1 で変更: This converter now lazily fetches members from the gateway and HTTP APIs, optionally caching the result if MemberCacheFlags.joined is enabled.

await convert(ctx, argument)[ソース]

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

パラメータ:
  • ctx (Context) -- The invocation context that the argument is being used in.

  • argument (str) -- The argument that is being converted.

例外:
  • .CommandError -- A generic exception occurred when converting the argument.

  • .BadArgument -- The converter failed to convert the argument.

戻り値の型:

Member

class discord.ext.commands.UserConverter(*args, **kwargs)[ソース]

Converts to a User.

All lookups are via the global user cache.

The lookup strategy is as follows (in order):

  1. Lookup by ID.

  2. Lookup by mention.

  3. Lookup by name#discrim

  4. Lookup by name

バージョン 1.5 で変更: Raise UserNotFound instead of generic BadArgument

バージョン 1.6 で変更: This converter now lazily fetches users from the HTTP APIs if an ID is passed, and it's not available in cache.

await convert(ctx, argument)[ソース]

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

パラメータ:
  • ctx (Context) -- The invocation context that the argument is being used in.

  • argument (str) -- The argument that is being converted.

例外:
  • .CommandError -- A generic exception occurred when converting the argument.

  • .BadArgument -- The converter failed to convert the argument.

戻り値の型:

User

class discord.ext.commands.MessageConverter(*args, **kwargs)[ソース]

Converts to a discord.Message.

Added in version 1.1.

The lookup strategy is as follows (in order):

  1. Lookup by "{channel ID}-{message ID}" (retrieved by shift-clicking on "Copy ID")

  2. Lookup by message ID (the message must be in the context channel)

  3. Lookup by message URL

バージョン 1.5 で変更: Raise ChannelNotFound, MessageNotFound or ChannelNotReadable instead of generic BadArgument

await convert(ctx, argument)[ソース]

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

パラメータ:
  • ctx (Context) -- The invocation context that the argument is being used in.

  • argument (str) -- The argument that is being converted.

例外:
  • .CommandError -- A generic exception occurred when converting the argument.

  • .BadArgument -- The converter failed to convert the argument.

戻り値の型:

Message

class discord.ext.commands.PartialMessageConverter(*args, **kwargs)[ソース]

Converts to a discord.PartialMessage.

Added in version 1.7.

The creation strategy is as follows (in order):

  1. By "{channel ID}-{message ID}" (retrieved by shift-clicking on "Copy ID")

  2. By message ID (The message is assumed to be in the context channel.)

  3. By message URL

await convert(ctx, argument)[ソース]

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

パラメータ:
  • ctx (Context) -- The invocation context that the argument is being used in.

  • argument (str) -- The argument that is being converted.

例外:
  • .CommandError -- A generic exception occurred when converting the argument.

  • .BadArgument -- The converter failed to convert the argument.

戻り値の型:

PartialMessage

class discord.ext.commands.GuildChannelConverter(*args, **kwargs)[ソース]

Converts to a GuildChannel.

All lookups are via the local guild. If in a DM context, then the lookup is done by the global cache.

The lookup strategy is as follows (in order):

  1. Lookup by ID.

  2. Lookup by mention.

  3. Lookup by name.

Added in version 2.0.

await convert(ctx, argument)[ソース]

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

パラメータ:
  • ctx (Context) -- The invocation context that the argument is being used in.

  • argument (str) -- The argument that is being converted.

例外:
  • .CommandError -- A generic exception occurred when converting the argument.

  • .BadArgument -- The converter failed to convert the argument.

戻り値の型:

GuildChannel

class discord.ext.commands.TextChannelConverter(*args, **kwargs)[ソース]

Converts to a TextChannel.

All lookups are via the local guild. If in a DM context, then the lookup is done by the global cache.

The lookup strategy is as follows (in order):

  1. Lookup by ID.

  2. Lookup by mention.

  3. Lookup by name

バージョン 1.5 で変更: Raise ChannelNotFound instead of generic BadArgument

await convert(ctx, argument)[ソース]

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

パラメータ:
  • ctx (Context) -- The invocation context that the argument is being used in.

  • argument (str) -- The argument that is being converted.

例外:
  • .CommandError -- A generic exception occurred when converting the argument.

  • .BadArgument -- The converter failed to convert the argument.

戻り値の型:

TextChannel

class discord.ext.commands.VoiceChannelConverter(*args, **kwargs)[ソース]

Converts to a VoiceChannel.

All lookups are via the local guild. If in a DM context, then the lookup is done by the global cache.

The lookup strategy is as follows (in order):

  1. Lookup by ID.

  2. Lookup by mention.

  3. Lookup by name

バージョン 1.5 で変更: Raise ChannelNotFound instead of generic BadArgument

await convert(ctx, argument)[ソース]

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

パラメータ:
  • ctx (Context) -- The invocation context that the argument is being used in.

  • argument (str) -- The argument that is being converted.

例外:
  • .CommandError -- A generic exception occurred when converting the argument.

  • .BadArgument -- The converter failed to convert the argument.

戻り値の型:

VoiceChannel

class discord.ext.commands.StageChannelConverter(*args, **kwargs)[ソース]

Converts to a StageChannel.

Added in version 1.7.

All lookups are via the local guild. If in a DM context, then the lookup is done by the global cache.

The lookup strategy is as follows (in order):

  1. Lookup by ID.

  2. Lookup by mention.

  3. Lookup by name

await convert(ctx, argument)[ソース]

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

パラメータ:
  • ctx (Context) -- The invocation context that the argument is being used in.

  • argument (str) -- The argument that is being converted.

例外:
  • .CommandError -- A generic exception occurred when converting the argument.

  • .BadArgument -- The converter failed to convert the argument.

戻り値の型:

StageChannel

class discord.ext.commands.CategoryChannelConverter(*args, **kwargs)[ソース]

Converts to a CategoryChannel.

All lookups are via the local guild. If in a DM context, then the lookup is done by the global cache.

The lookup strategy is as follows (in order):

  1. Lookup by ID.

  2. Lookup by mention.

  3. Lookup by name

バージョン 1.5 で変更: Raise ChannelNotFound instead of generic BadArgument

await convert(ctx, argument)[ソース]

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

パラメータ:
  • ctx (Context) -- The invocation context that the argument is being used in.

  • argument (str) -- The argument that is being converted.

例外:
  • .CommandError -- A generic exception occurred when converting the argument.

  • .BadArgument -- The converter failed to convert the argument.

戻り値の型:

CategoryChannel

class discord.ext.commands.ForumChannelConverter(*args, **kwargs)[ソース]

Converts to a ForumChannel.

All lookups are via the local guild. If in a DM context, then the lookup is done by the global cache.

The lookup strategy is as follows (in order):

  1. Lookup by ID.

  2. Lookup by mention.

  3. Lookup by name

Added in version 2.0.

await convert(ctx, argument)[ソース]

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

パラメータ:
  • ctx (Context) -- The invocation context that the argument is being used in.

  • argument (str) -- The argument that is being converted.

例外:
  • .CommandError -- A generic exception occurred when converting the argument.

  • .BadArgument -- The converter failed to convert the argument.

戻り値の型:

ForumChannel

class discord.ext.commands.InviteConverter(*args, **kwargs)[ソース]

Converts to a Invite.

This is done via an HTTP request using Bot.fetch_invite().

バージョン 1.5 で変更: Raise BadInviteArgument instead of generic BadArgument

await convert(ctx, argument)[ソース]

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

パラメータ:
  • ctx (Context) -- The invocation context that the argument is being used in.

  • argument (str) -- The argument that is being converted.

例外:
  • .CommandError -- A generic exception occurred when converting the argument.

  • .BadArgument -- The converter failed to convert the argument.

戻り値の型:

Invite

class discord.ext.commands.GuildConverter(*args, **kwargs)[ソース]

Converts to a Guild.

The lookup strategy is as follows (in order):

  1. Lookup by ID.

  2. Lookup by name. (There is no disambiguation for Guilds with multiple matching names).

Added in version 1.7.

await convert(ctx, argument)[ソース]

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

パラメータ:
  • ctx (Context) -- The invocation context that the argument is being used in.

  • argument (str) -- The argument that is being converted.

例外:
  • .CommandError -- A generic exception occurred when converting the argument.

  • .BadArgument -- The converter failed to convert the argument.

戻り値の型:

Guild

class discord.ext.commands.RoleConverter(*args, **kwargs)[ソース]

Converts to a Role.

All lookups are via the local guild. If in a DM context, the converter raises NoPrivateMessage exception.

The lookup strategy is as follows (in order):

  1. Lookup by ID.

  2. Lookup by mention.

  3. Lookup by name

バージョン 1.5 で変更: Raise RoleNotFound instead of generic BadArgument

await convert(ctx, argument)[ソース]

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

パラメータ:
  • ctx (Context) -- The invocation context that the argument is being used in.

  • argument (str) -- The argument that is being converted.

例外:
  • .CommandError -- A generic exception occurred when converting the argument.

  • .BadArgument -- The converter failed to convert the argument.

戻り値の型:

Role

class discord.ext.commands.GameConverter(*args, **kwargs)[ソース]

Converts to Game.

await convert(ctx, argument)[ソース]

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

パラメータ:
  • ctx (Context) -- The invocation context that the argument is being used in.

  • argument (str) -- The argument that is being converted.

例外:
  • .CommandError -- A generic exception occurred when converting the argument.

  • .BadArgument -- The converter failed to convert the argument.

戻り値の型:

Game

class discord.ext.commands.ColourConverter(*args, **kwargs)[ソース]

Converts to a Colour.

バージョン 1.5 で変更: Add an alias named ColorConverter

The following formats are accepted:

  • 0x<hex>

  • #<hex>

  • 0x#<hex>

  • rgb(<number>, <number>, <number>)

  • Any of the classmethod in Colour

    • The _ in the name can be optionally replaced with spaces.

Like CSS, <number> can be either 0-255 or 0-100% and <hex> can be either a 6 digit hex number or a 3 digit hex shortcut (e.g. #fff).

バージョン 1.5 で変更: Raise BadColourArgument instead of generic BadArgument

バージョン 1.7 で変更: Added support for rgb function and 3-digit hex shortcuts

await convert(ctx, argument)[ソース]

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

パラメータ:
  • ctx (Context) -- The invocation context that the argument is being used in.

  • argument (str) -- The argument that is being converted.

例外:
  • .CommandError -- A generic exception occurred when converting the argument.

  • .BadArgument -- The converter failed to convert the argument.

戻り値の型:

Colour

class discord.ext.commands.EmojiConverter(*args, **kwargs)[ソース]

Converts to a GuildEmoji.

All lookups are done for the local guild first, if available. If that lookup fails, then it checks the client's global cache.

The lookup strategy is as follows (in order):

  1. Lookup by ID.

  2. Lookup by extracting ID from the emoji.

  3. Lookup by name

バージョン 1.5 で変更: Raise EmojiNotFound instead of generic BadArgument

await convert(ctx, argument)[ソース]

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

パラメータ:
  • ctx (Context) -- The invocation context that the argument is being used in.

  • argument (str) -- The argument that is being converted.

例外:
  • .CommandError -- A generic exception occurred when converting the argument.

  • .BadArgument -- The converter failed to convert the argument.

戻り値の型:

GuildEmoji

class discord.ext.commands.PartialEmojiConverter(*args, **kwargs)[ソース]

Converts to a PartialEmoji.

This is done by extracting the animated flag, name, and ID for custom emojis, or by using the standard Unicode emojis supported by Discord.

バージョン 1.5 で変更: Raise PartialEmojiConversionFailure instead of generic BadArgument

await convert(ctx, argument)[ソース]

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

パラメータ:
  • ctx (Context) -- The invocation context that the argument is being used in.

  • argument (str) -- The argument that is being converted.

例外:
  • .CommandError -- A generic exception occurred when converting the argument.

  • .BadArgument -- The converter failed to convert the argument.

戻り値の型:

PartialEmoji

class discord.ext.commands.ThreadConverter(*args, **kwargs)[ソース]

Coverts to a Thread.

All lookups are via the local guild.

The lookup strategy is as follows (in order):

  1. Lookup by ID.

  2. Lookup by mention.

  3. Lookup by name.

await convert(ctx, argument)[ソース]

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

パラメータ:
  • ctx (Context) -- The invocation context that the argument is being used in.

  • argument (str) -- The argument that is being converted.

例外:
  • .CommandError -- A generic exception occurred when converting the argument.

  • .BadArgument -- The converter failed to convert the argument.

戻り値の型:

Thread

class discord.ext.commands.GuildStickerConverter(*args, **kwargs)[ソース]

Converts to a GuildSticker.

All lookups are done for the local guild first, if available. If that lookup fails, then it checks the client's global cache.

The lookup strategy is as follows (in order):

1. Lookup by ID. 3. Lookup by name

Added in version 2.0.

await convert(ctx, argument)[ソース]

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

パラメータ:
  • ctx (Context) -- The invocation context that the argument is being used in.

  • argument (str) -- The argument that is being converted.

例外:
  • .CommandError -- A generic exception occurred when converting the argument.

  • .BadArgument -- The converter failed to convert the argument.

戻り値の型:

GuildSticker

class discord.ext.commands.clean_content(*, fix_channel_mentions=False, use_nicknames=True, escape_markdown=False, remove_markdown=False)[ソース]

Converts the argument to mention scrubbed version of said content.

This behaves similarly to clean_content.

fix_channel_mentions

Whether to clean channel mentions.

Type:

bool

use_nicknames

Whether to use nicknames when transforming mentions.

Type:

bool

escape_markdown

Whether to also escape special markdown characters.

Type:

bool

remove_markdown

Whether to also remove special markdown characters. This option is not supported with escape_markdown

Added in version 1.7.

Type:

bool

パラメータ:
  • fix_channel_mentions (bool)

  • use_nicknames (bool)

  • escape_markdown (bool)

  • remove_markdown (bool)

await convert(ctx, argument)[ソース]

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

パラメータ:
  • ctx (Context) -- The invocation context that the argument is being used in.

  • argument (str) -- The argument that is being converted.

例外:
  • .CommandError -- A generic exception occurred when converting the argument.

  • .BadArgument -- The converter failed to convert the argument.

戻り値の型:

str

class discord.ext.commands.Greedy(*, converter)[ソース]

A special converter that greedily consumes arguments until it can't. As a consequence of this behaviour, most input errors are silently discarded, since it is used as an indicator of when to stop parsing.

When a parser error is met the greedy converter stops converting, undoes the internal string parsing routine, and continues parsing regularly.

For example, in the following code:

@commands.command()
async def test(ctx, numbers: Greedy[int], reason: str):
    await ctx.send("numbers: {}, reason: {}".format(numbers, reason))

An invocation of [p]test 1 2 3 4 5 6 hello would pass numbers with [1, 2, 3, 4, 5, 6] and reason with hello.

For more information, check Special Converters.

パラメータ:

converter (TypeVar(T))

await discord.ext.commands.run_converters(ctx, converter, argument, param)[ソース]

This function is a coroutine.

Runs converters for a given converter, argument, and parameter.

This function does the same work that the library does under the hood.

Added in version 2.0.

パラメータ:
  • ctx (Context) -- The invocation context to run the converters under.

  • converter (Any) -- The converter to run, this corresponds to the annotation in the function.

  • argument (str | None) -- The argument to convert to.

  • param (Parameter) -- The parameter being converted. This is mainly for error reporting.

戻り値:

The resulting conversion.

戻り値の型:

Any

例外:

CommandError -- The converter failed to convert.

Flag Converter

class discord.ext.commands.FlagConverter[ソース]

A converter that allows for a user-friendly flag syntax.

The flags are defined using PEP 526 type annotations similar to the dataclasses Python module. For more information on how this converter works, check the appropriate documentation.

iter(x)

Returns an iterator of (flag_name, flag_value) pairs. This allows it to be, for example, constructed as a dict or a list of pairs. Note that aliases are not shown.

Added in version 2.0.

パラメータ:
  • case_insensitive (bool) -- A class parameter to toggle case insensitivity of the flag parsing. If True then flags are parsed in a case-insensitive manner. Defaults to False.

  • prefix (str) -- The prefix that all flags must be prefixed with. By default, there is no prefix.

  • delimiter (str) -- The delimiter that separates a flag's argument from the flag's name. By default, this is :.

classmethod get_flags()[ソース]

A mapping of flag name to flag object this converter has.

戻り値の型:

dict[str, Flag]

classmethod await convert(ctx, argument)[ソース]

This function is a coroutine.

The method that actually converters an argument to the flag mapping.

パラメータ:
  • cls (Type[FlagConverter]) -- The flag converter class.

  • ctx (Context) -- The invocation context.

  • argument (str) -- The argument to convert from.

戻り値:

The flag converter instance with all flags parsed.

戻り値の型:

TypeVar(F, bound= FlagConverter)

例外:
class discord.ext.commands.Flag(name=<factory>, aliases=<factory>, attribute=<factory>, annotation=<factory>, default=<factory>, max_args=<factory>, positional=<factory>, override=<factory>, cast_to_dict=False)[ソース]

Represents a flag parameter for FlagConverter.

The flag() function helps create these flag objects, but it is not necessary to do so. These cannot be constructed manually.

name

The name of the flag.

Type:

str

aliases

The aliases of the flag name.

Type:

List[str]

attribute

The attribute in the class that corresponds to this flag.

Type:

str

default

The default value of the flag, if available.

Type:

Any

annotation

The underlying evaluated annotation of the flag.

Type:

Any

max_args

The maximum number of arguments the flag can accept. A negative value indicates an unlimited amount of arguments.

Type:

int

positional

Whether the flag is positional. A FlagConverter can only handle one positional flag.

Type:

bool

override

Whether multiple given values overrides the previous value.

Type:

bool

パラメータ:
property required: bool

Whether the flag is required.

A required flag has no default value.

discord.ext.commands.flag(*, name=..., aliases=..., default=..., max_args=..., override=..., positional=...)[ソース]

Override default functionality and parameters of the underlying FlagConverter class attributes.

パラメータ:
  • name (str) -- The flag name. If not given, defaults to the attribute name.

  • aliases (list[str]) -- Aliases to the flag name. If not given, no aliases are set.

  • default (Any) -- The default parameter. This could be either a value or a callable that takes Context as its sole parameter. If not given then it defaults to the default value given to the attribute.

  • max_args (int) -- The maximum number of arguments the flag can accept. A negative value indicates an unlimited amount of arguments. The default value depends on the annotation given.

  • override (bool) -- Whether multiple given values overrides the previous value. The default value depends on the annotation given.

  • positional (bool) -- Whether the flag is positional or not. There can only be one positional flag.

戻り値の型:

Any

Exceptions

exception discord.ext.commands.CommandError(message=None, *args)[ソース]

The base exception type for all command related errors.

This inherits from discord.DiscordException.

This exception and exceptions inherited from it are handled in a special way as they are caught and passed into a special event from Bot, on_command_error().

パラメータ:
exception discord.ext.commands.ConversionError(converter, original)[ソース]

Exception raised when a Converter class raises non-CommandError.

This inherits from CommandError.

converter

The converter that failed.

Type:

discord.ext.commands.Converter

original

The original exception that was raised. You can also get this via the __cause__ attribute.

Type:

Exception

パラメータ:
exception discord.ext.commands.MissingRequiredArgument(param)[ソース]

Exception raised when parsing a command and a parameter that is required is not encountered.

This inherits from UserInputError

param

The argument that is missing.

Type:

inspect.Parameter

パラメータ:

param (Parameter)

exception discord.ext.commands.ArgumentParsingError(message=None, *args)[ソース]

An exception raised when the parser fails to parse a user's input.

This inherits from UserInputError.

There are child classes that implement more granular parsing errors for i18n purposes.

パラメータ:
exception discord.ext.commands.UnexpectedQuoteError(quote)[ソース]

An exception raised when the parser encounters a quote mark inside a non-quoted string.

This inherits from ArgumentParsingError.

quote

The quote mark that was found inside the non-quoted string.

Type:

str

パラメータ:

quote (str)

exception discord.ext.commands.InvalidEndOfQuotedStringError(char)[ソース]

An exception raised when a space is expected after the closing quote in a string but a different character is found.

This inherits from ArgumentParsingError.

char

The character found instead of the expected string.

Type:

str

パラメータ:

char (str)

exception discord.ext.commands.ExpectedClosingQuoteError(close_quote)[ソース]

An exception raised when a quote character is expected but not found.

This inherits from ArgumentParsingError.

close_quote

The quote character expected.

Type:

str

パラメータ:

close_quote (str)

exception discord.ext.commands.BadArgument(message=None, *args)[ソース]

Exception raised when a parsing or conversion failure is encountered on an argument to pass into a command.

This inherits from UserInputError

パラメータ:
exception discord.ext.commands.BadUnionArgument(param, converters, errors)[ソース]

Exception raised when a typing.Union converter fails for all its associated types.

This inherits from UserInputError

param

The parameter that failed being converted.

Type:

inspect.Parameter

converters

A tuple of converters attempted in conversion, in order of failure.

Type:

Tuple[Type, ...]

errors

A list of errors that were caught from failing the conversion.

Type:

List[CommandError]

パラメータ:
exception discord.ext.commands.BadLiteralArgument(param, literals, errors)[ソース]

Exception raised when a typing.Literal converter fails for all its associated values.

This inherits from UserInputError

Added in version 2.0.

param

The parameter that failed being converted.

Type:

inspect.Parameter

literals

A tuple of values compared against in conversion, in order of failure.

Type:

Tuple[Any, ...]

errors

A list of errors that were caught from failing the conversion.

Type:

List[CommandError]

パラメータ:
exception discord.ext.commands.PrivateMessageOnly(message=None)[ソース]

Exception raised when an operation does not work outside of private message contexts.

This inherits from CheckFailure

パラメータ:

message (str | None)

exception discord.ext.commands.NoPrivateMessage(message=None)[ソース]

Exception raised when an operation does not work in private message contexts.

This inherits from CheckFailure

パラメータ:

message (str | None)

exception discord.ext.commands.CheckFailure(message=None, *args)[ソース]

Exception raised when the predicates in Command.checks have failed.

This inherits from CommandError

パラメータ:
exception discord.ext.commands.CheckAnyFailure(checks, errors)[ソース]

Exception raised when all predicates in check_any() fail.

This inherits from CheckFailure.

Added in version 1.3.

errors

A list of errors that were caught during execution.

Type:

List[CheckFailure]

checks

A list of check predicates that failed.

Type:

List[Callable[[Context], bool]]

パラメータ:
exception discord.ext.commands.CommandNotFound(message=None, *args)[ソース]

Exception raised when a command is attempted to be invoked but no command under that name is found.

This is not raised for invalid subcommands, rather just the initial main command that is attempted to be invoked.

This inherits from CommandError.

パラメータ:
exception discord.ext.commands.DisabledCommand(message=None, *args)[ソース]

Exception raised when the command being invoked is disabled.

This inherits from CommandError

パラメータ:
exception discord.ext.commands.CommandInvokeError(e)[ソース]

Exception raised when the command being invoked raised an exception.

This inherits from CommandError

original

The original exception that was raised. You can also get this via the __cause__ attribute.

Type:

Exception

パラメータ:

e (Exception)

exception discord.ext.commands.TooManyArguments(message=None, *args)[ソース]

Exception raised when the command was passed too many arguments and its Command.ignore_extra attribute was not set to True.

This inherits from UserInputError

パラメータ:
exception discord.ext.commands.UserInputError(message=None, *args)[ソース]

The base exception type for errors that involve errors regarding user input.

This inherits from CommandError.

パラメータ:
exception discord.ext.commands.CommandOnCooldown(cooldown, retry_after, type)[ソース]

Exception raised when the command being invoked is on cooldown.

This inherits from CommandError

cooldown

A class with attributes rate and per similar to the cooldown() decorator.

Type:

Cooldown

type

The type associated with the cooldown.

Type:

BucketType

retry_after

The amount of seconds to wait before you can retry again.

Type:

float

パラメータ:
exception discord.ext.commands.MaxConcurrencyReached(number, per)[ソース]

Exception raised when the command being invoked has reached its maximum concurrency.

This inherits from CommandError.

number

The maximum number of concurrent invokers allowed.

Type:

int

per

The bucket type passed to the max_concurrency() decorator.

Type:

BucketType

パラメータ:
  • number (int)

  • per (BucketType)

exception discord.ext.commands.NotOwner(message=None, *args)[ソース]

Exception raised when the message author is not the owner of the bot.

This inherits from CheckFailure

パラメータ:
exception discord.ext.commands.MessageNotFound(argument)[ソース]

Exception raised when the message provided was not found in the channel.

This inherits from BadArgument

Added in version 1.5.

argument

The message supplied by the caller that was not found

Type:

str

パラメータ:

argument (str)

exception discord.ext.commands.MemberNotFound(argument)[ソース]

Exception raised when the member provided was not found in the bot's cache.

This inherits from BadArgument

Added in version 1.5.

argument

The member supplied by the caller that was not found

Type:

str

パラメータ:

argument (str)

exception discord.ext.commands.GuildNotFound(argument)[ソース]

Exception raised when the guild provided was not found in the bot's cache.

This inherits from BadArgument

Added in version 1.7.

argument

The guild supplied by the called that was not found

Type:

str

パラメータ:

argument (str)

exception discord.ext.commands.UserNotFound(argument)[ソース]

Exception raised when the user provided was not found in the bot's cache.

This inherits from BadArgument

Added in version 1.5.

argument

The user supplied by the caller that was not found

Type:

str

パラメータ:

argument (str)

exception discord.ext.commands.ChannelNotFound(argument)[ソース]

Exception raised when the bot can not find the channel.

This inherits from BadArgument

Added in version 1.5.

argument

The channel supplied by the caller that was not found

Type:

str

パラメータ:

argument (str)

exception discord.ext.commands.ChannelNotReadable(argument)[ソース]

Exception raised when the bot does not have permission to read messages in the channel.

This inherits from BadArgument

Added in version 1.5.

argument

The channel supplied by the caller that was not readable

Type:

Union[abc.GuildChannel, Thread]

パラメータ:

argument (GuildChannel | Thread)

exception discord.ext.commands.ThreadNotFound(argument)[ソース]

Exception raised when the bot can not find the thread.

This inherits from BadArgument

Added in version 2.0.

argument

The thread supplied by the caller that was not found

Type:

str

パラメータ:

argument (str)

exception discord.ext.commands.BadColourArgument(argument)[ソース]

Exception raised when the colour is not valid.

This inherits from BadArgument

Added in version 1.5.

argument

The colour supplied by the caller that was not valid

Type:

str

パラメータ:

argument (str)

exception discord.ext.commands.RoleNotFound(argument)[ソース]

Exception raised when the bot can not find the role.

This inherits from BadArgument

Added in version 1.5.

argument

The role supplied by the caller that was not found

Type:

str

パラメータ:

argument (str)

exception discord.ext.commands.BadInviteArgument(argument)[ソース]

Exception raised when the invite is invalid or expired.

This inherits from BadArgument

Added in version 1.5.

パラメータ:

argument (str)

exception discord.ext.commands.EmojiNotFound(argument)[ソース]

Exception raised when the bot can not find the emoji.

This inherits from BadArgument

Added in version 1.5.

argument

The emoji supplied by the caller that was not found

Type:

str

パラメータ:

argument (str)

exception discord.ext.commands.PartialEmojiConversionFailure(argument)[ソース]

Exception raised when the emoji provided does not match the correct format.

This inherits from BadArgument

Added in version 1.5.

argument

The emoji supplied by the caller that did not match the regex

Type:

str

パラメータ:

argument (str)

exception discord.ext.commands.GuildStickerNotFound(argument)[ソース]

Exception raised when the bot can not find the sticker.

This inherits from BadArgument

Added in version 2.0.

argument

The sticker supplied by the caller that was not found

Type:

str

パラメータ:

argument (str)

exception discord.ext.commands.BadBoolArgument(argument)[ソース]

Exception raised when a boolean argument was not convertible.

This inherits from BadArgument

Added in version 1.5.

argument

The boolean argument supplied by the caller that is not in the predefined list

Type:

str

パラメータ:

argument (str)

exception discord.ext.commands.MissingPermissions(missing_permissions, *args)[ソース]

Exception raised when the command invoker lacks permissions to run a command.

This inherits from CheckFailure

missing_permissions

The required permissions that are missing.

Type:

List[str]

パラメータ:
exception discord.ext.commands.BotMissingPermissions(missing_permissions, *args)[ソース]

Exception raised when the bot's member lacks permissions to run a command.

This inherits from CheckFailure

missing_permissions

The required permissions that are missing.

Type:

List[str]

パラメータ:
exception discord.ext.commands.MissingRole(missing_role)[ソース]

Exception raised when the command invoker lacks a role to run a command.

This inherits from CheckFailure

Added in version 1.1.

missing_role

The required role that is missing. This is the parameter passed to has_role().

Type:

Union[str, int]

パラメータ:

missing_role (str | int)

exception discord.ext.commands.BotMissingRole(missing_role)[ソース]

Exception raised when the bot's member lacks a role to run a command.

This inherits from CheckFailure

Added in version 1.1.

missing_role

The required role that is missing. This is the parameter passed to has_role().

Type:

Union[str, int]

パラメータ:

missing_role (str | int)

exception discord.ext.commands.MissingAnyRole(missing_roles)[ソース]

Exception raised when the command invoker lacks any of the roles specified to run a command.

This inherits from CheckFailure

Added in version 1.1.

missing_roles

The roles that the invoker is missing. These are the parameters passed to has_any_role().

Type:

List[Union[str, int]]

パラメータ:

missing_roles (List[str | int])

exception discord.ext.commands.BotMissingAnyRole(missing_roles)[ソース]

Exception raised when the bot's member lacks any of the roles specified to run a command.

This inherits from CheckFailure

Added in version 1.1.

missing_roles

The roles that the bot's member is missing. These are the parameters passed to has_any_role().

Type:

List[Union[str, int]]

パラメータ:

missing_roles (List[str | int])

exception discord.ext.commands.NSFWChannelRequired(channel)[ソース]

Exception raised when a channel does not have the required NSFW setting.

This inherits from CheckFailure.

Added in version 1.1.

パラメータ:

channel (GuildChannel | Thread) -- The channel that does not have NSFW enabled.

exception discord.ext.commands.FlagError(message=None, *args)[ソース]

The base exception type for all flag parsing related errors.

This inherits from BadArgument.

Added in version 2.0.

パラメータ:
exception discord.ext.commands.BadFlagArgument(flag)[ソース]

An exception raised when a flag failed to convert a value.

This inherits from FlagError

Added in version 2.0.

flag

The flag that failed to convert.

Type:

Flag

パラメータ:

flag (Flag)

exception discord.ext.commands.MissingFlagArgument(flag)[ソース]

An exception raised when a flag did not get a value.

This inherits from FlagError

Added in version 2.0.

flag

The flag that did not get a value.

Type:

Flag

パラメータ:

flag (Flag)

exception discord.ext.commands.TooManyFlags(flag, values)[ソース]

An exception raised when a flag has received too many values.

This inherits from FlagError.

Added in version 2.0.

flag

The flag that received too many values.

Type:

Flag

values

The values that were passed.

Type:

List[str]

パラメータ:
exception discord.ext.commands.MissingRequiredFlag(flag)[ソース]

An exception raised when a required flag was not given.

This inherits from FlagError

Added in version 2.0.

flag

The required flag that was not found.

Type:

Flag

パラメータ:

flag (Flag)

exception discord.ext.commands.CommandRegistrationError(name, *, alias_conflict=False)[ソース]

An exception raised when the command can't be added because the name is already taken by a different command.

This inherits from discord.ClientException

Added in version 1.4.

name

The command name that had the error.

Type:

str

alias_conflict

Whether the name that conflicts is an alias of the command we try to add.

Type:

bool

パラメータ:

Exception Hierarchy