명령어¶
명령어 확장자에서 가장 매력적인 것은 명령어를 정의하는 것이 매우 쉽고 당신 마음대로 그룹과 명령어를 묶어서 풍부한 서브커맨드 시스템을 가질 수 있다는 것입니다.
명령어는 기본적인 Python 함수에 붙여서 정의됩니다. 그다음에 유저가 Python 함수처럼 비슷한 서명을 사용해서 실행됩니다.
예를 들면, 주어진 명령어 정의에서:
@bot.command()
async def foo(ctx, arg):
await ctx.send(arg)
프리픽스로 ($
) 를 갖고 있을 때, 이 명령어는 이렇게 유저에 의해 실행됩니다:
$foo abc
명령어는 항상 매개변수로 처음에 Context
인 ctx
를 갖고 있어야 합니다.
명령어를 등록하는 방법은 두가지가 있습니다. 첫번째는 위의 예시처럼 Bot.command()
데코레이터를 사용하는 것입니다. 두번째는 인스턴스에서 Bot.add_command()
다음에 오는 command()
데코레이터를 사용하는 것입니다.
기본적으로는, 이 둘은 같습니다:
from discord.ext import commands
bot = commands.Bot(command_prefix='$')
@bot.command()
async def test(ctx):
pass
# or:
@commands.command()
async def test(ctx):
pass
bot.add_command(test)
Bot.command()
데코레이터가 더 짧고 이해하기 더 쉽기 때문에 이 문서에서 사용될 것입니다.
Command
생성자에 의해 받아들여진 매개변수는 데코레이터로 들어갈 수 있습니다. 예를 들어서, 함수 이외의 이름으로 변경하는 것은 이렇게 하는 것처럼 간단합니다:
@bot.command(name='list')
async def _list(ctx, arg):
pass
매개변수¶
우리는 명령어를 Python 함수를 만드는 것으로 정의하고 있기 때문에, 우리는 지나가는 전달인자도 함수 매개변수로 정의합니다.
특정 매개변수 종류는 유저쪽에서 다른 것을 하고 대부분의 매개변수 형태는 지원됩니다.
위치¶
The most basic form of parameter passing is the positional parameter. This is where we pass a parameter as-is:
@bot.command()
async def test(ctx, arg):
await ctx.send(arg)
On the bot using side, you can provide positional arguments by just passing a regular string:
To make use of a word with spaces in between, you should quote it:
As a note of warning, if you omit the quotes, you will only get the first word:
Since positional arguments are just regular Python arguments, you can have as many as you want:
@bot.command()
async def test(ctx, arg1, arg2):
await ctx.send('You passed {} and {}'.format(arg1, arg2))
변수¶
Sometimes you want users to pass in an undetermined number of parameters. The library supports this similar to how variable list parameters are done in Python:
@bot.command()
async def test(ctx, *args):
await ctx.send('{} arguments: {}'.format(len(args), ', '.join(args)))
This allows our user to accept either one or many arguments as they please. This works similar to positional arguments, so multi-word parameters should be quoted.
For example, on the bot side:
If the user wants to input a multi-word argument, they have to quote it like earlier:
Do note that similar to the Python function behaviour, a user can technically pass no arguments at all:
Since the args
variable is a tuple
,
you can do anything you would usually do with one.
키워드 전용 전달인자¶
When you want to handle parsing of the argument yourself or do not feel like you want to wrap multi-word user input into quotes, you can ask the library to give you the rest as a single argument. We do this by using a keyword-only argument, seen below:
@bot.command()
async def test(ctx, *, arg):
await ctx.send(arg)
경고
You can only have one keyword-only argument due to parsing ambiguities.
On the bot side, we do not need to quote input with spaces:
Do keep in mind that wrapping it in quotes leaves it as-is:
By default, the keyword-only arguments are stripped of white space to make it easier to work with. This behaviour can be
toggled by the Command.rest_is_raw
argument in the decorator.
Invocation Context¶
As seen earlier, every command must take at least a single parameter, called the Context
.
This parameter gives you access to something called the 《invocation context》. Essentially all the information you need to know how the command was executed. It contains a lot of useful information:
Context.guild
to fetch theGuild
of the command, if any.Context.message
to fetch theMessage
of the command.Context.author
to fetch theMember
orUser
that called the command.Context.send()
to send a message to the channel the command was used in.
The context implements the abc.Messageable
interface, so anything you can do on a abc.Messageable
you
can do on the Context
.
Converters¶
Adding bot arguments with function parameters is only the first step in defining your bot’s command interface. To actually make use of the arguments, we usually want to convert the data into a target type. We call these Converters.
Converters come in a few flavours:
A regular callable object that takes an argument as a sole parameter and returns a different type.
A custom class that inherits from
Converter
.
Basic Converters¶
At its core, a basic converter is a callable that takes in an argument and turns it into something else.
For example, if we wanted to add two numbers together, we could request that they are turned into integers for us by specifying the converter:
@bot.command()
async def add(ctx, a: int, b: int):
await ctx.send(a + b)
We specify converters by using something called a function annotation. This is a Python 3 exclusive feature that was introduced in PEP 3107.
This works with any callable, such as a function that would convert a string to all upper-case:
def to_upper(argument):
return argument.upper()
@bot.command()
async def up(ctx, *, content: to_upper):
await ctx.send(content)
bool¶
Unlike the other basic converters, the bool
converter is treated slightly different. Instead of casting directly to the bool
type, which would result in any non-empty argument returning True
, it instead evaluates the argument as True
or False
based on its given content:
if lowered in ('yes', 'y', 'true', 't', '1', 'enable', 'on'):
return True
elif lowered in ('no', 'n', 'false', 'f', '0', 'disable', 'off'):
return False
Advanced Converters¶
Sometimes a basic converter doesn’t have enough information that we need. For example, sometimes we want to get some
information from the Message
that called the command or we want to do some asynchronous processing.
For this, the library provides the Converter
interface. This allows you to have access to the
Context
and have the callable be asynchronous. Defining a custom converter using this interface requires
overriding a single method, Converter.convert()
.
An example converter:
import random
class Slapper(commands.Converter):
async def convert(self, ctx, argument):
to_slap = random.choice(ctx.guild.members)
return '{0.author} slapped {1} because *{2}*'.format(ctx, to_slap, argument)
@bot.command()
async def slap(ctx, *, reason: Slapper):
await ctx.send(reason)
The converter provided can either be constructed or not. Essentially these two are equivalent:
@bot.command()
async def slap(ctx, *, reason: Slapper):
await ctx.send(reason)
# is the same as...
@bot.command()
async def slap(ctx, *, reason: Slapper()):
await ctx.send(reason)
Having the possibility of the converter be constructed allows you to set up some state in the converter’s __init__
for
fine tuning the converter. An example of this is actually in the library, clean_content
.
@bot.command()
async def clean(ctx, *, content: commands.clean_content):
await ctx.send(content)
# or for fine-tuning
@bot.command()
async def clean(ctx, *, content: commands.clean_content(use_nicknames=False)):
await ctx.send(content)
If a converter fails to convert an argument to its designated target type, the BadArgument
exception must be
raised.
Inline Advanced Converters¶
If we don’t want to inherit from Converter
, we can still provide a converter that has the
advanced functionalities of an advanced converter and save us from specifying two types.
For example, a common idiom would be to have a class and a converter for that class:
class JoinDistance:
def __init__(self, joined, created):
self.joined = joined
self.created = created
@property
def delta(self):
return self.joined - self.created
class JoinDistanceConverter(commands.MemberConverter):
async def convert(self, ctx, argument):
member = await super().convert(ctx, argument)
return JoinDistance(member.joined_at, member.created_at)
@bot.command()
async def delta(ctx, *, member: JoinDistanceConverter):
is_new = member.delta.days < 100
if is_new:
await ctx.send("Hey you're pretty new!")
else:
await ctx.send("Hm you're not so new.")
This can get tedious, so an inline advanced converter is possible through a classmethod
inside the type:
class JoinDistance:
def __init__(self, joined, created):
self.joined = joined
self.created = created
@classmethod
async def convert(cls, ctx, argument):
member = await commands.MemberConverter().convert(ctx, argument)
return cls(member.joined_at, member.created_at)
@property
def delta(self):
return self.joined - self.created
@bot.command()
async def delta(ctx, *, member: JoinDistance):
is_new = member.delta.days < 100
if is_new:
await ctx.send("Hey you're pretty new!")
else:
await ctx.send("Hm you're not so new.")
Discord Converters¶
Working with 디스코드 모델 is a fairly common thing when defining commands, as a result the library makes working with them easy.
For example, to receive a Member
you can just pass it as a converter:
@bot.command()
async def joined(ctx, *, member: discord.Member):
await ctx.send('{0} joined on {0.joined_at}'.format(member))
When this command is executed, it attempts to convert the string given into a Member
and then passes it as a
parameter for the function. This works by checking if the string is a mention, an ID, a nickname, a username + discriminator,
or just a regular username. The default set of converters have been written to be as easy to use as possible.
A lot of discord models work out of the gate as a parameter:
Message
(v1.1 부터)PartialMessage
(since v1.7)
Having any of these set as the converter will intelligently convert the argument to the appropriate target type you specify.
Under the hood, these are implemented by the Advanced Converters interface. A table of the equivalent converter is given below:
디스코드 클래스 |
변환기 |
|
|
By providing the converter it allows us to use them as building blocks for another converter:
class MemberRoles(commands.MemberConverter):
async def convert(self, ctx, argument):
member = await super().convert(ctx, argument)
return [role.name for role in member.roles[1:]] # Remove everyone role!
@bot.command()
async def roles(ctx, *, member: MemberRoles):
"""Tells you a member's roles."""
await ctx.send('I see the following roles: ' + ', '.join(member))
특별한 변환기¶
The command extension also has support for certain converters to allow for more advanced and intricate use cases that go beyond the generic linear parsing. These converters allow you to introduce some more relaxed and dynamic grammar to your commands in an easy to use manner.
typing.Union¶
A typing.Union
is a special type hint that allows for the command to take in any of the specific types instead of
a singular type. For example, given the following:
import typing
@bot.command()
async def union(ctx, what: typing.Union[discord.TextChannel, discord.Member]):
await ctx.send(what)
The what
parameter would either take a discord.TextChannel
converter or a discord.Member
converter.
The way this works is through a left-to-right order. It first attempts to convert the input to a
discord.TextChannel
, and if it fails it tries to convert it to a discord.Member
. If all converters fail,
then a special error is raised, BadUnionArgument
.
Note that any valid converter discussed above can be passed in to the argument list of a typing.Union
.
typing.Optional¶
A typing.Optional
is a special type hint that allows for 《back-referencing》 behaviour. If the converter fails to
parse into the specified type, the parser will skip the parameter and then either None
or the specified default will be
passed into the parameter instead. The parser will then continue on to the next parameters and converters, if any.
Consider the following example:
import typing
@bot.command()
async def bottles(ctx, amount: typing.Optional[int] = 99, *, liquid="beer"):
await ctx.send('{} bottles of {} on the wall!'.format(amount, liquid))
In this example, since the argument could not be converted into an int
, the default of 99
is passed and the parser
resumes handling, which in this case would be to pass it into the liquid
parameter.
참고
This converter only works in regular positional parameters, not variable parameters or keyword-only parameters.
Greedy¶
The Greedy
converter is a generalisation of the typing.Optional
converter, except applied
to a list of arguments. In simple terms, this means that it tries to convert as much as it can until it can’t convert
any further.
Consider the following example:
@bot.command()
async def slap(ctx, members: commands.Greedy[discord.Member], *, reason='no reason'):
slapped = ", ".join(x.name for x in members)
await ctx.send('{} just got slapped for {}'.format(slapped, reason))
When invoked, it allows for any number of members to be passed in:
The type passed when using this converter depends on the parameter type that it is being attached to:
Positional parameter types will receive either the default parameter or a
list
of the converted values.Variable parameter types will be a
tuple
as usual.Keyword-only parameter types will be the same as if
Greedy
was not passed at all.
Greedy
parameters can also be made optional by specifying an optional value.
When mixed with the typing.Optional
converter you can provide simple and expressive command invocation syntaxes:
import typing
@bot.command()
async def ban(ctx, members: commands.Greedy[discord.Member],
delete_days: typing.Optional[int] = 0, *,
reason: str):
"""Mass bans members with an optional delete_days parameter"""
for member in members:
await member.ban(delete_message_days=delete_days, reason=reason)
This command can be invoked any of the following ways:
$ban @Member @Member2 spam bot
$ban @Member @Member2 7 spam bot
$ban @Member spam
경고
The usage of Greedy
and typing.Optional
are powerful and useful, however as a
price, they open you up to some parsing ambiguities that might surprise some people.
For example, a signature expecting a typing.Optional
of a discord.Member
followed by a
int
could catch a member named after a number due to the different ways a
MemberConverter
decides to fetch members. You should take care to not introduce
unintended parsing ambiguities in your code. One technique would be to clamp down the expected syntaxes
allowed through custom converters or reordering the parameters to minimise clashes.
To help aid with some parsing ambiguities, str
, None
, typing.Optional
and
Greedy
are forbidden as parameters for the Greedy
converter.
에러 다루기¶
When our commands fail to parse we will, by default, receive a noisy error in stderr
of our console that tells us
that an error has happened and has been silently ignored.
In order to handle our errors, we must use something called an error handler. There is a global error handler, called
on_command_error()
which works like any other event in the Event Reference. This global error handler is
called for every error reached.
Most of the time however, we want to handle an error local to the command itself. Luckily, commands come with local error
handlers that allow us to do just that. First we decorate an error handler function with Command.error()
:
@bot.command()
async def info(ctx, *, member: discord.Member):
"""Tells you some info about the member."""
fmt = '{0} joined on {0.joined_at} and has {1} roles.'
await ctx.send(fmt.format(member, len(member.roles)))
@info.error
async def info_error(ctx, error):
if isinstance(error, commands.BadArgument):
await ctx.send('I could not find that member...')
The first parameter of the error handler is the Context
while the second one is an exception that is derived from
CommandError
. A list of errors is found in the Exceptions page of the documentation.
체크¶
우리가 유저들이 전용 명령어를 사용하지 못하게 막고 싶을 때가 있습니다. 그들에게 권한이 없거나 우리가 그들이 봇을 사용하지 못하도록 막았었을 수도 있습니다. 명령어 확장자는 이것들을 위한 완전한 지원이 Checks로 함께 옵니다.
체크는 Context
에서 단독 매개 변수로 자리잡는 기본적인 서술자입니다. 이 안에서, 당신에게는 이런 옵션들이 있습니다:
이 사람이 명령어를 사용할 수 있다고
True
를 시그널에 반환.이 사람이 명령어를 사용할 수 없다고
False
를 시그널에 반환.이 사람이 명령어를 사용할 수 없다고
CommandError
예외를 일으키기.이는 당신이 error handlers를 다루기 위해 당신만을 위한 커스텀 오류 메시지를 만들 수 있게 합니다.
명령어에 체크를 등록하기 위해, 우리는 2가지 방법으로 할 수 있습니다. 첫번째 방법은 check()
데코레이터를 사용하는 것입니다. 예를 들어:
async def is_owner(ctx):
return ctx.author.id == 316026178463072268
@bot.command(name='eval')
@commands.check(is_owner)
async def _eval(ctx, *, code):
"""A bad example of an eval command"""
await ctx.send(eval(code))
This would only evaluate the command if the function is_owner
returns True
. Sometimes we re-use a check often and
want to split it into its own decorator. To do that we can just add another level of depth:
def is_owner():
async def predicate(ctx):
return ctx.author.id == 316026178463072268
return commands.check(predicate)
@bot.command(name='eval')
@is_owner()
async def _eval(ctx, *, code):
"""A bad example of an eval command"""
await ctx.send(eval(code))
Since an owner check is so common, the library provides it for you (is_owner()
):
@bot.command(name='eval')
@commands.is_owner()
async def _eval(ctx, *, code):
"""A bad example of an eval command"""
await ctx.send(eval(code))
When multiple checks are specified, all of them must be True
:
def is_in_guild(guild_id):
async def predicate(ctx):
return ctx.guild and ctx.guild.id == guild_id
return commands.check(predicate)
@bot.command()
@commands.is_owner()
@is_in_guild(41771983423143937)
async def secretguilddata(ctx):
"""super secret stuff"""
await ctx.send('secret stuff')
If any of those checks fail in the example above, then the command will not be run.
When an error happens, the error is propagated to the error handlers. If you do not
raise a custom CommandError
derived exception, then it will get wrapped up into a
CheckFailure
exception as so:
@bot.command()
@commands.is_owner()
@is_in_guild(41771983423143937)
async def secretguilddata(ctx):
"""super secret stuff"""
await ctx.send('secret stuff')
@secretguilddata.error
async def secretguilddata_error(ctx, error):
if isinstance(error, commands.CheckFailure):
await ctx.send('nothing to see here comrade.')
If you want a more robust error system, you can derive from the exception and raise it instead of returning False
:
class NoPrivateMessages(commands.CheckFailure):
pass
def guild_only():
async def predicate(ctx):
if ctx.guild is None:
raise NoPrivateMessages('Hey no DMs!')
return True
return commands.check(predicate)
@guild_only()
async def test(ctx):
await ctx.send('Hey this is not a DM! Nice.')
@test.error
async def test_error(ctx, error):
if isinstance(error, NoPrivateMessages):
await ctx.send(error)
참고
Since having a guild_only
decorator is pretty common, it comes built-in via guild_only()
.
글로벌 체크¶
가끔 우리는 특정 명령어 말고 모든 명령어에 체크를 적용하고 싶을때가 있습니다. 이 라이브러리는 글로벌 체크를 통해 이 기능을 지원합니다.
Global checks work similarly to regular checks except they are registered with the Bot.check()
decorator.
예를 들면, 모든 DM을 막기 위해 이렇게 할 수도 있습니다:
@bot.check
async def globally_block_dms(ctx):
return ctx.guild is not None
경고
당신이 당신의 봇을 사용 못하도록 만들 수도 있기 때문에 글로벌 체크를 작성할 때는 조심하세요.