API Reference¶
이 섹션에서는 discord.py의 명령어 확장 모듈에 대해 설명합니다.
Bots¶
봇¶
- defadd_check
- defadd_cog
- defadd_command
- defadd_listener
- @after_invoke
- asyncapplication_info
- asyncbefore_identify_hook
- @before_invoke
- asyncchange_presence
- @check
- @check_once
- defclear
- @command
- asyncconnect
- asynccreate_guild
- asyncdelete_invite
- @event
- asyncfetch_channel
- asyncfetch_guild
- asyncfetch_guilds
- asyncfetch_invite
- asyncfetch_template
- asyncfetch_user
- asyncfetch_user_profile
- asyncfetch_webhook
- asyncfetch_widget
- defget_all_channels
- defget_all_members
- defget_channel
- defget_cog
- defget_command
- asyncget_context
- defget_emoji
- defget_guild
- asyncget_prefix
- defget_user
- @group
- asyncinvoke
- defis_closed
- asyncis_owner
- defis_ready
- defis_ws_ratelimited
- @listen
- defload_extension
- asynclogin
- asynclogout
- asyncon_command_error
- asyncon_error
- asyncprocess_commands
- defreload_extension
- defremove_check
- defremove_cog
- defremove_command
- defremove_listener
- asyncrequest_offline_members
- defrun
- asyncstart
- defunload_extension
- asyncwait_for
- asyncwait_until_ready
- defwalk_commands
-
class
discord.ext.commands.
Bot
(command_prefix, help_command=<default-help-command>, description=None, **options)¶ 디스코드 봇을 나타냅니다.
이 클래스는
discord.Client
의 서브클래스이며 결과적으로discord.Client
로 할 수 있는 모든 작업을 이 봇으로 할 수 있습니다.또한 이 클래스는 커맨드를 관리하는 기능을 제공하기 위해
GroupMixin
를 서브클래스로 갖습니다.-
command_prefix
¶ 명령어 접두어는 커맨드를 실행하기 위해 메시지의 첫부분에 있어야 하는 내용입니다.이는 접두어를 나타내는 문자열이거나, 봇을 첫 매개변수로 가지고 두 번째 매개변수를
discord.Message
로 가지는 콜러블이여야 합니다. 이는 명령어 접두사를 《동적》으로 설정할 수 있게 합니다. 이 콜러블은 일반 함수이거나 코루틴일 수 있습니다.접두어가 항상 일치하는 빈 문자열은 접두어 없는 명령 호출을 가능하게 합니다. DM에서는 유용할 수 있지만 성능 문제와 의도하지 않은 명령어의 호출이 발생할 수 있으므로 서버에서는 피해야 합니다.
명령어 접두어는 또한 접두사에 대한 여러 검사를 사용해야 할 경우 처음으로 일치하는 항목이 호출 접두사임을 나타내는, 문자열들의 반복 가능 객체일 수 있습니다. 이때 접두사는
Context.prefix
를 통해 얻을 수 있습니다. 혼동을 피하기 위해 빈 반복 가능 객체는 허용되지 않습니다.참고
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.- 타입
-
self_bot
¶ If
True
, the bot will only listen to commands invoked by itself rather than ignoring itself. IfFalse
(the default) then the bot will ignore itself. This cannot be changed once initialised.- 타입
-
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.- 타입
Optional[
HelpCommand
]
-
owner_id
¶ The user ID that owns the bot. If this is not set and is then queried via
is_owner()
then it is fetched automatically usingapplication_info()
.- 타입
Optional[
int
]
-
owner_ids
¶ The user IDs that owns the bot. This is similar to
owner_id
. If this is not set and the application is team based, then it is fetched automatically usingapplication_info()
. For performance reasons it is recommended to use aset
for the collection. You cannot set bothowner_id
andowner_ids
.버전 1.3에 추가.
- 타입
Optional[Collection[
int
]]
-
activity
¶ The activity being used upon logging in.
- 타입
Optional[
BaseActivity
]
-
add_check
(func, *, call_once=False)¶ Adds a global check to the bot.
This is the non-decorator interface to
check()
andcheck_once()
.- 매개변수
func – The function that was used as a global check.
call_once (
bool
) – If the function should only be called once perCommand.invoke()
call.
-
add_cog
(cog)¶ Adds a 《cog》 to the bot.
A cog is a class that has its own event listeners and commands.
- 매개변수
cog (
Cog
) – The cog to register to the bot.- 예외
CommandError – 로드하는 중 오류가 발생했습니다.
-
add_command
(command)¶ Adds a
Command
into the internal list of commands.This is usually not called, instead the
command()
orgroup()
shortcut decorators are used instead.버전 1.4에서 변경: Raise
CommandRegistrationError
instead of genericClientException
- 매개변수
command (
Command
) – 추가할 명령어.- 예외
CommandRegistrationError – If the command or its alias is already registered by different command.
TypeError – If the command passed is not a subclass of
Command
.
-
add_listener
(func, name=None)¶ The non decorator alternative to
listen()
.- 매개변수
예제
async def on_ready(): pass async def my_message(message): pass bot.add_listener(on_ready) bot.add_listener(my_message, 'on_message')
-
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
.참고
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.
-
allowed_mentions
¶ 허용된 맨션 설정.
버전 1.4에 추가.
- 타입
Optional[
AllowedMentions
]
-
await
application_info
()¶ 이 함수는 코루틴 입니다.
Retrieves the bot’s application information.
- 예외
HTTPException – Retrieving the information failed somehow.
- 반환값
The bot’s application information.
- 반환 형식
-
await
before_identify_hook
(shard_id, *, initial=False)¶ 이 함수는 코루틴 입니다.
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.
버전 1.4에 추가.
-
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
.참고
The
before_invoke()
andafter_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.
-
cached_messages
¶ Read-only list of messages the connected client has cached.
버전 1.1에 추가.
- 타입
Sequence[
Message
]
-
await
change_presence
(*, activity=None, status=None, afk=False)¶ 이 함수는 코루틴 입니다.
Changes the client’s presence.
예제
game = discord.Game("with the API") await client.change_presence(status=discord.Status.idle, activity=game)
- 매개변수
activity (Optional[
BaseActivity
]) – The activity being done.None
if no currently active activity is done.status (Optional[
Status
]) – Indicates what status to change to. IfNone
, thenStatus.online
is used.afk (Optional[
bool
]) – Indicates if you are going AFK. This allows the discord client to know how to handle push notifications better for you in case you are actually idle and not lying.
- 예외
InvalidArgument – If the
activity
parameter is not the proper type.
-
check
(func)¶ 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 typeContext
and can only raise exceptions inherited fromCommandError
.예제
@bot.check def check_commands(ctx): return ctx.command.qualified_name in allowed_commands
-
check_once
(func)¶ A decorator that adds a 《call once》 global check to the bot.
Unlike regular global checks, this one is called only once per
Command.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 perBot.invoke()
call.참고
This function can either be a regular function or a coroutine.
Similar to a command
check()
, this takes a single parameter of typeContext
and can only raise exceptions inherited fromCommandError
.예제
@bot.check_once def whitelist(ctx): return ctx.message.author.id in my_whitelist
-
clear
()¶ Clears the internal state of the bot.
After this, the bot can be considered 《re-opened》, i.e.
is_closed()
andis_ready()
both returnFalse
along with the bot’s internal cache cleared.
-
command
(*args, **kwargs)¶ A shortcut decorator that invokes
command()
and adds it to the internal command list viaadd_command()
.- 반환값
A decorator that converts the provided method into a Command, adds it to the bot, then returns it.
- 반환 형식
Callable[…,
Command
]
-
await
connect
(*, reconnect=True)¶ 이 함수는 코루틴 입니다.
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 – If the gateway to connect to Discord is not found. Usually if this is thrown then there is a Discord API outage.
ConnectionClosed – The websocket connection has been terminated.
-
await
create_guild
(name, region=None, icon=None, *, code=None)¶ 이 함수는 코루틴 입니다.
Creates a
Guild
.Bot accounts in more than 10 guilds are not allowed to create guilds.
- 매개변수
name (
str
) – The name of the guild.region (
VoiceRegion
) – The region for the voice communication server. Defaults toVoiceRegion.us_west
.icon (
bytes
) – The bytes-like object representing the icon. SeeClientUser.edit()
for more details on what is expected.code (Optional[
str
]) –The code for a template to create the guild with.
버전 1.4에 추가.
- 예외
HTTPException – Guild creation failed.
InvalidArgument – Invalid icon image format given. Must be PNG or JPG.
- 반환값
The guild created. This is not the same guild that is added to cache.
- 반환 형식
-
await
delete_invite
(invite)¶ 이 함수는 코루틴 입니다.
Revokes an
Invite
, URL, or ID to an invite.You must have the
manage_channels
permission in the associated guild to do this.- 매개변수
- 예외
Forbidden – You do not have permissions to revoke invites.
NotFound – The invite is invalid or expired.
HTTPException – Revoking the invite failed.
-
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.예제
@client.event async def on_ready(): print('Ready!')
- 예외
TypeError – 전달된 코루틴이 사실 코루틴이 아닙니다.
-
extensions
¶ A read-only mapping of extension name to extension.
- 타입
Mapping[
str
,types.ModuleType
]
-
await
fetch_channel
(channel_id)¶ 이 함수는 코루틴 입니다.
Retrieves a
abc.GuildChannel
orabc.PrivateChannel
with the specified ID.참고
This method is an API call. For general usage, consider
get_channel()
instead.버전 1.2에 추가.
- 예외
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.
- 반환값
The channel from the ID.
- 반환 형식
Union[
abc.GuildChannel
,abc.PrivateChannel
]
-
await
fetch_guild
(guild_id)¶ 이 함수는 코루틴 입니다.
Retrieves a
Guild
from an ID.참고
Using this, you will not receive
Guild.channels
,Guild.members
,Member.activity
andMember.voice
perMember
.참고
This method is an API call. For general usage, consider
get_guild()
instead.- 매개변수
guild_id (
int
) – The guild’s ID to fetch from.- 예외
Forbidden – You do not have access to the guild.
HTTPException – Getting the guild failed.
- 반환값
The guild from the ID.
- 반환 형식
-
fetch_guilds
(*, limit=100, before=None, after=None)¶ 이 함수는 코루틴 입니다.
Retrieves an
AsyncIterator
that enables receiving your guilds.참고
Using this, you will only receive
Guild.owner
,Guild.icon
,Guild.id
, andGuild.name
perGuild
.참고
This method is an API call. For general usage, consider
guilds
instead.예제
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.
- 매개변수
limit (Optional[
int
]) – The number of guilds to retrieve. IfNone
, it retrieves every guild you have access to. Note, however, that this would make it a slow operation. Defaults to100
.before (Union[
abc.Snowflake
,datetime.datetime
]) – Retrieves guilds before this date or object. If a date is provided it must be a timezone-naive datetime representing UTC time.after (Union[
abc.Snowflake
,datetime.datetime
]) – Retrieve guilds after this date or object. If a date is provided it must be a timezone-naive datetime representing UTC time.
- 예외
HTTPException – Getting the guilds failed.
- Yields
Guild
– The guild with the guild data parsed.
-
await
fetch_invite
(url, *, with_counts=True)¶ 이 함수는 코루틴 입니다.
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 bePartialInviteGuild
andPartialInviteChannel
respectively.- 매개변수
url (Union[
Invite
,str
]) – The Discord invite ID or URL (must be a discord.gg URL).with_counts (
bool
) – Whether to include count information in the invite. This fills theInvite.approximate_member_count
andInvite.approximate_presence_count
fields.
- 예외
NotFound – The invite has expired or is invalid.
HTTPException – Getting the invite failed.
- 반환값
The invite from the URL/ID.
- 반환 형식
-
await
fetch_template
(code)¶ 이 함수는 코루틴 입니다.
Gets a
Template
from a discord.new URL or code.- 매개변수
code (Union[
Template
,str
]) – The Discord Template Code or URL (must be a discord.new URL).- 예외
NotFound – The template is invalid.
HTTPException – Getting the template failed.
- 반환값
The template from the URL/code.
- 반환 형식
-
await
fetch_user
(user_id)¶ 이 함수는 코루틴 입니다.
Retrieves a
User
based on their ID. This can only be used by bot accounts. 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. For general usage, consider
get_user()
instead.- 매개변수
user_id (
int
) – The user’s ID to fetch from.- 예외
NotFound – A user with this ID does not exist.
HTTPException – Fetching the user failed.
- 반환값
The user you requested.
- 반환 형식
-
await
fetch_user_profile
(user_id)¶ 이 함수는 코루틴 입니다.
Gets an arbitrary user’s profile.
버전 1.7부터 폐지.
참고
This can only be used by non-bot accounts.
- 매개변수
user_id (
int
) – The ID of the user to fetch their profile for.- 예외
Forbidden – Not allowed to fetch profiles.
HTTPException – Fetching the profile failed.
- 반환값
The profile of the user.
- 반환 형식
-
await
fetch_webhook
(webhook_id)¶ 이 함수는 코루틴 입니다.
Retrieves a
Webhook
with the specified ID.- 예외
HTTPException – Retrieving the webhook failed.
NotFound – Invalid webhook ID.
Forbidden – You do not have permission to fetch this webhook.
- 반환값
The webhook you requested.
- 반환 형식
-
await
fetch_widget
(guild_id)¶ 이 함수는 코루틴 입니다.
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.- 예외
Forbidden – The widget for this guild is disabled.
HTTPException – Retrieving the widget failed.
- 반환값
The guild’s widget.
- 반환 형식
-
for ... in
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.- Yields
abc.GuildChannel
– A channel the client can 〈access〉.
-
for ... in
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
- Yields
Member
– A member the client can see.
-
get_channel
(id)¶ Returns a channel with the given ID.
- 매개변수
id (
int
) – The ID to search for.- 반환값
The returned channel or
None
if not found.- 반환 형식
Optional[Union[
abc.GuildChannel
,abc.PrivateChannel
]]
-
get_cog
(name)¶ Gets the cog instance requested.
If the cog is not found,
None
is returned instead.
-
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 subcommandbar
of the group commandfoo
. If a subcommand is not found thenNone
is returned just as usual.
-
await
get_context
(message, *, cls=<class 'discord.ext.commands.context.Context'>)¶ 이 함수는 코루틴 입니다.
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 underinvoke()
.- 매개변수
message (
discord.Message
) – The message to get the invocation context from.cls – 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 toContext
's interface.
- 반환값
The invocation context. The type of this can change via the
cls
parameter.- 반환 형식
-
get_emoji
(id)¶ Returns an emoji with the given ID.
-
get_guild
(id)¶ Returns a guild with the given ID.
-
await
get_prefix
(message)¶ 이 함수는 코루틴 입니다.
Retrieves the prefix the bot is listening to with the message as a context.
- 매개변수
message (
discord.Message
) – The message context to get the prefix of.- 반환값
A list of prefixes or a single prefix that the bot is listening for.
- 반환 형식
-
get_user
(id)¶ Returns a user with the given ID.
-
group
(*args, **kwargs)¶ A shortcut decorator that invokes
group()
and adds it to the internal command list viaadd_command()
.- 반환값
A decorator that converts the provided method into a Group, adds it to the bot, then returns it.
- 반환 형식
Callable[…,
Group
]
-
intents
¶ The intents configured for this connection.
버전 1.5에 추가.
- 타입
Intents
-
await
invoke
(ctx)¶ 이 함수는 코루틴 입니다.
Invokes the command given under the invocation context and handles all the internal event dispatch mechanisms.
- 매개변수
ctx (
Context
) – The invocation context to invoke.
-
await
is_owner
(user)¶ 이 함수는 코루틴 입니다.
Checks if a
User
orMember
is the owner of this bot.If an
owner_id
is not set, it is fetched automatically through the use ofapplication_info()
.버전 1.3에서 변경: The function also checks if the application is team-owned if
owner_ids
is not set.
-
is_ws_ratelimited
()¶ bool
: 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.
버전 1.6에 추가.
-
latency
¶ Measures latency between a HEARTBEAT and a HEARTBEAT_ACK in seconds.
This could be referred to as the Discord WebSocket protocol latency.
- 타입
-
listen
(name=None)¶ 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.
예제
@bot.listen() async def on_message(message): print('one') # in some other file... @bot.listen('on_message') async def my_message(message): print('two')
Would print one and two in an unspecified order.
- 예외
TypeError – The function being listened to is not a coroutine.
-
load_extension
(name, *, package=None)¶ 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, thebot
.- 매개변수
name (
str
) – The extension name to load. It must be dot separated like regular Python imports if accessing a sub-module. e.g.foo.test
if you want to importfoo/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 toNone
.버전 1.7에 추가.
- 예외
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.
-
await
login
(token, *, bot=True)¶ 이 함수는 코루틴 입니다.
Logs in the client with the specified credentials.
This function can be used in two different ways.
경고
Logging on with a user token is against the Discord Terms of Service and doing so might potentially get your account banned. Use this at your own risk.
- 매개변수
- 예외
LoginFailure – The wrong credentials are passed.
HTTPException – An unknown HTTP related error occurred, usually when it isn’t 200 or the known incorrect credentials passing status code.
-
await
logout
()¶ 이 함수는 코루틴 입니다.
Logs out of Discord and closes all connections.
참고
This is just an alias to
close()
. If you want to do extraneous cleanup when subclassing, it is suggested to overrideclose()
instead.
-
await
on_command_error
(context, exception)¶ 이 함수는 코루틴 입니다.
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.
-
await
on_error
(event_method, *args, **kwargs)¶ 이 함수는 코루틴 입니다.
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. Checkon_error()
for more details.
-
private_channels
¶ 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.
- 타입
List[
abc.PrivateChannel
]
-
await
process_commands
(message)¶ 이 함수는 코루틴 입니다.
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 theon_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 toinvoke()
.This also checks if the message’s author is a bot and doesn’t call
get_context()
orinvoke()
if so.- 매개변수
message (
discord.Message
) – The message to process commands for.
-
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 aload_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 sub-module. e.g.foo.test
if you want to importfoo/test.py
.package (Optional[
str
]) –The package name to resolve relative imports with. This is required when reloading an extension using a relative path, e.g
.foo.test
. Defaults toNone
.버전 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.
-
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 withcall_once=True
in theBot.add_check()
call or usingcheck_once()
.
-
remove_cog
(name)¶ Removes a cog from the bot.
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.
-
remove_command
(name)¶ Remove a
Command
from the internal list of commands.This could also be used as a way to remove aliases.
-
remove_listener
(func, name=None)¶ Removes a listener from the pool of listeners.
- 매개변수
func – The function that was used as a listener to remove.
name (
str
) – The name of the event we want to remove. Defaults tofunc.__name__
.
-
await
request_offline_members
(*guilds)¶ 이 함수는 코루틴 입니다.
Requests previously offline members from the guild to be filled up into the
Guild.members
cache. This function is usually not called. It should only be used if you have thefetch_offline_members
parameter set toFalse
.When the client logs on and connects to the websocket, Discord does not provide the library with offline members if the number of members in the guild is larger than 250. You can check if a guild is large if
Guild.large
isTrue
.경고
This method is deprecated. Use
Guild.chunk()
instead.- 매개변수
*guilds (
Guild
) – An argument list of guilds to request offline members for.- 예외
InvalidArgument – If any guild is unavailable in the collection.
-
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 orconnect()
+login()
.Roughly Equivalent to:
try: loop.run_until_complete(start(*args, **kwargs)) except KeyboardInterrupt: loop.run_until_complete(logout()) # 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.
-
await
start
(*args, **kwargs)¶ 이 함수는 코루틴 입니다.
A shorthand coroutine for
login()
+connect()
.- 예외
TypeError – An unexpected keyword argument was received.
-
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, thebot
, similar tosetup
fromload_extension()
.- 매개변수
name (
str
) – The extension name to unload. It must be dot separated like regular Python imports if accessing a sub-module. e.g.foo.test
if you want to importfoo/test.py
.package (Optional[
str
]) –The package name to resolve relative imports with. This is required when unloading an extension using a relative path, e.g
.foo.test
. Defaults toNone
.버전 1.7에 추가.
- 예외
ExtensionNotFound – The name of the extension could not be resolved using the provided
package
parameter.ExtensionNotLoaded – The extension was not loaded.
-
user
¶ Represents the connected client.
None
if not logged in.- 타입
Optional[
ClientUser
]
-
voice_clients
¶ Represents a list of voice connections.
These are usually
VoiceClient
instances.- 타입
List[
VoiceProtocol
]
-
wait_for
(event, *, check=None, timeout=None)¶ 이 함수는 코루틴 입니다.
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 ontoasyncio.wait_for()
. By default, it does not timeout. Note that this does propagate theasyncio.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.
예제
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('Hello {.author}!'.format(msg))
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('👍')
- 매개변수
event (
str
) – The event name, similar to the event reference, but without theon_
prefix, to wait for.check (Optional[Callable[…,
bool
]]) – A predicate to check what to wait for. The arguments must meet the parameters of the event being waited for.timeout (Optional[
float
]) – The number of seconds to wait before timing out and raisingasyncio.TimeoutError
.
- 예외
asyncio.TimeoutError – If a timeout is provided and it was reached.
- 반환값
Returns no arguments, a single argument, or a
tuple
of multiple arguments that mirrors the parameters passed in the event reference.- 반환 형식
Any
-
AutoShardedBot¶
-
class
discord.ext.commands.
AutoShardedBot
(command_prefix, help_command=<default-help-command>, description=None, **options)¶ This is similar to
Bot
except that it is inherited fromdiscord.AutoShardedClient
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.
-
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)
더 보기
Event Reference¶
These events function similar to the regular events, except they are custom to the command extension module.
-
discord.
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.
Commands¶
Decorators¶
-
discord.ext.commands.
command
(name=None, cls=None, **attrs)¶ A decorator that transforms a function into a
Command
or if called withgroup()
,Group
.By default the
help
attribute is received automatically from the docstring of the function and is cleaned up with the use ofinspect.cleandoc
. If the docstring isbytes
, then it is decoded intostr
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.- 매개변수
- 예외
TypeError – If the function is not a coroutine or is already a command.
Command¶
- async__call__
- defadd_check
- @after_invoke
- @before_invoke
- asynccan_run
- defcopy
- @error
- defget_cooldown_retry_after
- defhas_error_handler
- defis_on_cooldown
- defremove_check
- defreset_cooldown
- defupdate
-
class
discord.ext.commands.
Command
(*args, **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.
-
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 theon_command_error()
event. Defaults toTrue
.- 타입
-
parent
¶ The parent command that this command belongs to.
None
if there isn’t one.- 타입
Optional[
Command
]
-
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 fromCommandError
should be used. Note that if the checks fail thenCheckFailure
exception is raised to theon_command_error()
event.- 타입
List[Callable[…,
bool
]]
If
True
, the default help command does not show this in the help output.- 타입
-
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 handlesMissingRequiredArgument
and default values in a regular matter rather than passing the rest completely raw. IfTrue
then the keyword-only argument will pass in the rest of the arguments in a completely raw matter. Defaults toFalse
.- 타입
-
require_var_positional
¶ If
True
and a variadic positional argument is specified, requires the user to specify at least one argument. Defaults toFalse
.버전 1.5에 추가.
- 타입
-
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 expectinga
andb
). Otherwiseon_command_error()
and local error handlers are called withTooManyArguments
. Defaults toTrue
.- 타입
-
cooldown_after_parsing
¶ If
True
, cooldown processing is done after argument parsing, which calls converters. IfFalse
then cooldown processing is done first and then the converters are called second. Defaults toFalse
.- 타입
-
add_check
(func)¶ Adds a check to the command.
This is the non-decorator interface to
check()
.버전 1.3에 추가.
- 매개변수
func – The function that will be used as a check.
-
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.
버전 1.3에 추가.
- 매개변수
func – The function to remove from the checks.
-
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 theCommand
or subclass constructors, sans the name and callback.
-
await
__call__
(*args, **kwargs)¶ 이 함수는 코루틴 입니다.
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.
버전 1.3에 추가.
-
clean_params
¶ OrderedDict[
str
,inspect.Parameter
]: Retrieves the parameter OrderedDict without the context or self parameters.Useful for inspecting signature.
-
full_parent_name
¶ 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 beone two
.- 타입
-
parents
¶ 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]
.버전 1.1에 추가.
- 타입
List[
Command
]
-
root_parent
¶ 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 isa
.- 타입
Optional[
Command
]
-
qualified_name
¶ 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 beone two three
.- 타입
-
is_on_cooldown
(ctx)¶ Checks whether the command is currently on cooldown.
-
reset_cooldown
(ctx)¶ Resets the cooldown on this command.
- 매개변수
ctx (
Context
) – The invocation context to reset the cooldown under.
-
get_cooldown_retry_after
(ctx)¶ Retrieves the amount of seconds before this command can be tried again.
버전 1.4에 추가.
-
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, theon_command_error()
is still invoked afterwards as the catch-all.
-
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.
-
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.
-
short_doc
¶ 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 thehelp
attribute is used instead.- 타입
-
await
can_run
(ctx)¶ 이 함수는 코루틴 입니다.
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.- 예외
CommandError – Any command error that was raised during a check call will be propagated by this function.
- 반환값
A boolean indicating if the command can be invoked.
- 반환 형식
-
Group¶
- defadd_check
- defadd_command
- @after_invoke
- @before_invoke
- asynccan_run
- @command
- defcopy
- @error
- defget_command
- defget_cooldown_retry_after
- @group
- defhas_error_handler
- defis_on_cooldown
- defremove_check
- defremove_command
- defreset_cooldown
- defupdate
- defwalk_commands
-
class
discord.ext.commands.
Group
(*args, **kwargs)¶ 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 inCommand
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 toFalse
.- 타입
-
case_insensitive
¶ Indicates if the group’s commands should be case insensitive. Defaults to
False
.- 타입
-
add_check
(func)¶ Adds a check to the command.
This is the non-decorator interface to
check()
.버전 1.3에 추가.
- 매개변수
func – The function that will be used as a check.
-
add_command
(command)¶ Adds a
Command
into the internal list of commands.This is usually not called, instead the
command()
orgroup()
shortcut decorators are used instead.버전 1.4에서 변경: Raise
CommandRegistrationError
instead of genericClientException
- 매개변수
command (
Command
) – 추가할 명령어.- 예외
CommandRegistrationError – If the command or its alias is already registered by different command.
TypeError – If the command passed is not a subclass of
Command
.
-
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.
-
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.
-
await
can_run
(ctx)¶ 이 함수는 코루틴 입니다.
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.- 예외
CommandError – Any command error that was raised during a check call will be propagated by this function.
- 반환값
A boolean indicating if the command can be invoked.
- 반환 형식
-
clean_params
¶ OrderedDict[
str
,inspect.Parameter
]: Retrieves the parameter OrderedDict without the context or self parameters.Useful for inspecting signature.
-
command
(*args, **kwargs)¶ A shortcut decorator that invokes
command()
and adds it to the internal command list viaadd_command()
.- 반환값
A decorator that converts the provided method into a Command, adds it to the bot, then returns it.
- 반환 형식
Callable[…,
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, theon_command_error()
is still invoked afterwards as the catch-all.
-
full_parent_name
¶ 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 beone 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 subcommandbar
of the group commandfoo
. If a subcommand is not found thenNone
is returned just as usual.
-
get_cooldown_retry_after
(ctx)¶ Retrieves the amount of seconds before this command can be tried again.
버전 1.4에 추가.
-
group
(*args, **kwargs)¶ A shortcut decorator that invokes
group()
and adds it to the internal command list viaadd_command()
.- 반환값
A decorator that converts the provided method into a Group, adds it to the bot, then returns it.
- 반환 형식
Callable[…,
Group
]
-
is_on_cooldown
(ctx)¶ Checks whether the command is currently on cooldown.
-
parents
¶ 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]
.버전 1.1에 추가.
- 타입
List[
Command
]
-
qualified_name
¶ 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 beone 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.
버전 1.3에 추가.
- 매개변수
func – The function to remove from the checks.
-
remove_command
(name)¶ Remove a
Command
from the internal list of commands.This could also be used as a way to remove aliases.
-
reset_cooldown
(ctx)¶ Resets the cooldown on this command.
- 매개변수
ctx (
Context
) – The invocation context to reset the cooldown under.
-
root_parent
¶ 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 isa
.- 타입
Optional[
Command
]
-
short_doc
¶ 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 thehelp
attribute is used instead.- 타입
-
GroupMixin¶
- defadd_command
- @command
- defget_command
- @group
- defremove_command
- defwalk_commands
-
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.-
add_command
(command)¶ Adds a
Command
into the internal list of commands.This is usually not called, instead the
command()
orgroup()
shortcut decorators are used instead.버전 1.4에서 변경: Raise
CommandRegistrationError
instead of genericClientException
- 매개변수
command (
Command
) – 추가할 명령어.- 예외
CommandRegistrationError – If the command or its alias is already registered by different command.
TypeError – If the command passed is not a subclass of
Command
.
-
remove_command
(name)¶ Remove a
Command
from the internal list of commands.This could also be used as a way to remove aliases.
-
for ... in
walk_commands
()¶ An iterator that recursively walks through all commands and subcommands.
버전 1.4에서 변경: Duplicates due to aliases are no longer returned
-
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 subcommandbar
of the group commandfoo
. If a subcommand is not found thenNone
is returned just as usual.
-
command
(*args, **kwargs)¶ A shortcut decorator that invokes
command()
and adds it to the internal command list viaadd_command()
.- 반환값
A decorator that converts the provided method into a Command, adds it to the bot, then returns it.
- 반환 형식
Callable[…,
Command
]
-
group
(*args, **kwargs)¶ A shortcut decorator that invokes
group()
and adds it to the internal command list viaadd_command()
.- 반환값
A decorator that converts the provided method into a Group, adds it to the bot, then returns it.
- 반환 형식
Callable[…,
Group
]
-
Cogs¶
Cog¶
- clsCog.listener
- defbot_check
- defbot_check_once
- asynccog_after_invoke
- asynccog_before_invoke
- defcog_check
- asynccog_command_error
- defcog_unload
- defget_commands
- defget_listeners
- defhas_error_handler
- defwalk_commands
-
class
discord.ext.commands.
Cog
(*args, **kwargs)¶ The base class that all cogs must inherit from.
A cog is a collection of commands, listeners, and optional state to help group commands together. More information on them can be found on the Cogs page.
When inheriting from this class, the options shown in
CogMeta
are equally valid here.-
get_commands
()¶
-
for ... in
walk_commands
()¶ An iterator that recursively walks through this cog’s commands and subcommands.
-
classmethod
listener
(name=None)¶ A decorator that marks a function as a listener.
This is the cog equivalent of
Bot.listen()
.
-
cog_unload
()¶ A special method that is called when the cog gets removed.
This function cannot be a coroutine. It must be a regular function.
Subclasses must replace this if they want special unloading behaviour.
-
bot_check_once
(ctx)¶ A special method that registers as a
Bot.check_once()
check.This function can be a coroutine and must take a sole parameter,
ctx
, to represent theContext
.
-
bot_check
(ctx)¶ A special method that registers as a
Bot.check()
check.This function can be a coroutine and must take a sole parameter,
ctx
, to represent theContext
.
-
cog_check
(ctx)¶ A special method that registers as a
commands.check()
for every command and subcommand in this cog.This function can be a coroutine and must take a sole parameter,
ctx
, to represent theContext
.
-
await
cog_command_error
(ctx, error)¶ A special method that is called whenever an error is dispatched inside this cog.
This is similar to
on_command_error()
except only applying to the commands inside this cog.This must be a coroutine.
- 매개변수
ctx (
Context
) – The invocation context where the error happened.error (
CommandError
) – The error that happened.
-
await
cog_before_invoke
(ctx)¶ A special method that acts as a cog local pre-invoke hook.
This is similar to
Command.before_invoke()
.This must be a coroutine.
- 매개변수
ctx (
Context
) – The invocation context.
-
await
cog_after_invoke
(ctx)¶ A special method that acts as a cog local post-invoke hook.
This is similar to
Command.after_invoke()
.This must be a coroutine.
- 매개변수
ctx (
Context
) – The invocation context.
-
CogMeta¶
-
class
discord.ext.commands.
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(commands.CogMeta, abc.ABCMeta): pass class SomeMixin(metaclass=abc.ABCMeta): pass class SomeCogMixin(SomeMixin, commands.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(commands.Cog, name='My Cog'): pass
-
description
¶ The cog description. By default, it is the cleaned docstring of the class.
버전 1.6에 추가.
- 타입
-
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(commands.Cog, command_attrs=dict(hidden=True)): @commands.command() async def foo(self, ctx): pass # hidden -> True @commands.command(hidden=False) async def bar(self, ctx): pass # hidden -> False
- 타입
-
Help Commands¶
HelpCommand¶
- defadd_check
- asynccommand_callback
- defcommand_not_found
- asyncfilter_commands
- defget_bot_mapping
- defget_command_signature
- defget_destination
- defget_max_size
- asyncon_help_command_error
- asyncprepare_help_command
- defremove_check
- defremove_mentions
- asyncsend_bot_help
- asyncsend_cog_help
- asyncsend_command_help
- asyncsend_error_message
- asyncsend_group_help
- defsubcommand_not_found
-
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.- 타입
Optional[
Context
]
Specifies if hidden commands should be shown in the output. Defaults to
False
.- 타입
-
verify_checks
¶ Specifies if commands should have their
Command.checks
called and verified. IfTrue
, always callsCommands.checks
. IfNone
, only callsCommands.checks
in a guild setting. IfFalse
, never callsCommands.checks
. Defaults toTrue
...versionchanged:: 1.7
- 타입
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.- 타입
-
add_check
(func)¶ Adds a check to the help command.
버전 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.
버전 1.4에 추가.
- 매개변수
func – The function to remove from the checks.
-
get_bot_mapping
()¶ Retrieves the bot mapping passed to
send_bot_help()
.
-
invoked_with
¶ Similar to
Context.invoked_with
except properly handles the case whereContext.send_help()
is used.If the help command was used regularly then this returns the
Context.invoked_with
attribute. Otherwise, if it the help command was called usingContext.send_help()
then it returns the internal command name of the help command.- 반환값
The command name that triggered this invocation.
- 반환 형식
-
get_command_signature
(command)¶ Retrieves the signature portion of the help page.
-
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.
- 반환 형식
-
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)¶ 이 함수는 코루틴 일 수 있습니다.
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.
-
subcommand_not_found
(command, string)¶ 이 함수는 코루틴 일 수 있습니다.
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 namedstring
.
-
await
filter_commands
(commands, *, sort=False, key=None)¶ 이 함수는 코루틴 입니다.
Returns a filtered list of commands and optionally sorts them.
This takes into account the
verify_checks
andshow_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 tosorted()
that takes aCommand
as its sole parameter. Ifsort
is passed asTrue
then this will default as the command name.
- 반환값
A list of commands that passed the filter.
- 반환 형식
List[
Command
]
-
get_max_size
(commands)¶ Returns the largest name length of the specified command list.
-
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.
- 반환 형식
-
await
send_error_message
(error)¶ 이 함수는 코루틴 입니다.
Handles the implementation when an error happens in the help command. For example, the result of
command_not_found()
orcommand_has_no_subcommand_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)¶ 이 함수는 코루틴 입니다.
The help command’s error handler, as specified by 에러 다루기.
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.
- 매개변수
ctx (
Context
) – The invocation context.error (
CommandError
) – The error that was raised.
-
await
send_bot_help
(mapping)¶ 이 함수는 코루틴 입니다.
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.
-
await
send_cog_help
(cog)¶ 이 함수는 코루틴 입니다.
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 callfilter_commands()
yourself.- 매개변수
cog (
Cog
) – The cog that was requested for help.
-
await
send_group_help
(group)¶ 이 함수는 코루틴 입니다.
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 callfilter_commands()
yourself.- 매개변수
group (
Group
) – The group that was requested for help.
-
await
send_command_help
(command)¶ 이 함수는 코루틴 입니다.
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)¶ 이 함수는 코루틴 입니다.
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.
-
DefaultHelpCommand¶
- defadd_command_formatting
- defadd_indented_commands
- defget_destination
- defget_ending_note
- asyncsend_pages
- defshorten_text
-
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.
-
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. IfFalse
, none of the help output is DM’d. IfNone
, then the bot will only DM when the help message becomes too long (dictated by more thandm_help_threshold
characters). Defaults toFalse
.- 타입
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 toNone
. Defaults to 1000.- 타입
Optional[
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:"
- 타입
-
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"
- 타입
-
get_ending_note
()¶ str
: Returns help command’s ending note. This is mainly useful to override for i18n purposes.
-
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 tomax_size
followed by the command’sCommand.short_doc
and then shortened to fit into thewidth
.- 매개변수
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, callsget_max_size()
on the commands parameter.
-
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.
- 반환 형식
-
MinimalHelpCommand¶
-
class
discord.ext.commands.
MinimalHelpCommand
(*args, **kwargs)¶ An implementation of a help command with minimal output.
This inherits from
HelpCommand
.-
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"
- 타입
-
aliases_heading
¶ The alias list’s heading string used to list the aliases of the command. Useful for i18n. Defaults to
"Aliases:"
.- 타입
-
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. IfFalse
, none of the help output is DM’d. IfNone
, then the bot will only DM when the help message becomes too long (dictated by more thandm_help_threshold
characters). Defaults toFalse
.- 타입
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 toNone
. Defaults to 1000.- 타입
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"
- 타입
-
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.
- 반환 형식
-
get_command_signature
(command)¶ Retrieves the signature portion of the help page.
-
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.
- 반환 형식
-
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.
-
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’sCommand.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.
- 반환 형식
-
Paginator¶
-
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.
-
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.- 매개변수
- 예외
RuntimeError – The line was too big for the current
max_size
.
-
close_page
()¶ Prematurely terminate a page.
-
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.
버전 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 viaCommand.checks
.These checks should be predicates that take in a single parameter taking a
Context
. If the check returns aFalse
-like value then during invocation aCheckFailure
exception is raised and sent to theon_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 toon_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!')
-
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 fromCheckFailure
.참고
The
predicate
attribute for this function is a coroutine.버전 1.3에 추가.
- 매개변수
*checks (Callable[[
Context
],bool
]) – An argument list of checks that have been decorated with thecheck()
decorator.- 예외
TypeError – A check passed has not been decorated with the
check()
decorator.
예제
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!')
-
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, orNoPrivateMessage
if it is used in a private message. Both inherit fromCheckFailure
.버전 1.1에서 변경: Raise
MissingRole
orNoPrivateMessage
instead of genericCheckFailure
-
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 fromCheckFailure
.- 매개변수
perms – An argument list of permissions to check for.
예제
@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
.버전 1.3에 추가.
-
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, orNoPrivateMessage
if it is used in a private message. Both inherit fromCheckFailure
.버전 1.1에서 변경: Raise
MissingAnyRole
orNoPrivateMessage
instead of genericCheckFailure
- 매개변수
items (List[Union[
str
,int
]]) – An argument list of names or IDs to check that the member has roles wise.
예제
@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, orNoPrivateMessage
if it is used in a private message. Both inherit fromCheckFailure
.버전 1.1에서 변경: Raise
BotMissingRole
orNoPrivateMessage
instead of genericCheckFailure
-
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 fromCheckFailure
.
-
discord.ext.commands.
bot_has_guild_permissions
(**perms)¶ Similar to
has_guild_permissions()
, but checks the bot members guild permissions.버전 1.3에 추가.
-
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, orNoPrivateMessage
if it is used in a private message. Both inherit fromCheckFailure
.버전 1.1에서 변경: Raise
BotMissingAnyRole
orNoPrivateMessage
instead of generic checkfailure
-
discord.ext.commands.
cooldown
(rate, per, type=<BucketType.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 typeBucketType
.If a cooldown is triggered, then
CommandOnCooldown
is triggered inon_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
) – The type of cooldown to have.
-
discord.ext.commands.
max_concurrency
(number, per=<BucketType.default: 0>, *, wait=False)¶ A decorator that adds a maximum concurrency to a
Command
or its subclasses.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.
버전 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 tonumber
times per guild.wait (
bool
) – Whether the command should wait for the queue to be over. If this is set toFalse
then instead of waiting until the command can run again, the command raisesMaxConcurrencyReached
to its error handler. If this is set toTrue
then the command waits until it can be executed.
-
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.
버전 1.4에 추가.
예제
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('and i have existed since {}'.format(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.
버전 1.4에 추가.
-
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 fromCheckFailure
.
-
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 fromCheckFailure
.버전 1.1에 추가.
-
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 fromCheckFailure
.
-
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 fromCheckFailure
.버전 1.1에서 변경: Raise
NSFWChannelRequired
instead of genericCheckFailure
. DM channels will also now pass this check.
컨텍스트¶
- asyncfetch_message
- defhistory
- asyncinvoke
- asyncpins
- asyncreinvoke
- asyncreply
- asyncsend
- asyncsend_help
- asynctrigger_typing
- deftyping
-
class
discord.ext.commands.
Context
(**attrs)¶ 명령어가 실행되고 있는 컨텍스트를 나타냅니다.
이 클래스는 호출 컨텍스트를 더 잘 이해하는 것을 도와주기 위해 여러가지 메타 데이터가 들어가있습니다. 이 클래스는 수동으로 생성되지 않는 대신 명령어의 첫 매개변수로 전달됩니다.
이 클래스는
Messageable
ABC를 구현합니다.-
args
¶ 명령어로 전달된 변환된 전달인자들의 리스트. 만약에 이것이
on_command_error()
이벤트 도중에 접근된 경우 이 리스트는 불완전할 수 있습니다.- 타입
-
kwargs
¶ 명령어로 전달된 변환된 전달인자들의 딕셔너리.
args
와 비슷하게, 만약에 이것이on_command_error()
이벤트 도중에 접근된 경우 이 딕셔너리는 불완전할 수 있습니다.- 타입
-
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']
.버전 1.7에 추가.
- 타입
List[
str
]
-
invoked_subcommand
¶ The subcommand that was invoked. If no valid subcommand was invoked then this is equal to
None
.- 타입
-
subcommand_passed
¶ 서브커맨드 호출을 시도하기 위해 사용된 문자열. 이것은 항상 유효한 등록된 서브커맨드를 가리키지 않고 의미없는 문자열일 수 있습니다. 만약에 서브커맨드 호출을 시도하기 위해 아무것도 사용되지 않았다면 이것은
None
입니다.- 타입
Optional[
str
]
-
async for ... in
history
(*, limit=100, before=None, after=None, around=None, oldest_first=None)¶ 목적지의 메시지 역사를 받을 수 있도록 활성화해주는
AsyncIterator
를 반환.이것을 사용하기 위해서는
read_message_history
권한이 필요합니다.예제
Usage
counter = 0 async for message in channel.history(limit=200): if message.author == client.user: counter += 1
리스트로 압축하기:
messages = await channel.history(limit=123).flatten() # messages is now a list of Message...
All parameters are optional.
- 매개변수
limit (Optional[
int
]) – 검색할 메시지의 개수. 만약에None
이라면, 이 채널의 모든 메시지를 검색합니다. 그러나, 참고로, 그렇게 한다면 느리게 작동할 수 있습니다.before (Optional[Union[
Snowflake
,datetime.datetime
]]) – 이 시간이나 메시지 이전의 메시지들을 검색. 만약에 시간이라면 UTC 시간대인 timezone-naive datetime 이어야 합니다.after (Optional[Union[
Snowflake
,datetime.datetime
]]) – 이 시간이나 메시지 이후의 메시지들을 검색. 만약에 시간이라면 UTC 시간대인 timezone-naive datetime 이어야 합니다.around (Optional[Union[
Snowflake
,datetime.datetime
]]) – 이 시간이나 메시지 근처의 메시지들을 검색. 만약에 시간이라면 UTC 시간대인 timezone-naive datetime 이어야 합니다. 이 전달인자를 사용할 때에는, 최대 제한이 101 입니다. 참고로 제한이 짝수라면 제한 + 1개 메시지들을 반환합니다.oldest_first (Optional[
bool
]) – 만약에True
로 설정되었다면 메시지를 오래된->최신 순으로 반환합니다. 기본값은after
가 설정되있다면True
이고, 아니라면False
입니다.
- 예외
Forbidden – 채널 메시지 역사를 가져올 권한이 없습니다.
HTTPException – 메시지 역사 요청이 실패했습니다.
- Yields
Message
– 파싱된 메시지 데이터가 들어있는 메시지 객체
-
async with
typing
()¶ 제한되지 않은 시간동안 입력할 수 있도록 하는 컨텍스트 매니저를 반환.
이것은 봇이 오랫동안 계산 등을 할 때 유용합니다.
참고
이것은 평범한 컨텍스트 매니저이기도 하고 비동기 컨텍스트 매니저이기도 합니다. 이 말은
with
와async with
둘다 가능하다는 뜻입니다.예제:
async with channel.typing(): # do expensive stuff here await channel.send('done!')
-
await
invoke
(*args, **kwargs)¶ 이 함수는 코루틴 입니다.
주어진 인자들과 함께 명령어를 불러옵니다.
이것은 내부에서
Command
을 잡고 있는 콜백을 호출하고 싶다면 유용합니다.참고
이것은 어떤 일이 일어나도 컨버터, 체크, 쿨다운, 프리-인보크, 또는 애프터-인보크 후크들을 핸들링하지 않습니다.이것은 내부 콜백을 일반 함수처럼 직접 호출합니다.
이 함수를 사용할 때에는 제대로 된 인자들을 전달할 때 조심해야 합니다.
경고
첫번째로 전달된 인자는 무조건 실행된 명령어 이어야 합니다.
-
await
reinvoke
(*, call_hooks=False, restart=True)¶ 이 함수는 코루틴 입니다.
명령어를 다시 호출합니다.
이것은 체크, 쿨다운, 그리고 에러 핸들러들을 무시한다는 점을 뺀다면
invoke()
와 비슷합니다.참고
만약에
UserInputError
에서 파생된 예외를 무시하고 싶다면, 기본적인invoke()
를 사용하는 것을 추천하는데 더 자연스럽게 작동하기 때문입니다. 어쨌든, 이 함수는 유저가 기존에 사용했던 오래된 인자들을 재사용하게 될 것이고 결국 명령어 실행이 다시 실패할 것입니다.- 매개변수
- 예외
ValueError – 재실행할 컨텍스트가 잘못되었습니다.
-
channel
¶ TextChannel
: 이 컨텍스트의 명령어와 연관된 채널을 반환.Message.channel
을 단축한 것입니다.
Union[
User
,Member
]: 이 컨텍스트의 명령어와 연관된 메시지 작성자를 반환.Message.author
를 단축한 것입니다.
-
me
¶ Union[
Member
,ClientUser
]: 개인 메시지 컨텍스트일 경우ClientUser
를 반환할 수 있다는 점만 제외한다면Guild.me
와 비슷합니다.
-
voice_client
¶ 사용할 수 있다면
Guild.voice_client
의 단축입니다.- 타입
Optional[
VoiceProtocol
]
-
await
send_help
(entity=<bot>)¶ 이 함수는 코루틴 입니다.
만약에 주어졌다면 특정한 개체에 대한 도움말 명령어를 보여줍니다. 개체는 명령어나 cog일 수 있습니다.
만약에 개체가 주어지지 않았다면, 봇 전체에 대한 도움말을 보여줍니다.
만약에 개체가 문자열이라면,
Cog
인지Command
인지 확인합니다.참고
이 함수가 작동되는 방식 때문에
command_not_found()
와 같은 것을 반환하는 대신 입력이 잘못됬다거나 도움말 명령어가 없는 경우None
을 반환합니다.
-
await
reply
(content=None, **kwargs)¶ 이 함수는 코루틴 입니다.
A shortcut method to
abc.Messageable.send()
to reply to theMessage
.버전 1.6에 추가.
- 예외
HTTPException – 메시지 전송에 실패했습니다.
Forbidden – 메시지를 전송하기 위해 필요한 권한들이 없습니다.
InvalidArgument –
files
리스트가 적절한 크기가 아니거나file
과files
둘 다 사용되었습니다.
- 반환값
보내진 메시지.
- 반환 형식
Message
-
await
fetch_message
(id)¶ 이 함수는 코루틴 입니다.
목적지에서 단일
Message
를 갖고옵니다.이것은 봇 계정으로만 사용할 수 있습니다.
- 매개변수
id (
int
) – 찾아야 하는 메시지 ID.- 예외
NotFound – 특정 메시지를 찾을 수 없습니다.
Forbidden – 메시지를 갖고오기 위해 필요한 권한이 없습니다.
HTTPException – 메시지 검색에 실패했습니다.
- 반환값
찾으라고 한 메시지.
- 반환 형식
-
await
pins
()¶ 이 함수는 코루틴 입니다.
채널에 고정되어있는 모든 메시지들을 검색합니다.
참고
디스코드 API의 한계때문에, 이 함수로 반환된
Message
객체들은Message.reactions
데이터가 불완전하게 들어가있습니다.- 예외
HTTPException – 고정된 메시지 검색에 실패했습니다.
- 반환값
현재 고정되어있는 메시지들.
- 반환 형식
List[
Message
]
-
await
send
(content=None, *, tts=False, embed=None, file=None, files=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None)¶ 이 함수는 코루틴 입니다.
주어진 내용과 함께 목적지로 메시지를 보냅니다.
내용은
str(content)
를 통해 문자열로 전환될 수 있는 타입이어야 합니다. 만약에 내용이None
(기본값)으로 설정되어있다면,embed
매개 변수가 주어져야 합니다.단일 파일을 업로드하기 위해서는,
file
매개변수가 단일File
객체와 함께 사용되어야 합니다. 여러 파일들을 업로드하기 위해서는,files
매개변수가File
객체들이 들어있는list
와 함께 사용되어야 합니다. 두 매개변수를 동시에 사용하는 경우에는 예외가 발생하게 됩니다.만약
embed
매개변수가 주어졌다면Embed
타입이어야 하고 rich 임베드 타입이어야 합니다.- 매개변수
content (
str
) – 전송할 메시지의 내용.tts (
bool
) – 메시지가 TTS를 이용해서 보내야 할지의 여부.embed (
Embed
) – 내용의 rich 임베드.file (
File
) – 업로드 할 파일.files (List[
File
]) – 업로드 할 파일들의 리스트. 최대 개수는 10 입니다.nonce (
int
) – 이 메시지를 전송할 때 사용할 임시값. 만약에 메시지가 성공적으로 전송되었다면, 그 메시지는 이 값의 임시값을 가질 것입니다.delete_after (
float
) – 만약에 주어졌다면, 방금 전송한 메시지를 삭제하기 전 까지 백그라운드에서 기다려야 하는 초. 삭제가 실패되었다면, 조용히 무시됩니다.allowed_mentions (
AllowedMentions
) – 이 메시지에서 처리되는 맨션을 조정. 만약에 주어졌다면, 객체는allowed_mentions
와 합체됩니다. 합체되는 방식은 객체에 명시적으로 설정된 속성들만 오버라이드 하고, 명시되있지 않았다면allowed_mentions
에 설정된 속성들을 사용합니다. 만약 그 어떤 객체들도 전달되지 않았다면allowed_mentions
에 있는 기본값들을 사용합니다. .. versionadded:: 1.4reference (Union[
Message
,MessageReference
]) –A reference to the
Message
to which you are replying, this can be created usingto_reference()
or passed directly as aMessage
. You can control whether this mentions the author of the referenced message using thereplied_user
attribute ofallowed_mentions
or by settingmention_author
.버전 1.6에 추가.
mention_author (Optional[
bool
]) –If set, overrides the
replied_user
attribute ofallowed_mentions
.버전 1.6에 추가.
- 예외
HTTPException – 메시지 전송에 실패했습니다.
Forbidden – 메시지를 전송하기 위해 필요한 권한들이 없습니다.
InvalidArgument – The
files
list is not of the appropriate size, you specified bothfile
andfiles
, or thereference
object is not aMessage
orMessageReference
.
- 반환값
보내진 메시지.
- 반환 형식
-
Converters¶
-
class
discord.ext.commands.
Converter
¶ 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)¶ 이 함수는 코루틴 입니다.
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.- 매개변수
- 예외
CommandError – A generic exception occurred when converting the argument.
BadArgument – The converter failed to convert the argument.
-
await
-
class
discord.ext.commands.
MemberConverter
¶ 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):
Lookup by ID.
Lookup by mention.
Lookup by name#discrim
Lookup by name
Lookup by nickname
버전 1.5에서 변경: Raise
MemberNotFound
instead of genericBadArgument
버전 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)¶ 이 함수는 코루틴 입니다.
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.- 매개변수
- 예외
CommandError – A generic exception occurred when converting the argument.
BadArgument – The converter failed to convert the argument.
-
class
discord.ext.commands.
UserConverter
¶ Converts to a
User
.All lookups are via the global user cache.
The lookup strategy is as follows (in order):
Lookup by ID.
Lookup by mention.
Lookup by name#discrim
Lookup by name
버전 1.5에서 변경: Raise
UserNotFound
instead of genericBadArgument
버전 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)¶ 이 함수는 코루틴 입니다.
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.- 매개변수
- 예외
CommandError – A generic exception occurred when converting the argument.
BadArgument – The converter failed to convert the argument.
-
class
discord.ext.commands.
MessageConverter
¶ Converts to a
discord.Message
.버전 1.1에 추가.
The lookup strategy is as follows (in order):
Lookup by 《{channel ID}-{message ID}》 (retrieved by shift-clicking on 《Copy ID》)
Lookup by message ID (the message must be in the context channel)
Lookup by message URL
버전 1.5에서 변경: Raise
ChannelNotFound
,MessageNotFound
orChannelNotReadable
instead of genericBadArgument
-
await
convert
(ctx, argument)¶ 이 함수는 코루틴 입니다.
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.- 매개변수
- 예외
CommandError – A generic exception occurred when converting the argument.
BadArgument – The converter failed to convert the argument.
-
class
discord.ext.commands.
PartialMessageConverter
¶ Converts to a
discord.PartialMessage
.버전 1.7에 추가.
The creation strategy is as follows (in order):
By 《{channel ID}-{message ID}》 (retrieved by shift-clicking on 《Copy ID》)
By message ID (The message is assumed to be in the context channel.)
By message URL
-
await
convert
(ctx, argument)¶ 이 함수는 코루틴 입니다.
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.- 매개변수
- 예외
CommandError – A generic exception occurred when converting the argument.
BadArgument – The converter failed to convert the argument.
-
class
discord.ext.commands.
TextChannelConverter
¶ 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):
Lookup by ID.
Lookup by mention.
Lookup by name
버전 1.5에서 변경: Raise
ChannelNotFound
instead of genericBadArgument
-
await
convert
(ctx, argument)¶ 이 함수는 코루틴 입니다.
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.- 매개변수
- 예외
CommandError – A generic exception occurred when converting the argument.
BadArgument – The converter failed to convert the argument.
-
class
discord.ext.commands.
VoiceChannelConverter
¶ 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):
Lookup by ID.
Lookup by mention.
Lookup by name
버전 1.5에서 변경: Raise
ChannelNotFound
instead of genericBadArgument
-
await
convert
(ctx, argument)¶ 이 함수는 코루틴 입니다.
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.- 매개변수
- 예외
CommandError – A generic exception occurred when converting the argument.
BadArgument – The converter failed to convert the argument.
-
class
discord.ext.commands.
CategoryChannelConverter
¶ 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):
Lookup by ID.
Lookup by mention.
Lookup by name
버전 1.5에서 변경: Raise
ChannelNotFound
instead of genericBadArgument
-
await
convert
(ctx, argument)¶ 이 함수는 코루틴 입니다.
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.- 매개변수
- 예외
CommandError – A generic exception occurred when converting the argument.
BadArgument – The converter failed to convert the argument.
-
class
discord.ext.commands.
InviteConverter
¶ Converts to a
Invite
.This is done via an HTTP request using
Bot.fetch_invite()
.버전 1.5에서 변경: Raise
BadInviteArgument
instead of genericBadArgument
-
await
convert
(ctx, argument)¶ 이 함수는 코루틴 입니다.
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.- 매개변수
- 예외
CommandError – A generic exception occurred when converting the argument.
BadArgument – The converter failed to convert the argument.
-
await
-
class
discord.ext.commands.
GuildConverter
¶ Converts to a
Guild
.The lookup strategy is as follows (in order):
Lookup by ID.
Lookup by name. (There is no disambiguation for Guilds with multiple matching names).
버전 1.7에 추가.
-
await
convert
(ctx, argument)¶ 이 함수는 코루틴 입니다.
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.- 매개변수
- 예외
CommandError – A generic exception occurred when converting the argument.
BadArgument – The converter failed to convert the argument.
-
class
discord.ext.commands.
RoleConverter
¶ Converts to a
Role
.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):
Lookup by ID.
Lookup by mention.
Lookup by name
버전 1.5에서 변경: Raise
RoleNotFound
instead of genericBadArgument
-
await
convert
(ctx, argument)¶ 이 함수는 코루틴 입니다.
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.- 매개변수
- 예외
CommandError – A generic exception occurred when converting the argument.
BadArgument – The converter failed to convert the argument.
-
class
discord.ext.commands.
GameConverter
¶ Converts to
Game
.-
await
convert
(ctx, argument)¶ 이 함수는 코루틴 입니다.
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.- 매개변수
- 예외
CommandError – A generic exception occurred when converting the argument.
BadArgument – The converter failed to convert the argument.
-
await
-
class
discord.ext.commands.
ColourConverter
¶ 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
inColour
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 genericBadArgument
버전 1.7에서 변경: Added support for
rgb
function and 3-digit hex shortcuts-
await
convert
(ctx, argument)¶ 이 함수는 코루틴 입니다.
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.- 매개변수
- 예외
CommandError – A generic exception occurred when converting the argument.
BadArgument – The converter failed to convert the argument.
-
class
discord.ext.commands.
EmojiConverter
¶ Converts to a
Emoji
.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):
Lookup by ID.
Lookup by extracting ID from the emoji.
Lookup by name
버전 1.5에서 변경: Raise
EmojiNotFound
instead of genericBadArgument
-
await
convert
(ctx, argument)¶ 이 함수는 코루틴 입니다.
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.- 매개변수
- 예외
CommandError – A generic exception occurred when converting the argument.
BadArgument – The converter failed to convert the argument.
-
class
discord.ext.commands.
PartialEmojiConverter
¶ Converts to a
PartialEmoji
.This is done by extracting the animated flag, name and ID from the emoji.
버전 1.5에서 변경: Raise
PartialEmojiConversionFailure
instead of genericBadArgument
-
await
convert
(ctx, argument)¶ 이 함수는 코루틴 입니다.
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.- 매개변수
- 예외
CommandError – A generic exception occurred when converting the argument.
BadArgument – The converter failed to convert the argument.
-
await
-
class
discord.ext.commands.
clean_content
(*, fix_channel_mentions=False, use_nicknames=True, escape_markdown=False)¶ Converts the argument to mention scrubbed version of said content.
This behaves similarly to
clean_content
.-
await
convert
(ctx, argument)¶ 이 함수는 코루틴 입니다.
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.- 매개변수
- 예외
CommandError – A generic exception occurred when converting the argument.
BadArgument – The converter failed to convert the argument.
-
await
-
ext.commands.
Greedy
¶ 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 passnumbers
with[1, 2, 3, 4, 5, 6]
andreason
withhello
.For more information, check 특별한 변환기.
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.
-
-
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.
-
-
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
.
-
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
.
-
exception
discord.ext.commands.
ExpectedClosingQuoteError
(close_quote)¶ An exception raised when a quote character is expected but not found.
This inherits from
ArgumentParsingError
.
-
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.
-
converters
¶ A tuple of converters attempted in conversion, in order of failure.
- 타입
Tuple[Type, ..]
-
errors
¶ A list of errors that were caught from failing the conversion.
- 타입
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
-
exception
discord.ext.commands.
NoPrivateMessage
(message=None)¶ Exception raised when an operation does not work in private message contexts.
This inherits from
CheckFailure
-
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
.버전 1.3에 추가.
-
errors
¶ A list of errors that were caught during execution.
- 타입
List[
CheckFailure
]
-
-
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
-
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 toTrue
.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)¶ Exception raised when the command being invoked is on cooldown.
This inherits from
CommandError
-
cooldown
¶ A class with attributes
rate
,per
, andtype
similar to thecooldown()
decorator.- 타입
Cooldown
-
-
exception
discord.ext.commands.
MaxConcurrencyReached
(number, per)¶ Exception raised when the command being invoked has reached its maximum concurrency.
This inherits from
CommandError
.-
per
¶ The bucket type passed to the
max_concurrency()
decorator.- 타입
-
-
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
버전 1.5에 추가.
-
exception
discord.ext.commands.
MemberNotFound
(argument)¶ Exception raised when the member provided was not found in the bot’s cache.
This inherits from
BadArgument
버전 1.5에 추가.
-
exception
discord.ext.commands.
GuildNotFound
(argument)¶ Exception raised when the guild provided was not found in the bot’s cache.
This inherits from
BadArgument
버전 1.7에 추가.
-
exception
discord.ext.commands.
UserNotFound
(argument)¶ Exception raised when the user provided was not found in the bot’s cache.
This inherits from
BadArgument
버전 1.5에 추가.
-
exception
discord.ext.commands.
ChannelNotFound
(argument)¶ Exception raised when the bot can not find the channel.
This inherits from
BadArgument
버전 1.5에 추가.
-
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
버전 1.5에 추가.
-
argument
¶ The channel supplied by the caller that was not readable
-
-
exception
discord.ext.commands.
BadColourArgument
(argument)¶ Exception raised when the colour is not valid.
This inherits from
BadArgument
버전 1.5에 추가.
-
exception
discord.ext.commands.
RoleNotFound
(argument)¶ Exception raised when the bot can not find the role.
This inherits from
BadArgument
버전 1.5에 추가.
-
exception
discord.ext.commands.
BadInviteArgument
¶ Exception raised when the invite is invalid or expired.
This inherits from
BadArgument
버전 1.5에 추가.
-
exception
discord.ext.commands.
EmojiNotFound
(argument)¶ Exception raised when the bot can not find the emoji.
This inherits from
BadArgument
버전 1.5에 추가.
-
exception
discord.ext.commands.
PartialEmojiConversionFailure
(argument)¶ Exception raised when the emoji provided does not match the correct format.
This inherits from
BadArgument
버전 1.5에 추가.
-
exception
discord.ext.commands.
BadBoolArgument
(argument)¶ Exception raised when a boolean argument was not convertable.
This inherits from
BadArgument
버전 1.5에 추가.
-
exception
discord.ext.commands.
MissingPermissions
(missing_perms, *args)¶ Exception raised when the command invoker lacks permissions to run a command.
This inherits from
CheckFailure
-
exception
discord.ext.commands.
BotMissingPermissions
(missing_perms, *args)¶ Exception raised when the bot’s member lacks permissions to run a command.
This inherits from
CheckFailure
-
exception
discord.ext.commands.
MissingRole
(missing_role)¶ Exception raised when the command invoker lacks a role to run a command.
This inherits from
CheckFailure
버전 1.1에 추가.
-
missing_role
¶ The required role that is missing. This is the parameter passed to
has_role()
.
-
-
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
버전 1.1에 추가.
-
missing_role
¶ The required role that is missing. This is the parameter passed to
has_role()
.
-
-
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
버전 1.1에 추가.
-
missing_roles
¶ The roles that the invoker is missing. These are the parameters passed to
has_any_role()
.
-
-
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
버전 1.1에 추가.
-
missing_roles
¶ The roles that the bot’s member is missing. These are the parameters passed to
has_any_role()
.
-
-
exception
discord.ext.commands.
NSFWChannelRequired
(channel)¶ Exception raised when a channel does not have the required NSFW setting.
This inherits from
CheckFailure
.버전 1.1에 추가.
- 매개변수
channel (
discord.abc.GuildChannel
) – The channel that does not have NSFW enabled.
-
exception
discord.ext.commands.
ExtensionError
(message=None, *args, name)¶ Base exception for extension related errors.
This inherits from
DiscordException
.
-
exception
discord.ext.commands.
ExtensionAlreadyLoaded
(name)¶ An exception raised when an extension has already been loaded.
This inherits from
ExtensionError
-
exception
discord.ext.commands.
ExtensionNotLoaded
(name)¶ An exception raised when an extension was not loaded.
This inherits from
ExtensionError
-
exception
discord.ext.commands.
NoEntryPointError
(name)¶ An exception raised when an extension does not have a
setup
entry point function.This inherits from
ExtensionError
-
exception
discord.ext.commands.
ExtensionFailed
(name, original)¶ An exception raised when an extension failed to load during execution of the module or
setup
entry point.This inherits from
ExtensionError
-
exception
discord.ext.commands.
ExtensionNotFound
(name, original=None)¶ An exception raised when an extension is not found.
This inherits from
ExtensionError
버전 1.3에서 변경: Made the
original
attribute always None.-
original
¶ Always
None
for backwards compatibility.- 타입
NoneType
-
-
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
버전 1.4에 추가.