Команда user discord py
Interest in creating a Discord bot is a common introduction to the world of programming in our community.
Using it as your first project in programming while trying to learn is a double-edged sword. A large number of concepts need to be understood before becoming proficient at creating a bot, making the journey of learning and completing the project more arduous than more simple projects designed specifically for beginners. However in return, you get the opportunity to expose yourself to many more aspects of Python than you normally would and so it can be an amazingly rewarding experience when you finally reach your goal.
Another excellent aspect of building bots is that it has a huge scope as to what you can do with it, almost only limited by your own imagination. This means you can continue to learn and apply more advanced concepts as you grow as a programmer while still building bots, so learning it can be a useful and enjoyable skillset.
This page provides resources to make the path to learning as clear and easy as possible, and collates useful examples provided by the community that may address common ideas and concerns that are seen when working on Discord bots.
Essential References¶
Creating a Discord Bot Account¶
Client ID¶
Your Client ID is the same as the User ID of your Bot. You will need this when creating an invite URL.
You can find your Client ID located on the General Information settings page of your Application, under the Name field.
Your Client ID is not a secret, and does not need to be kept private.
Bot Token¶
Your Bot Token is the token that authorises your Bot account with the API. Think of it like your Bot's API access key. With your token, you can interact with any part of the API that's available to bots.
You can find your Bot Token located on the Bot settings page of your Application, under the Username field. You can click the Copy button to copy it without revealing it manually.
Your Bot Token is a secret, and must be kept private. If you leak your token anywhere other people has access to see it, no matter the duration, you should reset your Bot Token.
To reset your token, go to the Bot settings page of your Application, and click the Regenerate button. Be sure to update the token you're using for your bot script to this new one, as the old one will not work anymore.
Permissions Integer¶
Discord Permissions are typically represented by a Permissions Integer which represents all the Permissions that have been allowed.
If you want to create your own Permissions Integer, you can generate it in the Bot settings page of your Application, located at the bottom of the page.
Tick the permissions you want to be allowing, and it'll update the Permissions Integer field, which you can use in your Bot Invite URL to set your bot's default permissions when users go to invite it.
Bot Invite URL¶
Bot's cannot use a server invite link. Instead, they have to be invited by a member with the Manage Server permission.
You can create the Invite URL for your bot by replacing:
You can also generate it with the Permissions Calculator tool.
Using the Basic Client ( discord.Client )¶
Below are the essential resources to read over to get familiar with the basic functionality of discord.py .
Using the Commands Extension ( commands.Bot )¶
It fully covers: * How to create bot using the Commands Extension * How to define commands and their arguments * What the Context object is * Argument Converters * Error Handling basics * Command checks
Usage Examples¶
Official Examples and Resources¶
The official examples can be found on the source repository.
Permissions Documentation¶
Community Examples and Resources¶
The discord.py developer community over time have shared examples and references with each other.
The following are a collated list of the most referenced community examples.
Extensions / Cogs¶
Error Handling¶
Embeds¶
Using Local Images in Embeds¶
Embed Limits¶
Element | Characters |
---|---|
Title | 256 |
Field Name | 256 |
Field Value | 1024 |
Description | 2048 |
Footer | 2048 |
Entire Embed | 6000 |
Element | Count |
---|---|
Fields | 25 |
Emoji¶
Activity Presence¶
Image Processing¶
Systemd Service¶
botname.service
Directory
/usr/local/lib/systemd/system
Service Commands
Refresh systemd after unit file changes:
systemctl daemon-reload
Set service to start on boot:
systemctl enable botname
Start service now:
systemctl start botname
Stop service:
systemctl stop botname
Viewing Logs
All logs:
journalctl -u botname
Recent logs and continue printing new logs live:
journalctl -fu mybot
One of the most appealing aspect 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.
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.
Essentially, these two are equivalent:
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 to fetch the Guild of the command, if any.
Context.message to fetch the Message of the command.
Context.author to fetch 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 it’s 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.
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 and Greedy are forbidden as parameters for the Greedy converter.
Error Handling¶
When our commands fail to either 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() :
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.
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.
Сегодня мы создадим Discord бота на Python, для этого не надо прикладывать каких то фантастических усилий.
Подготовка к работе
Для начала посещаем портал разработчиков и жмём кнопку "New Application" ("Создать приложение"), вводим название нашего будущего бота и жмём "Create" ("Создать").
Диалоговое окно
Теперь нам нужно создать аккаунт для бота — переходим в категорию "Bot" и жмём "Add Bot" ("Добавить бота"), в появляющемся диалоговом окне подтвердим это — "Yes, do it!".
Настройки бота
Копируем токен используя соответсвующую кнопку.
Интересный факт: Токен разделён на 3 части с помощью точек. Первая часть — зашифрованый с помощью base64 ID бота, вторая — время создания токена, третья — секретный ключ.
А сейчас нам нужно установить библиотеку discord.py. Для этого нужно использовать утилиту pip.
pip install discord.py — обратите внимание что на дистрибутивах Linux pip , python являются версией 2.х, но нам нужна конкретно 3.5.3 и выше, поэтому pip нужно будет заменить на pip3 или pip3.x .
Также если у вас появилась ошибка изза отсутсвия прав суперпользователя (администратора) вы можете использовать флаг --user для установки библиотеки только для вашего пользователя.
"Костяк" программной части бота. Эвенты, команды
После установки библиотеки можем приступать к написанию кода.
Давайте разбираться что это такое. Для начала — в первой строке мы видим декоратор bot.event , он обозначает программе что следующая функция будет реакцией на действие. Во второй строке мы видим саму функцию — она асинхронна.
Почему она должна быть асинхронна? Потому что возьмём для примера команду которую исполняют одновременно 2 раза разные пользователи. def может заставить бота повиснуть изза того что она не может быть исполнена вместе с другими процессами, но async def занимает только один поток вместо того что бы не давать другим процессам программы исполняться.
Мы видим что название функции — on_ready , её вызывает фреймворк если бот аутентифицировался. Дальше мы печатаем "Logged in as BotName", где BotName это значение переменной bot.user.name , если простым языком "Имя пользователя бота".
Тестируем наш костяк
Для начала нам нужно пригласить бота на сервер — и мы возвращаемся на портал разработки, переходим в категорию OAuth2 и в поле "Scopes" отмечаем только галочку на bot и получаем приглашение.
Асинхронная библиотека discord.py содержит все что нужно для бота, с помощью нее даже можно работать с голосовыми каналами сервера. В этой статье я расскажу как создать простенького бота для вашего discord сервера.
Получение токена и Client ID для вашего бота
Для получения токена и ID бота небходимо создать свое приложение и в разделе General Information скопировать Client ID.
А в разделе настроек создать бота и скопировать его токен. Задача не сложная, думаю все с этим справятся.
Собственно пишем бота
Устанавливаем discord.py с помощью pip:
После успешной установки создаем файл bot.py, где будем писать бота.
Импортируем все необходимое:
Создаем переменную с вашим токеном, про который я писал выше:
Создаем тело бота:
Для начала сделаем простенькую команду, аргумент которой бот будет просто пересылать:
И в конце запускаем бота с вашим токеном:
В итоге должно получится вот такое:
Теперь необходимо добавить бота на сервер. Сделать это можно с помощью ссылки:
Число необходимых прав можно получить в разделе настроек бота.
Теперь можно запускать бота:
После нескольких секунд, можно заметить его в сети:
Заключение
Вот так можно легко запустить у себя на сервере бота. Как можно заметить библиотека делает практически все за тебя и остается только добавлять свой функционал с использованием python. В следующий раз я покажу как следить за событиями, подключатся к голосовым каналам (избегая проблем с linux и Windows), использовать роли и права участников и другое.
Читайте также: