Какие ивенты есть в discord py
A few days ago I became interested in programming discord bots a bit. In the syntax of these programs I noticed a lot of unintelligible issues that I can not find an answer to. That's why I am asking you for help in understanding them.
All questions are based on this code:
What is @client.event? I found that is a event handler, but how is it worki? Why is it needed to run program? Is it somehow connected to a asyncio?
Thanks you so much, i have already found something about these decorators, let's study now. Thanks again. :P
1 Answer 1
When a Client receives an event from Discord, It works out what that event is and generates, or locates, the objects that were sent by the event, such as a discord.Message for any MESSAGE_RECEIVE events, or a discord.Reaction for REACTION_ADD etc.
The client then sends the objects into the method that handles those events, but you first need to tell the client what those methods are. This is where the event decorators come in.
Decorators are, in essence, functions that take other functions as arguments. The most common one you'll see is @property . This says that the function you define should be passed into the property() function
This may be a bit confusing to wrap your head around, but this is how discord.py handles its events.
When you use the @client.event decorator on your on_message , what you are actually doing is saying on_message = client.event(on_message)
The internal code of discord.py for on_event is this
Which means that it takes the function as its parameter, and sets a new attribute on the client itself. For our on_message example, we pass our on_message function into client.event() and it makes the client define a new client.on_message method that is the same method as our on_message .
Note: func.__name__ returns the name of that function. on_message.__name__ will return "on_message" .
setattr(obj, name, value) sets an attribute on an object, so setattr(self, "foo", 100) means that self.foo will be 100.
Now that the client knows our on_message , when it receives an event saying that a message was sent, it creates the discord.Message object and passes that into client.on_message , which as we already established, is the same as our own on_message
If you wanted, you could even just skip the decorator and do this after your function, but it is less elegant than a decorator is:
Discord.py is a very powerful API. It aims to make creating Discord bots incredibly easy while still giving lots of power to the user. People have made game bots, RPG bots, Moderation Bots, Economy bots, and even more! Carl-bot, Auttaja, and lots more bots use discord.py. Using this guide, you can learn how to use it.
Users who have contributed to this file
- Open with Desktop
- View raw
- Copy raw contents Copy raw contents
Copy raw contents
Copy raw contents
The following section outlines the API of discord.py.
This module uses the Python logging module to log diagnostic and errors in an output independent way. If the logging module is not configured, these logs will not be output anywhere. See :ref:`logging_setup` for more information on how to set up and use the logging module with discord.py.
Version Related Info
There are two main ways to query version information about the library. For guarantees, check :ref:`version_guarantees` .
This section outlines the different types of events listened by :class:`Client` .
There are two ways to register an event, the first way is through the use of :meth:`Client.event` . The second way is through subclassing :class:`Client` and overriding the specific events. For example:
If an event handler raises an exception, :func:`on_error` will be called to handle it, which defaults to print a traceback and ignoring the exception.
All the events must be a |coroutine_link|_ . If they aren't, then you might get unexpected errors. In order to turn a function into a coroutine they must be async def functions.
A data class which represents a resolved invite returned from :func:`discord.utils.resolve_invite` .
The API provides some enumerations for certain types of strings to avoid the API from being stringly typed in case the strings change in the future.
All enumerations are subclasses of an internal class which mimics the behaviour of :class:`enum.Enum` .
Specifies the type of channel.
Specifies the type of :class:`Message` . This is used to denote if a message is to be interpreted as a system message or a regular message.
Represents Discord User flags.
Specifies the type of :class:`Activity` . This is used to check how to interpret the activity itself.
Specifies a :class:`Guild` 's verification level, which is the criteria in which a member must meet before being able to send messages to the guild.
Specifies whether a :class:`Guild` has notifications on for all messages or mentions only by default.
Specifies a :class:`Guild` 's explicit content filter, which is the machine learning algorithms that Discord uses to detect if an image contains pornography or otherwise explicit content.
Specifies a :class:`Member` 's status.
Represents the type of action being done for a :class:`AuditLogEntry` , which is retrievable via :meth:`Guild.audit_logs` .
Represents the category that the :class:`AuditLogAction` belongs to.
Represents the membership state of a team member retrieved through :func:`Client.application_info` .
Represents the type of webhook that can be received.
Represents the behaviour the :class:`Integration` should perform when a user's subscription has finished.
There is an alias for this called ExpireBehavior .
Represents the default avatar of a Discord :class:`User`
Represents the type of sticker.
Represents the type of sticker images.
Represents the invite type for voice channel invites.
Represents the camera video quality mode for voice channel participants.
Represents the privacy level of a stage instance or scheduled event.
Represents the NSFW level of a guild.
Supported locales by Discord. Mainly used for application command localisation.
Represents the Multi-Factor Authentication requirement level of a guild.
Represents the type of entity that a scheduled event is for.
Represents the status of an event.
Working with :meth:`Guild.audit_logs` is a complicated process with a lot of machinery involved. The library attempts to make it easy to use and friendly. In order to accomplish this goal, it must make use of a couple of data classes that aid in this goal.
An audit log change set.
Represents an audit log "change" object. A change object has dynamic attributes that depend on the type of action being done. Certain actions map to certain attributes being set.
Note that accessing an attribute that does not match the specified action will lead to an attribute error.
To get a list of attributes that have been set, you can iterate over them. To see a list of all possible attributes that could be set based on the action being done, check the documentation for :class:`AuditLogAction` , otherwise check the documentation below for all attributes that are possible.
discord.py offers support for creating, editing, and executing webhooks through the :class:`Webhook` class.
Installing discord.py
Assuming you have Python already installed, you should install discord.py with
Exit fullscreen mode
Ta-da! discord.py is ready for use!
You will need to make a bot account for your bot. A guide to this is written here.
Discussion (6)
Hi, I'm trying to apply your methodology but with a different API. The key for mine is different (url) and I'm wondering if this might be affecting why my bot won't send the image when I input the command. I've attached my current code below. Please let me know if you can assist and thank you for the post! Code done in Replit
@client.event
async def on_ready():
print('We have logged in as '.format(client))
Гайд для GitHub по написанию бота c помощью discord.py
Дата написания данного гайда 05.02.2021 Библиотека discord.py может обновляться, поэтому после крупных патчей разработка бота может отличаться. В любом случае ближайшие несколько месяцев данный гайд будет актуален.
Что нам потребуется?:
- Стабильное интернет соединение
- Неплохие знания Питона
- Умение "гуглить" и находить нужную информацию
- Среда для написания кода
Я советую для разработки бота создать отдельный сервер в Дискорде, где мы будем проверять нашего бота, потому что почти ни у кого не получается запустить сложный код с первого раза, а спамить другим не очень хочется.
Создание Application'a:
После создания Application'а мы должны перейти во вкладку Bot, а затем нажать на кнопку Add Bot.
Если у вас появилось зеленая надпись по типу: A wild bot has appeared!, значит вы всё сделали правильно и бот у вас уже создан.
Подключаем нашего бота к серверу:
Для того чтобы подключить бота к вашему серверу Дискорд, нужно следовать простым инструкциям:
Нужно получить Client_ID вашего бота. Для этого мы переходим во вкладку General Information и копируем его нажав на кнопку Copy.
Копируем эту ссылку ==> https://discordapp.com/oauth2/authorize?&client_id=(тут)&scope=bot&permissions=8 . В эту ссылку вместо слова "тут" вставляем наш Client_ID. Скобки естественно убираем. Доп. информация: В нашей ссылке bot&permissions=8 означает что наш permissions integer равен 8. Проще говоря, это число отвечает за то, какие права будут выданы боту при подключении. Этот код можно узнать во вкладке Bot (в которой мы создавали бота). Пролистав вниз, вы сможете сами выбрать нужные вам права, но я советую оставить 8, так как если вы будете сами выбирать права, могут произойти казусные ситуации при работе с ботом.
После создания нашей ссылки мы переходим по ней, выбираем сервер на который хотите пригласить бота и нажимаем кнопку Авторизовать. После прохождения капчи наш бот успешно присоединится к серверу, но будет оффлайн. Не пугайтесь, это нормально, ведь наш бот еще не запущен.
Создание проекта:
Ну вот мы и готовы начать писать код для нашего прекрасного бота. Если вы знаете Python на ОЧЕНЬ низком уровне, я советую воздержаться от создания ботов и заняться чем нибудь более простым.
Для начала я советую создать пустую папку где мы будем хранить все файлы для нашего бота.
Затем если у вас не установлена библиотека discord.py, вам нужно её устновить. Для этого переходим в командную строку и пишем: pip install discord.py
Внимание, для установки библиотек требуется pip, если он у вас не установлен, то гугл в помощь ^_^
После успешной установки библиотеки, переходим в вашу любимую среду разработки, в моём случае это PyCharm. Затем создаем новый файл Python файл с названием "bot" (такое название не даст вам запутаться) и расширением .py и сразу сохраняем его в нашей папке с проектом.
Первые строчки кода: Начинаем писать скрипт для нашего бота.
Для начала подключаем (импортируем) наши библиотеки:
(можем запустить наш скрипт для проверки работоспособности библиотеки)
Создаем еще один файлик .py названием config, для хранения в нём опасных данных. Почему мы не можем просто создать переменные с этими данными? Всё очень просто. Это самый простой способ защитить себя от злоумышленников. Если кто-то каким-то образом получит ваш код, то не сможет управлять вашим ботом. Все наши токены будут хранится в отдельном файлике.
В файле config.py создаем словарь, к которому мы будем обращаться при работе в ботом:
Сохраняем файл config.py и возвращаемся обратно к файлу bot.py
Импортируем наш файлик config.py:
Написание "тела" для бота и первый запуск:
Я буду стараться объяснять подробно каждый шаг и каждую строчку, потому что на первый взгляд это может показаться сложным, хотя таковым не является.
- Переменная bot - это "тело" нашего бота. Ему мы присваиваем значение commands.Bot с определёнными аргументами.
- command_prefix=settings['prefix'] - это аргумент, в который мы вписываем значение нашего префикса. settings['prefix'] означает, кто мы обращаемся к словарю settings (который мы импортировали из файла config.py) и обращаемся к ключу prefix, в котором вписано нужное нам значение.
Затем мы можем проверить, запускается наш бот или нет. В библиотеке discord.py есть огромное количество разных ивентов (Event). Одним из них мы сейчас воспользуемся:
@bot.event - говорит нам о том, что ниже будет прописана функция, являющаяся ивентом.
async def on_ready(): - Асинхронная функция (Очень важно все функции создавать асинхронными, так как бот должен выполнять несколько функций в одно время). Ей присваивается значение on_ready, данная функция срабатывает когда бот полностью подключен и готов к работе. Аргументов у этой функции нет.
Создание первой команды:
Настало время создать первую команду для нашего бота:
Можем запускать нашего бота и проверять команду!
Давайте создадим еще одну команду, но уже с использованием посторонней библиотеки. Я возьму библиотеку random. Для начала её нужно подключить. Переходим в cmd (командную строку) и пишем pip install random, после чего начнется скачка библиотеки. Затем в самом начале кода пишем:
Я создал очень простую команду, которая умеет генерировать случайное число от 0 до числа, которого мы зададим сами:
Точно так-же говорим о том что ниже будет команда с помощью строчки @bot.command. Напоиманаю, что bot - это перемеенная, которую мы создали в самом начале. Это наше "тело" для бота. Дольше создаем асинхронную функцию randoms. Почему не random? Потому что название функции не может совпадать с названием библиотеки. Дальше мы передаем 2 аргумеента: ctx и arg. В arg поместиться наше число, которое мы будем задавать. Дальше я использую try, вы спросите зачем? Всё просто. Если мы случайно укажем вместо числа какой-то другой символ, бот в чате выдаст ошибку. Затем мы создаем переменную a - это наше сгенерированное число. Как генерировать числа с помощью библиотеки random вы сможете найти выше по ссылке. Дальше с помощью await ctx.send мы выводим наше число.
Есть еще очень классная "фича" в библиотеке discord.py как стили embed. Их обычно используют для красивого вывода какой либо информации на экран. Например команды help обычно делают с использованием этого стиля. Я создал небольшую и довольно простую функцию, которая называется menu. В неё мы например можем записать каждую команду в боте и указать что она делает. Вот что у меня получилось:
Некоторые строчки я буду пропускать, потому что я их свойства и значения я объяснял выше. В любом случае если вы что-то не поняли я оставлял ссылку на доп. информацию в самом конце гайда. Для начала мы задаем переменную embed, в которой мы будем хранить сам "embed", а так-же его значения. Color - цвет, title - текст, который будет являться "названием". В них мы записываем нужны нам значения. Кстати в color мы так-же можем записывать цвет словами, например "yellow", "white" и так далее. Дальше мы прописываем add_field, эта штука добавляет нам новую "строку" для "embed". В значение name мы записываем имя строки, в value - значение ну и в inline указываем True или False, она меняет расположение строки. Советую поиграться и выбрать самый оптимальный для вас вариант. Последней строчкой в значении embed мы просто указываем переменную, которую мы задали в начале функции.
Есть еще несколько вещей, которые я хотел бы разобрать, но это я сделаю в будущем
P.S Возможно, я когда нибудь дополню этот гайд дополнительными интересными командами и ивентами.
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
79 contributors
The basics of a bot
When starting out and creating your bot, you need to decide whether to use discord.Client or commands.Bot .
- Is more lightweight than commands.Bot
- Is best if you're not going to be using commands
- Has an extensive commands system
- Is best if your bot is going to have commands
- Supports a high amount of code splitting through 'cogs'
- Supports easy discord object conversion
In this guide we will make a bot with commands, so we will use commands.Bot.
Exit fullscreen mode
What we just did was initialize a class as an object. This is similar to having an idea for an invention, then creating your invention. We defined this class to the variable bot , which can be named whatever you want. Most people use bot or client .
Now that our bot is defined, we can start on the first commands. discord.py's commands.Bot creates commands like this:
Exit fullscreen mode
Exit fullscreen mode
ctx is the context of our command, which contains lots of data that can be used. It also has the send method, which will let us send a message to the channel the command was used in.
Now, let's make it say the command user's username! To do this we can use ctx.author :
Exit fullscreen mode
Now, when we greet the user, it will say Hello mikey 🌌!
Congratulations! You've just written a bot using discord.py! Run the code, and your bot should come online! When you type !hello , the bot will respond!
Final Code:
PSSST! Need some web development resources? Check out this article, by @devlorenzo!
In this article, you're going to learn how to make a Discord bot that can:
- Send a picture of a dog in an embed
- Send a dog fact in an embed using footers
By the end of this post, you will know how to:
- Make REST API requests
- Parse JSON data
- Use the footer and image fields of an embed.
Wherever the command is used, it will send an embed similar to this:
To start, we need to initialize our bot. This time, we're back using commands.Bot since we are going to have one function, our dog command.
Exit fullscreen mode
So far, we have a bot with the prefix ! . When it's ready, it will print Ready in the console!
Exit fullscreen mode
Now create the command:
Exit fullscreen mode
Now, dogjson will be a variable containing a dictionary, which is a list of aliases.
What's a dictionary?
An example of where you would use a dictionary is in a substitution cipher. You might be making an a1z26 (where a becomes 1 , b becomes 2 , etc.). So, you'd make a dictionary to make it easier:
Exit fullscreen mode
Now, you could use this to substitute:
Exit fullscreen mode
Knowing that the dictionary is structured like this:
we know that we want to use the link key.
Exit fullscreen mode
Now, when we use the bot command, we will get this output:
Now, let's have it send a dog fact as well! SomeRandomAPI also has a dog facts endpoint, which will allow us to get a random fact about dogs!
Exit fullscreen mode
This will produce the following!
Have Questions? Have a suggestion about what to do for the next post?
Tell me in the comments and I'll reply!
Читайте также: