Commands¶
One of the most appealing aspects of the command extension is how easy it is to define commands and how you can arbitrarily nest groups and commands to have a rich sub-command system.
Commands are defined by attaching it to a regular Python function. The command is then invoked by the user using a similar signature to the Python function.
You must have access to the message_content intent for the commands extension to function. This must be set both in the developer portal and within your code.
Failure to do this will result in your bot not responding to any of your commands.
For example, in the given command definition:
With the following prefix ( $ ), it would be invoked by the user via:
A command must always have at least one parameter, ctx , which is the Context as the first one.
There are two ways of registering a command. The first one is by using Bot.command() decorator, as seen in the example above. The second is using the command() decorator followed by Bot.add_command() on the instance.
Essentially, these two are equivalent:
Since the Bot.command() decorator is shorter and easier to comprehend, it will be the one used throughout the documentation here.
Any parameter that is accepted by the Command constructor can be passed into the decorator. For example, to change the name to something other than the function would be as simple as doing this:
Parameters¶
Since we define commands by making Python functions, we also define the argument passing behaviour by the function parameters.
Certain parameter types do different things in the user side and most forms of parameter types are supported.
Positional¶
The most basic form of parameter passing is the positional parameter. This is where we pass a parameter as-is:
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:
Variable¶
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:
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.
Keyword-Only Arguments¶
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:
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 returns the Guild of the command, if any.
Context.message returns the Message of the command.
Context.author returns the Member or User 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.
-
These range from your own function, to something like bool or int .
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:
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:
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:
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:
The converter provided can either be constructed or not. Essentially these two are equivalent:
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 .
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:
This can get tedious, so an inline advanced converter is possible through a classmethod() inside the type:
Discord Converters¶
Working with Discord Models 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:
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:
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:
Special Converters¶
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:
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:
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.
typing.Literal¶
New in version 2.0.
A typing.Literal is a special type hint that requires the passed parameter to be equal to one of the listed values after being converted to the same type. For example, given the following:
The buy_sell parameter must be either the literal string "buy" or "sell" and amount must convert to the int 1 or 2 . If buy_sell or amount don’t match any value, then a special error is raised, BadLiteralArgument . Any literal values can be mixed and matched within the same typing.Literal converter.
Note that typing.Literal[True] and typing.Literal[False] still follow the bool converter rules.
typing.Annotated¶
New in version 2.0.
A typing.Annotated is a special type introduced in Python 3.9 that allows the type checker to see one type, but allows the library to see another type. This is useful for appeasing the type checker for complicated converters. The second parameter of Annotated must be the converter that the library should use.
For example, given the following:
The type checker will see arg as a regular str but the library will know you wanted to change the input into all upper-case.
For Python versions below 3.9, it is recommended to install the typing_extensions library and import Annotated from there.
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:
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:
This command can be invoked any of the following ways:
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.
discord.Attachment¶
New in version 2.0.
The discord.Attachment converter is a special converter that retrieves an attachment from the uploaded attachments on a message. This converter does not look at the message content at all and just the uploaded attachments.
Consider the following example:
When this command is invoked, the user must directly upload a file for the command body to be executed. When combined with the typing.Optional converter, the user does not have to provide an attachment.
This also works with multiple attachments:
In this example the user must provide at least one file but the second one is optional.
As a special case, using Greedy will return the remaining attachments in the message, if any.
Note that using a discord.Attachment converter after a Greedy of discord.Attachment will always fail since the greedy had already consumed the remaining attachments.
If an attachment is expected but not given, then MissingRequiredAttachment is raised to the error handlers.
FlagConverter¶
New in version 2.0.
A FlagConverter allows the user to specify user-friendly “flags” using PEP 526 type annotations or a syntax more reminiscent of the dataclasses module.
For example, the following code:
Allows the user to invoke the command using a simple flag-like syntax:
Flags use a syntax that allows the user to not require quotes when passing in values to the flag. The goal of the flag syntax is to be as user-friendly as possible. This makes flags a good choice for complicated commands that can have multiple knobs to turn or simulating keyword-only parameters in your external command interface. It is recommended to use keyword-only parameters with the flag converter. This ensures proper parsing and behaviour with quoting.
Internally, the FlagConverter class examines the class to find flags. A flag can either be a class variable with a type annotation or a class variable that’s been assigned the result of the flag() function. These flags are then used to define the interface that your users will use. The annotations correspond to the converters that the flag arguments must adhere to.
For most use cases, no extra work is required to define flags. However, if customisation is needed to control the flag name or the default value then the flag() function can come in handy:
This tells the parser that the members attribute is mapped to a flag named member and that the default value is an empty list. For greater customisability, the default can either be a value or a callable that takes the Context as a sole parameter. This callable can either be a function or a coroutine.
In order to customise the flag syntax we also have a few options that can be passed to the class parameter list:
Despite the similarities in these examples to command like arguments, the syntax and parser is not a command line parser. The syntax is mainly inspired by Discord’s search bar input and as a result all flags need a corresponding value.
Flag converters will only raise FlagError derived exceptions. If an error is raised while converting a flag, BadFlagArgument is raised instead and the original exception can be accessed with the original attribute.
The flag converter is similar to regular commands and allows you to use most types of converters (with the exception of Greedy ) as the type annotation. Some extra support is added for specific annotations as described below.
typing.List¶
If a list is given as a flag annotation it tells the parser that the argument can be passed multiple times.
For example, augmenting the example above:
This is called by repeatedly specifying the flag:
typing.Tuple¶
Since the above syntax can be a bit repetitive when specifying a flag many times, the tuple type annotation allows for “greedy-like” semantics using a variadic tuple:
This allows the previous ban command to be called like this:
The tuple annotation also allows for parsing of pairs. For example, given the following code:
Due to potential parsing ambiguities, the parser expects tuple arguments to be quoted if they require spaces. So if one of the inner types is str and the argument requires spaces then quotes should be used to disambiguate it from the other element of the tuple.
typing.Dict¶
A dict annotation is functionally equivalent to List[Tuple[K, V]] except with the return type given as a dict rather than a list .
Hybrid Command Interaction¶
When used as a hybrid command, the parameters are flattened into different parameters for the application command. For example, the following converter:
Would be equivalent to an application command defined as this:
This means that decorators that refer to a parameter by name will use the flag name instead:
For ease of use, the flag() function accepts a description keyword argument to allow you to pass descriptions inline:
Likewise, use of the name keyword argument allows you to pass renames for the parameter, similar to the rename() decorator.
Note that in hybrid command form, a few annotations are unsupported due to Discord limitations:
Only one flag converter is supported per hybrid command. Due to the flag converter’s way of working, it is unlikely for a user to have two of them in one signature.
Parameter Metadata¶
parameter() assigns custom metadata to a Command ’s parameter.
This is useful for:
Custom converters as annotating a parameter with a custom converter works at runtime, type checkers don’t like it because they can’t understand what’s going on.
However, fear not we can use parameter() to tell type checkers what’s going on.
Late binding behaviour
Because this is such a common use-case, the library provides Author , CurrentChannel and CurrentGuild , armed with this we can simplify wave to:
Author and co also have other benefits like having the displayed default being filled.
Error Handling¶
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 error() :
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¶
There are cases when we don’t want a user to use our commands. They don’t have permissions to do so or maybe we blocked them from using our bot earlier. The commands extension comes with full support for these things in a concept called a Checks .
A check is a basic predicate that can take in a Context as its sole parameter. Within it, you have the following options:
Return True to signal that the person can run the command.
Return False to signal that the person cannot run the command.
Raise a CommandError derived exception to signal the person cannot run the command.
-
This allows you to have custom error messages for you to handle in the error handlers .
To register a check for a command, we would have two ways of doing so. The first is using the check() decorator. For example:
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:
Since an owner check is so common, the library provides it for you ( is_owner() ):
When multiple checks are specified, all of them must be True :
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:
If you want a more robust error system, you can derive from the exception and raise it instead of returning False :
Since having a guild_only decorator is pretty common, it comes built-in via guild_only() .
Global Checks¶
Sometimes we want to apply a check to every command, not just certain commands. The library supports this as well using the global check concept.
Global checks work similarly to regular checks except they are registered with the Bot.check() decorator.
For example, to block all DMs we could do the following:
Be careful on how you write your global checks, as it could also lock you out of your own bot.
Hybrid Commands¶
New in version 2.0.
commands.HybridCommand is a command that can be invoked as both a text and a slash command. This allows you to define a command as both slash and text command without writing separate code for both counterparts.
In order to define a hybrid command, The command callback should be decorated with Bot.hybrid_command() decorator.
The above command can be invoked as both text and slash command. Note that you have to manually sync your CommandTree by calling sync in order for slash commands to appear.
You can create hybrid command groups and sub-commands using the Bot.hybrid_group() decorator.
Due to a Discord limitation, slash command groups cannot be invoked directly so the fallback parameter allows you to create a sub-command that will be bound to callback of parent group.
Due to certain limitations on slash commands, some features of text commands are not supported on hybrid commands. You can define a hybrid command as long as it meets the same subset that is supported for slash commands.
Following are currently not supported by hybrid commands:
Variable number of arguments. e.g. *arg: int
Group commands with a depth greater than 1.
Unions of channel types are allowed
Unions of user types are allowed
Unions of user types with roles are allowed
Apart from that, all other features such as converters, checks, autocomplete, flags etc. are supported on hybrid commands. Note that due to a design constraint, decorators related to application commands such as discord.app_commands.autocomplete() should be placed below the hybrid_command() decorator.
For convenience and ease in writing code, The Context class implements some behavioural changes for various methods and attributes:
Остановка бота discord.py
Стоит задача: нужно при запуске программы запускать бота discord, генерировать ссылку-приглашение и останавливать бота.
Есть ли стандартные (валидные) методы остановки бота? В API Reference найти его не удалось =/
Упрощённый пример бота:
Попробуй такой вариант:
Дизайн сайта / логотип © 2023 Stack Exchange Inc; пользовательские материалы лицензированы в соответствии с CC BY-SA . rev 2023.6.8.43486
Нажимая «Принять все файлы cookie» вы соглашаетесь, что Stack Exchange может хранить файлы cookie на вашем устройстве и раскрывать информацию в соответствии с нашей Политикой в отношении файлов cookie.
Как в discord.py сделать функцию shutdown?
Если допустить, что ваш сервер линуксовый, и он при завершении работы вызывает необходимые сигналы — ловить эти самые сигналы.
https://docs.python.org/3/library/asyncio-eventloo. (достать eventloop бота можно через bot.loop)
- Вконтакте
- Вконтакте
Если речь об остановке программы, то гипотетически может пригодиться модуль atexit.
Но нужно иметь ввиду, что этот модуль не поможет если процесс убит сигналом KILL (Unix системы) или через TerminateProcess() (Windows системы).
Кроме того, нет гарантий, что после вызова atexit-обработчика бот проживёт достаточно долго, чтобы на самом деле отправить сообщение по сети, а не только «принять к сведению и поставить в очередь».
Так что скорее стоит задуматься, что именно вы пытаетесь сделать, и зачем.
Как остановить запуск процесса бота Discord (Python)
Я новичок в этой штуке с discord.py. Я только что сделал бота discord.py, он работает нормально, но иногда бот постоянно повторяет командные сообщения. Я погуглил эту проблему и обнаружил, что, возможно, для запуска скрипта снова и снова (например, когда вы сохраняете и запускаете после редактирования или добавления функций). Поэтому я хочу прекратить запуск процесса, точно так же, как когда я перезапускаю окна, бот отключен (если я запускаю скрипт после перезапуска Windows, бот работает нормально). Пожалуйста, помогите
Если кому-то нужен код, то я могу вставить его сюда.
PD: Я сделал бота точным в качестве учебника.
5 ответов
- Если вы добавите код, который я написал там (который может использовать только владелец), отключит уже запущенных ботов (запись / завершение работы на сервере Discord или независимо от вашего префикса).
Однако вам может потребоваться перезагрузка ПК после сохранения бота с этим кодом.
- Поэтому каждый раз, если вы хотите отредактировать свою команду, вы пишете / завершаете работу и редактируете ее, после этого вы можете запускать ее снова.
Я надеюсь, что это сработает для вас, и я смогу помочь.
Способ завершить весь скрипт, на котором работает ваш бот, — использовать встроенные функции Python. exit() и quit() оба делают одно и то же.
поставив @commands.is_owner() вы делаете так, что только владелец бота может использовать эту команду. Чтобы вызвать этот тип команды /shutdown на вашем дискорд сервере (замените / с любым вашим префиксом).
Он вызывает кучу ошибок, но в целом завершает программу, поэтому, возможно, это не самый эффективный метод, но он выполняет свою работу.
Это сообщение действительно не является специфическим для discord.py и применяется ко всем скриптам, которые выполняются бесконечно.
Вы запускаете несколько экземпляров своего бота. Если вы запустите его в среде IDE, то где-то должна быть кнопка остановки. Если вы запускаете его в консоли, закрытие окна консоли закроет бот.
Изменить: если вы запускаете его в sublime3, как предлагают ваши теги, каждый раз, когда вы хотите закрыть своего бота, переходите в «Инструменты», а затем «Отменить сборку» (горячая клавиша: CTRL + Break). Как только вы запускаете другой экземпляр своего бота, sublime «отделяет» текущий скрипт от нового, и этот метод больше не работает. Затем вам нужно вручную просмотреть все запущенные процессы (командную строку или диспетчер задач) и найти любые процессы «Python».
В общем, я рекомендую запускать скрипт в командной строке, так как у вас больше контроля над ним.