How to write discord bot on python

How to write discord bot on python

Пишем Discord бота на Python используя фреймворк discord.ext

Сегодня мы создадим Discord бота на Python, для этого не надо прикладывать каких то фантастических усилий.

Подготовка к работе

Для начала посещаем портал разработчиков и жмём кнопку «New Application» («Создать приложение»), вводим название нашего будущего бота и жмём «Create» («Создать»).

Диалоговое окно

How to write discord bot on python. Смотреть фото How to write discord bot on python. Смотреть картинку How to write discord bot on python. Картинка про How to write discord bot on python. Фото How to write discord bot on python

Теперь нам нужно создать аккаунт для бота — переходим в категорию «Bot» и жмём «Add Bot» («Добавить бота»), в появляющемся диалоговом окне подтвердим это — «Yes, do it!».

Настройки бота

How to write discord bot on python. Смотреть фото How to write discord bot on python. Смотреть картинку How to write discord bot on python. Картинка про How to write discord bot on python. Фото How to write discord bot on python

Копируем токен используя соответсвующую кнопку.

Интересный факт: Токен разделён на 3 части с помощью точек. Первая часть — зашифрованый с помощью base64 ID бота, вторая — время создания токена, третья — секретный ключ.

А сейчас нам нужно установить библиотеку discord.py. Для этого нужно использовать утилиту pip.

«Костяк» программной части бота. Эвенты, команды

После установки библиотеки можем приступать к написанию кода.

Почему она должна быть асинхронна? Потому что возьмём для примера команду которую исполняют одновременно 2 раза разные пользователи. def может заставить бота повиснуть изза того что она не может быть исполнена вместе с другими процессами, но async def занимает только один поток вместо того что бы не давать другим процессам программы исполняться.

Этот аргумент хранит информацию про сообщение, автора сообщения, гильдию, канал и т.п. и быть он всегда должен первым аргументом.

И что же мы делаем в ответ на команду? Мы запускаем асинхронную функцию ctx.send что бы отправить сообщение в тот канал в котором была отправлена команда

Тестируем наш костяк

Для начала нам нужно пригласить бота на сервер — и мы возвращаемся на портал разработки, переходим в категорию OAuth2 и в поле «Scopes» отмечаем только галочку на bot и получаем приглашение.

Запускаем бота, и тестируем работает ли команда

How to write discord bot on python. Смотреть фото How to write discord bot on python. Смотреть картинку How to write discord bot on python. Картинка про How to write discord bot on python. Фото How to write discord bot on python

Заключение

Возможно в следующих туториалах:

Работа с эмбедами
Разбитие бота на коги

Making a Cool Discord Bot in Python 3

Discord has a wonderful API that allows you to creates bots that can join Discord servers and channels and help manage as well as add extra functionality for it’s users.

In this tutorial I will show you how to make a basic Discord bot written in Python 3 that will be able to take handle custom commands using the discord.py package available through pip.

How to write discord bot on python. Смотреть фото How to write discord bot on python. Смотреть картинку How to write discord bot on python. Картинка про How to write discord bot on python. Фото How to write discord bot on python

Step 1: Getting Setup

Having a good editor can make the process of writing and debugging code in any language much easier. Some good free editors that I have personally used are PyCharm Community Edition and Sublime Text 3.

You will also need to make sure that you have Python 3 installed on you computer. If you are on Windows you can download an installer from the following link.

Welcome to Python.org

The official home of the Python Programming Language

You will also need to go to the Discord website and create your bot, add it to a server, and grant it permissions. This can be done at the following link.

Discord API Docs for Bots and Developers

The following eight pictures will guide you through setting up you bot and adding it to your Discord server.

How to write discord bot on python. Смотреть фото How to write discord bot on python. Смотреть картинку How to write discord bot on python. Картинка про How to write discord bot on python. Фото How to write discord bot on python

How to write discord bot on python. Смотреть фото How to write discord bot on python. Смотреть картинку How to write discord bot on python. Картинка про How to write discord bot on python. Фото How to write discord bot on python

How to write discord bot on python. Смотреть фото How to write discord bot on python. Смотреть картинку How to write discord bot on python. Картинка про How to write discord bot on python. Фото How to write discord bot on python

How to write discord bot on python. Смотреть фото How to write discord bot on python. Смотреть картинку How to write discord bot on python. Картинка про How to write discord bot on python. Фото How to write discord bot on python

How to write discord bot on python. Смотреть фото How to write discord bot on python. Смотреть картинку How to write discord bot on python. Картинка про How to write discord bot on python. Фото How to write discord bot on python

How to write discord bot on python. Смотреть фото How to write discord bot on python. Смотреть картинку How to write discord bot on python. Картинка про How to write discord bot on python. Фото How to write discord bot on python

How to write discord bot on python. Смотреть фото How to write discord bot on python. Смотреть картинку How to write discord bot on python. Картинка про How to write discord bot on python. Фото How to write discord bot on python

How to write discord bot on python. Смотреть фото How to write discord bot on python. Смотреть картинку How to write discord bot on python. Картинка про How to write discord bot on python. Фото How to write discord bot on python

You should now be able to see your bot in the Discord server you added it too and it should have a little tag that says “Bot” next to it’s name.

Step 2: Starting the Code

Create a folder that you will use for bot and in it create a file called bot.py. We are going to start by adding the boilerplate code that is required.

But first we need to install discord.py with Python’s package manager called pip. You can do this by navigating to you Command Prompt in Windows and entering the following.

After this has completed successfully we can open our bot.py and begin. The code below imports the discord.py package that we just installed as well as creates our Discord client object that we will use to interact with the API. The token variable has our bot’s token that we copied earlier from the Discord developers page.

The client variable seen on line 4 is a Discord client object and will facilitate all the communication of the bot.

The on_ready() function above will be called when the bot starts and is connects to the API and will print the bot’s username, client ID, and the version of discord.py that is being used as seen beneath the try on line 12, 13, 14.

The on_message() function above will be called when ever a new message is posted in the Discord server and the message will be passed as the message variable seen entered as it’s only argument. As we have the function right now it will print that message to the console when received.

Try running this code, if it works you should see your bot’s username and client id printed in the console. If you go to the Discord channel that bot was added to and type a message you should see it appear in the console where you bot is running, you might also get an error directly after it which you can ignore for now.

Step 3: Building a Command Handler

So at this point our bot is able to read every message that is posted in it’s Discord server. To make this useful we need to implement some kind function that evaluates the messages that are posted. We can do this by making a command handler which will read each message, determine if a command is being called, and relay the appropriate response.

Although, before we make our command handler we have to decide on how we are going to organize our commands to make them easy to implement and visualize. My favorite way to do this in Python is by using dictionaries. Dictionaries allow us to define multiple labeled properties to a variable. An example is shown below.

The function above starting on line 2 will take in the parameters message, clients, and args. The variable message is an object with the details of the message, the client variable is also an object we need in the function to send messages with, the args variable is and array that will contain the arguments for function. This function will be used as a variable in our dictionary.

The Command Dictionary Parts

We could just write an independent function that would handle these commands but there is a better way to do it, creating a class. This class will contain methods to add commands, store commands, and evaluate commands. The class would look like this…

The __init__(self, client) method will be called when the class is instantiated and will bind the client object to itself and create an array, self.commands, to store the commands.

The add_command(self, command) method simply adds the command dictionary that we designed earlier to the self.commands array.

The command_handler(self, message) method will be used to evaluate each message that is sent on the Discord server. It basically just sees if the message starts with a command trigger and if it does it executes it’s corresponding function. The following is a pseudo code breakdown of what the command handler is doing for each message posted in the server.

Step 4: Bringing it all together

Below is what all this code would look like together and should be completely functional.

Step 5: Adding useful Functions & Examples

So what we have now is a functional “platform” to expand on. In this step I will demonstrate some of the more advanced things you could do with this setup and some ways to make it more user friendly.

Also if you notice, you also can use the Discord formatting markdown shown in the link below to style your outputs, the **text** will show up as bold in Discord. You can also use Unicode Symbols to mark new lines ( \n).

Markdown Text 101 (Chat Formatting: Bold, Italic, Underline)

Want to inject some flavor into your everyday text chat? You’re in luck! Discord uses Markdown, a simple plain text…

At this point you can do allot. Any information you can get into Python (which is allot) you can style and print to the users. You can add allot of cool features just from using different API’s. Below are a couple other API’s that I have made commands with.

How to Make a Discord Bot in Python

Table of Contents

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Creating a Discord Bot in Python

In a world where video games are so important to so many people, communication and community around games are vital. Discord offers both of those and more in one well-designed package. In this tutorial, you’ll learn how to make a Discord bot in Python so that you can make the most of this fantastic platform.

By the end of this article you’ll learn:

You’ll begin by learning what Discord is and why it’s valuable.

What Is Discord?

Discord is a voice and text communication platform for gamers.

Players, streamers, and developers use Discord to discuss games, answer questions, chat while they play, and much more. It even has a game store, complete with critical reviews and a subscription service. It is nearly a one-stop shop for gaming communities.

While there are many things you can build using Discord’s APIs, this tutorial will focus on a particular learning outcome: how to make a Discord bot in Python.

What Is a Bot?

Discord is growing in popularity. As such, automated processes, such as banning inappropriate users and reacting to user requests are vital for a community to thrive and grow.

Automated programs that look and act like users and automatically respond to events and commands on Discord are called bot users. Discord bot users (or just bots) have nearly unlimited applications.

For example, let’s say you’re managing a new Discord guild and a user joins for the very first time. Excited, you may personally reach out to that user and welcome them to your community. You might also tell them about your channels or ask them to introduce themselves.

The user feels welcomed and enjoys the discussions that happen in your guild and they, in turn, invite friends.

Over time, your community grows so big that it’s no longer feasible to personally reach out to each new member, but you still want to send them something to recognize them as a new member of the guild.

With a bot, it’s possible to automatically react to the new member joining your guild. You can even customize its behavior based on context and control how it interacts with each new user.

This is great, but it’s only one small example of how a bot can be useful. There are so many opportunities for you to be creative with bots, once you know how to make them.

Note: Although Discord allows you to create bots that deal with voice communication, this article will stick to the text side of the service.

There are two key steps when you’re creating a bot:

In the next section, you’ll learn how to make a Discord bot in Discord’s Developer Portal.

How to Make a Discord Bot in the Developer Portal

Before you can dive into any Python code to handle events and create exciting automations, you need to first create a few Discord components:

You’ll learn more about each piece in the following sections.

Once you’ve created all of these components, you’ll tie them together by registering your bot with your guild.

You can get started by heading to Discord’s Developer Portal.

Creating a Discord Account

The first thing you’ll see is a landing page where you’ll need to either login, if you have an existing account, or create a new account:

How to write discord bot on python. Смотреть фото How to write discord bot on python. Смотреть картинку How to write discord bot on python. Картинка про How to write discord bot on python. Фото How to write discord bot on python

If you need to create a new account, then click on the Register button below Login and enter your account information.

Important: You’ll need to verify your email before you’re able to move on.

Once you’re finished, you’ll be redirected to the Developer Portal home page, where you’ll create your application.

Creating an Application

An application allows you to interact with Discord’s APIs by providing authentication tokens, designating permissions, and so on.

To create a new application, select New Application:

How to write discord bot on python. Смотреть фото How to write discord bot on python. Смотреть картинку How to write discord bot on python. Картинка про How to write discord bot on python. Фото How to write discord bot on python

Next, you’ll be prompted to name your application. Select a name and click Create:

How to write discord bot on python. Смотреть фото How to write discord bot on python. Смотреть картинку How to write discord bot on python. Картинка про How to write discord bot on python. Фото How to write discord bot on python

Congratulations! You made a Discord application. On the resulting screen, you can see information about your application:

How to write discord bot on python. Смотреть фото How to write discord bot on python. Смотреть картинку How to write discord bot on python. Картинка про How to write discord bot on python. Фото How to write discord bot on python

Keep in mind that any program that interacts with Discord APIs requires a Discord application, not just bots. Bot-related APIs are only a subset of Discord’s total interface.

However, since this tutorial is about how to make a Discord bot, navigate to the Bot tab on the left-hand navigation list.

Creating a Bot

As you learned in the previous sections, a bot user is one that listens to and automatically reacts to certain events and commands on Discord.

For your code to actually be manifested on Discord, you’ll need to create a bot user. To do so, select Add Bot:

How to write discord bot on python. Смотреть фото How to write discord bot on python. Смотреть картинку How to write discord bot on python. Картинка про How to write discord bot on python. Фото How to write discord bot on python

Once you confirm that you want to add the bot to your application, you’ll see the new bot user in the portal:

How to write discord bot on python. Смотреть фото How to write discord bot on python. Смотреть картинку How to write discord bot on python. Картинка про How to write discord bot on python. Фото How to write discord bot on python

How to write discord bot on python. Смотреть фото How to write discord bot on python. Смотреть картинку How to write discord bot on python. Картинка про How to write discord bot on python. Фото How to write discord bot on python

Now, the bot’s all set and ready to go, but to where?

A bot user is not useful if it’s not interacting with other users. Next, you’ll create a guild so that your bot can interact with other users.

Creating a Guild

A guild (or a server, as it is often called in Discord’s user interface) is a specific group of channels where users congregate to chat.

Note: While guild and server are interchangeable, this article will use the term guild primarily because the APIs stick to the same term. The term server will only be used when referring to a guild in the graphical UI.

For example, say you want to create a space where users can come together and talk about your latest game. You’d start by creating a guild. Then, in your guild, you could have multiple channels, such as:

Once you’ve created your guild, you’d invite other users to populate it.

So, to create a guild, head to your Discord home page:

How to write discord bot on python. Смотреть фото How to write discord bot on python. Смотреть картинку How to write discord bot on python. Картинка про How to write discord bot on python. Фото How to write discord bot on python

From this home page, you can view and add friends, direct messages, and guilds. From here, select the + icon on the left-hand side of the web page to Add a Server:

How to write discord bot on python. Смотреть фото How to write discord bot on python. Смотреть картинку How to write discord bot on python. Картинка про How to write discord bot on python. Фото How to write discord bot on python

This will present two options, Create a server and Join a Server. In this case, select Create a server and enter a name for your guild:

How to write discord bot on python. Смотреть фото How to write discord bot on python. Смотреть картинку How to write discord bot on python. Картинка про How to write discord bot on python. Фото How to write discord bot on python

Once you’ve finished creating your guild, you’ll be able to see the users on the right-hand side and the channels on the left:

How to write discord bot on python. Смотреть фото How to write discord bot on python. Смотреть картинку How to write discord bot on python. Картинка про How to write discord bot on python. Фото How to write discord bot on python

The final step on Discord is to register your bot with your new guild.

Adding a Bot to a Guild

A bot can’t accept invites like a normal user can. Instead, you’ll add your bot using the OAuth2 protocol.

Technical Detail: OAuth2 is a protocol for dealing with authorization, where a service can grant a client application limited access based on the application’s credentials and allowed scopes.

To do so, head back to the Developer Portal and select the OAuth2 page from the left-hand navigation:

How to write discord bot on python. Смотреть фото How to write discord bot on python. Смотреть картинку How to write discord bot on python. Картинка про How to write discord bot on python. Фото How to write discord bot on python

From this window, you’ll see the OAuth2 URL Generator.

This tool generates an authorization URL that hits Discord’s OAuth2 API and authorizes API access using your application’s credentials.

In this case, you’ll want to grant your application’s bot user access to Discord APIs using your application’s OAuth2 credentials.

To do this, scroll down and select bot from the SCOPES options and Administrator from BOT PERMISSIONS:

How to write discord bot on python. Смотреть фото How to write discord bot on python. Смотреть картинку How to write discord bot on python. Картинка про How to write discord bot on python. Фото How to write discord bot on python

Now, Discord has generated your application’s authorization URL with the selected scope and permissions.

Disclaimer: While we’re using Administrator for the purposes of this tutorial, you should be as granular as possible when granting permissions in a real-world application.

Select Copy beside the URL that was generated for you, paste it into your browser, and select your guild from the dropdown options:

How to write discord bot on python. Смотреть фото How to write discord bot on python. Смотреть картинку How to write discord bot on python. Картинка про How to write discord bot on python. Фото How to write discord bot on python

Click Authorize, and you’re done!

Note: You might get a reCAPTCHA before moving on. If so, you’ll need to prove you’re a human.

If you go back to your guild, then you’ll see that the bot has been added:

How to write discord bot on python. Смотреть фото How to write discord bot on python. Смотреть картинку How to write discord bot on python. Картинка про How to write discord bot on python. Фото How to write discord bot on python

In summary, you’ve created:

Now, you know how to make a Discord bot using the Developer Portal. Next comes the fun stuff: implementing your bot in Python!

How to Make a Discord Bot in Python

discord.py is a Python library that exhaustively implements Discord’s APIs in an efficient and Pythonic way. This includes utilizing Python’s implementation of Async IO.

Begin by installing discord.py with pip :

Creating a Discord Connection

A Client is an object that represents a connection to Discord. A Client handles events, tracks state, and generally interacts with Discord APIs.

Here, you’ve created a Client and implemented its on_ready() event handler, which handles the event when the Client has established a connection to Discord and it has finished preparing the data that Discord has sent, such as login state, guild and channel data, and more.

In other words, on_ready() will be called (and your message will be printed) once client is ready for further action. You’ll learn more about event handlers later in this article.

When you’re working with secrets such as your Discord token, it’s good practice to read it into your program from an environment variable. Using environment variables helps you:

You’ll need to replace with your bot’s token, which you can get by going back to the Bot page on the Developer Portal and clicking Copy under the TOKEN section:

How to write discord bot on python. Смотреть фото How to write discord bot on python. Смотреть картинку How to write discord bot on python. Картинка про How to write discord bot on python. Фото How to write discord bot on python

Install dotenv with pip :

Finally, client.run() runs your Client using your bot’s token.

Great! Your Client has connected to Discord using your bot’s token. In the next section, you’ll build on this Client by interacting with more Discord APIs.

Interacting With Discord APIs

For example, let’s say you wanted to write the name and identifier of the guild that you registered your bot user with to the console.

First, you’ll need to add a new environment variable:

Don’t forget that you’ll need to replace the two placeholders with actual values:

Note: Even though you can be pretty confident at this point in the tutorial that your bot is only connected to a single guild (so client.guilds[0] would be simpler), it’s important to realize that a bot user can be connected to many guilds.

Therefore, a more robust solution is to loop through client.guilds to find the one you’re looking for.

Run the program to see the results:

Great! You can see the name of your bot, the name of your server, and the server’s identification number.

Another interesting bit of data you can pull from a guild is the list of users who are members of the guild:

When you run the program, you should see at least the name of the account you created the guild with and the name of the bot user itself:

These examples barely scratch the surface of the APIs available on Discord, be sure to check out their documentation to see all that they have to offer.

Next, you’ll learn about some utility functions and how they can simplify these examples.

Using Utility Functions

Let’s take another look at the example from the last section where you printed the name and identifier of the bot’s guild:

discord.utils.find() is one utility that can improve the simplicity and readability of this code by replacing the for loop with an intuitive, abstracted function:

find() takes a function, called a predicate, which identifies some characteristic of the element in the iterable that you’re looking for. Here, you used a particular type of anonymous function, called a lambda, as the predicate.

In this case, you’re trying to find the guild with the same name as the one you stored in the DISCORD_GUILD environment variable. Once find() locates an element in the iterable that satisfies the predicate, it will return the element. This is essentially equivalent to the break statement in the previous example, but cleaner.

discord.py has even abstracted this concept one step further with the get() utility:

get() takes the iterable and some keyword arguments. The keyword arguments represent attributes of the elements in the iterable that must all be satisfied for get() to return the element.

In this example, you’ve identified name=GUILD as the attribute that must be satisfied.

Responding to Events

You already learned that on_ready() is an event. In fact, you might have noticed that it is identified as such in the code by the client.event decorator.

But what is an event?

An event is something that happens on Discord that you can use to trigger a reaction in your code. Your code will listen for and then respond to events.

Using the example you’ve seen already, the on_ready() event handler handles the event that the Client has made a connection to Discord and prepared its response data.

There are two ways in discord.py to implement an event handler:

You already saw the implementation using the decorator. Next, take a look at how to subclass Client :

There is no difference between the two implementation styles of events, but this tutorial will primarily use the decorator version because it looks similar to how you implement Bot commands, which is a topic you’ll cover in a bit.

Technical Detail: Regardless of how you implement your event handler, one thing must be consistent: all event handlers in discord.py must be coroutines.

Now that you’ve learned how to create an event handler, let’s walk through some different examples of handlers you can create.

Welcoming New Members

Previously, you saw the example of responding to the event where a member joins a guild. In that example, your bot user could send them a message, welcoming them to your Discord community.

Like before, you handled the on_ready() event by printing the bot user’s name in a formatted string. New, however, is the implementation of the on_member_join() event handler.

await suspends the execution of the surrounding coroutine until the execution of each coroutine has finished.

Now, let’s test out your bot’s new behavior.

First, run your new version of bot.py and wait for the on_ready() event to fire, logging your message to stdout :

Now, head over to Discord, log in, and navigate to your guild by selecting it from the left-hand side of the screen:

How to write discord bot on python. Смотреть фото How to write discord bot on python. Смотреть картинку How to write discord bot on python. Картинка про How to write discord bot on python. Фото How to write discord bot on python

Select Invite People just beside the guild list where you selected your guild. Check the box that says Set this link to never expire and copy the link:

How to write discord bot on python. Смотреть фото How to write discord bot on python. Смотреть картинку How to write discord bot on python. Картинка про How to write discord bot on python. Фото How to write discord bot on python

Now, with the invite link copied, create a new account and join the guild using your invite link:

How to write discord bot on python. Смотреть фото How to write discord bot on python. Смотреть картинку How to write discord bot on python. Картинка про How to write discord bot on python. Фото How to write discord bot on python

First, you’ll see that Discord introduced you to the guild by default with an automated message. More importantly though, notice the badge on the left-hand side of the screen that notifies you of a new message:

How to write discord bot on python. Смотреть фото How to write discord bot on python. Смотреть картинку How to write discord bot on python. Картинка про How to write discord bot on python. Фото How to write discord bot on python

When you select it, you’ll see a private message from your bot user:

How to write discord bot on python. Смотреть фото How to write discord bot on python. Смотреть картинку How to write discord bot on python. Картинка про How to write discord bot on python. Фото How to write discord bot on python

Perfect! Your bot user is now interacting with other users with minimal code.

Next, you’ll learn how to respond to specific user messages in the chat.

Responding to Messages

Let’s add on to the previous functionality of your bot by handling the on_message() event.

on_message() occurs when a message is posted in a channel that your bot has access to. In this example, you’ll respond to the message ’99!’ with a one-liner from the television show Brooklyn Nine-Nine:

The other piece is an important one:

Because a Client can’t tell the difference between a bot user and a normal user account, your on_message() handler should protect against a potentially recursive case where the bot sends a message that it might, itself, handle.

Aside from the potentially spammy nature of this event handler, it also has a devastating side effect. The message that the bot responds with contains the same message it’s going to handle!

So, if one person in the channel tells another “Happy Birthday,” then the bot will also chime in… again… and again… and again:

How to write discord bot on python. Смотреть фото How to write discord bot on python. Смотреть картинку How to write discord bot on python. Картинка про How to write discord bot on python. Фото How to write discord bot on python

That’s why it’s important to compare the message.author to the client.user (your bot user), and ignore any of its own messages.

So, let’s fix bot.py :

Run the program:

Finally, head over to Discord to test it out:

How to write discord bot on python. Смотреть фото How to write discord bot on python. Смотреть картинку How to write discord bot on python. Картинка про How to write discord bot on python. Фото How to write discord bot on python

Great! Now that you’ve seen a few different ways to handle some common Discord events, you’ll learn how to deal with errors that event handlers may raise.

Handling Exceptions

The new raise-exception message handler allows you to raise a DiscordException on command.

Run the program and type raise-exception into the Discord channel:

How to write discord bot on python. Смотреть фото How to write discord bot on python. Смотреть картинку How to write discord bot on python. Картинка про How to write discord bot on python. Фото How to write discord bot on python

You should now see the Exception that was raised by your on_message() handler in the console:

Run bot.py and send the raise-exception message again to view the output in err.log :

Connecting a Bot

A Bot is a subclass of Client that adds a little bit of extra functionality that is useful when you’re creating bot users. For example, a Bot can handle events and commands, invoke validation checks, and more.

As you can see, Bot can handle events the same way that Client does. However, notice the differences between Client and Bot :

Using Bot Commands

In general terms, a command is an order that a user gives to a bot so that it will do something. Commands are different from events because they are:

Let’s take a look at an old event to better understand what this looks like:

There are several important characteristics to understand about using Command :

A Context holds data such as the channel and guild that the user called the Command from.

Run the program:

With your bot running, you can now head to Discord to try out your new command:

How to write discord bot on python. Смотреть фото How to write discord bot on python. Смотреть картинку How to write discord bot on python. Картинка про How to write discord bot on python. Фото How to write discord bot on python

From the user’s point of view, the practical difference is that the prefix helps formalize the command, rather than simply reacting to a particular on_message() event.

How to write discord bot on python. Смотреть фото How to write discord bot on python. Смотреть картинку How to write discord bot on python. Картинка про How to write discord bot on python. Фото How to write discord bot on python

How to write discord bot on python. Смотреть фото How to write discord bot on python. Смотреть картинку How to write discord bot on python. Картинка про How to write discord bot on python. Фото How to write discord bot on python

Keep in mind that all of this functionality exists only for the Bot subclass, not the Client superclass.

Command has another useful functionality: the ability to use a Converter to change the types of its arguments.

Converting Parameters Automatically

Another benefit of using commands is the ability to convert parameters.

Sometimes, you require a parameter to be a certain type, but arguments to a Command function are, by default, strings. A Converter lets you convert those parameters to the type that you expect.

For example, if you want to build a Command for your bot user to simulate rolling some dice (knowing what you’ve learned so far), you might define it like this:

You defined roll to take two parameters:

How to write discord bot on python. Смотреть фото How to write discord bot on python. Смотреть картинку How to write discord bot on python. Картинка про How to write discord bot on python. Фото How to write discord bot on python

Next, you’ll learn about the Check object and how it can improve your commands.

Checking Command Predicates

A Check is a predicate that is evaluated before a Command is executed to ensure that the Context surrounding the Command invocation is valid.

In an earlier example, you did something similar to verify that the user who sent a message that the bot handles was not the bot user, itself:

The commands extension provides a cleaner and more usable mechanism for performing this kind of check, namely using Check objects.

First, you’ll need to create a new member role in the admin. Go into the Discord guild and select the → Server Settings menu:

How to write discord bot on python. Смотреть фото How to write discord bot on python. Смотреть картинку How to write discord bot on python. Картинка про How to write discord bot on python. Фото How to write discord bot on python

Then, select Roles from the left-hand navigation list:

How to write discord bot on python. Смотреть фото How to write discord bot on python. Смотреть картинку How to write discord bot on python. Картинка про How to write discord bot on python. Фото How to write discord bot on python

Finally select the + sign next to ROLES and enter the name admin and select Save Changes:

How to write discord bot on python. Смотреть фото How to write discord bot on python. Смотреть картинку How to write discord bot on python. Картинка про How to write discord bot on python. Фото How to write discord bot on python

Now, you’ve created an admin role that you can assign to particular users. Next, you’ll update bot.py to Check the user’s role before allowing them to initiate the command:

You also use discord.utils.get() to ensure that you don’t create a channel with the same name as an existing channel.

Try it all again, and you should see an error in the Discord channel:

How to write discord bot on python. Смотреть фото How to write discord bot on python. Смотреть картинку How to write discord bot on python. Картинка про How to write discord bot on python. Фото How to write discord bot on python

Great! Now, to resolve the issue, you’ll need to give yourself the admin role:

How to write discord bot on python. Смотреть фото How to write discord bot on python. Смотреть картинку How to write discord bot on python. Картинка про How to write discord bot on python. Фото How to write discord bot on python

With the admin role, your user will pass the Check and will be able to create channels using the command.

Note: Keep in mind that in order to assign a role, your user will have to have the correct permissions. The easiest way to ensure this is to sign in with the user that you created the guild with.

How to write discord bot on python. Смотреть фото How to write discord bot on python. Смотреть картинку How to write discord bot on python. Картинка про How to write discord bot on python. Фото How to write discord bot on python

Also, note that you can pass the optional channel_name argument to name the channel to whatever you want!

Conclusion

Congratulations! Now, you’ve learned how to make a Discord bot in Python. You’re able to build bots for interacting with users in guilds that you create or even bots that other users can invite to interact with their communities. Your bots will be able to respond to messages and commands and numerous other events.

In this tutorial, you learned the basics of creating your own Discord bot. You now know:

To read more about the powerful discord.py library and take your bots to the next level, read through their extensive documentation. Also, now that you’re familiar with Discord APIs in general, you have a better foundation for building other types of Discord applications.

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Creating a Discord Bot in Python

Get a short & sweet Python Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.

How to write discord bot on python. Смотреть фото How to write discord bot on python. Смотреть картинку How to write discord bot on python. Картинка про How to write discord bot on python. Фото How to write discord bot on python

About Alex Ronquillo

How to write discord bot on python. Смотреть фото How to write discord bot on python. Смотреть картинку How to write discord bot on python. Картинка про How to write discord bot on python. Фото How to write discord bot on python How to write discord bot on python. Смотреть фото How to write discord bot on python. Смотреть картинку How to write discord bot on python. Картинка про How to write discord bot on python. Фото How to write discord bot on python

Alex Ronquillo is a Software Engineer at thelab. He’s an avid Pythonista who is also passionate about writing and game development.

Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are:

How to write discord bot on python. Смотреть фото How to write discord bot on python. Смотреть картинку How to write discord bot on python. Картинка про How to write discord bot on python. Фото How to write discord bot on python

How to write discord bot on python. Смотреть фото How to write discord bot on python. Смотреть картинку How to write discord bot on python. Картинка про How to write discord bot on python. Фото How to write discord bot on python

How to write discord bot on python. Смотреть фото How to write discord bot on python. Смотреть картинку How to write discord bot on python. Картинка про How to write discord bot on python. Фото How to write discord bot on python

Master Real-World Python Skills With Unlimited Access to Real Python

How to write discord bot on python. Смотреть фото How to write discord bot on python. Смотреть картинку How to write discord bot on python. Картинка про How to write discord bot on python. Фото How to write discord bot on python

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

Master Real-World Python Skills
With Unlimited Access to Real Python

How to write discord bot on python. Смотреть фото How to write discord bot on python. Смотреть картинку How to write discord bot on python. Картинка про How to write discord bot on python. Фото How to write discord bot on python

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

What Do You Think?

What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know.

Commenting Tips: The most useful comments are those written with the goal of learning from or helping out other students. Get tips for asking good questions and get answers to common questions in our support portal. Looking for a real-time conversation? Visit the Real Python Community Chat or join the next “Office Hours” Live Q&A Session. Happy Pythoning!

A Simple Guide To Making A Discord Bot Using Python

How to write discord bot on python. Смотреть фото How to write discord bot on python. Смотреть картинку How to write discord bot on python. Картинка про How to write discord bot on python. Фото How to write discord bot on python

Learn to program your own little discord bot by following these simple steps!

Discord is a free software initially meant for gamers to create communities and play together. From texting and talking through several channels, to recently sharing your screen or your webcam to your friends, it has become a great way to bring people together. In the last two years, discord has notably picked up in interest from many other means than just gamers, such as education, clubs of shared interest, influencer communities.

How to write discord bot on python. Смотреть фото How to write discord bot on python. Смотреть картинку How to write discord bot on python. Картинка про How to write discord bot on python. Фото How to write discord bot on python

In the left menu of many highly populated discord servers, you will often find users with a blue badge labelled “BOT”. These bots can range from a variety of applications, from server moderation (preventing spam, kicking users that don’t respect the rules, managing roles, and permissions, etc.), to creating music lobbies, and so forth. A bot will be able to do anything a user can do, if not even more, and with the advantage of being automated.

Programming a python bot for discord is fairly easy, but requires at least some basic python knowledge. Without further ado, let’s get into it.

What you will need

You can check your python version by entering the following line in your console :

First, we need to create the bot instance

Connect to your discord account on a browser (this cannot be done through the discord client app). Then head to the developer’s tab.

How to write discord bot on python. Смотреть фото How to write discord bot on python. Смотреть картинку How to write discord bot on python. Картинка про How to write discord bot on python. Фото How to write discord bot on python

2. On the left, go on the “Bot” tab and click “Add Bot”, and confirm by clicking “Yes, Do it!”

How to write discord bot on python. Смотреть фото How to write discord bot on python. Смотреть картинку How to write discord bot on python. Картинка про How to write discord bot on python. Фото How to write discord bot on python

3. Copy the token and save it someplace secure and safe, you will need it later. (preferably in a token.txt file). Check if “Public bot” is enabled and “Requires oauth2” disabled:

How to write discord bot on python. Смотреть фото How to write discord bot on python. Смотреть картинку How to write discord bot on python. Картинка про How to write discord bot on python. Фото How to write discord bot on python

Then, we need to invite your bot on a server.

How to write discord bot on python. Смотреть фото How to write discord bot on python. Смотреть картинку How to write discord bot on python. Картинка про How to write discord bot on python. Фото How to write discord bot on python

2. Scroll down to the “bot permissions” menu that appeared below, and tick whatever boxes apply to what you’ll like your bot to be allowed to do. I recommend you tick at least “View Channels”, “Send Messages” and “Add Reactions”.

How to write discord bot on python. Смотреть фото How to write discord bot on python. Смотреть картинку How to write discord bot on python. Картинка про How to write discord bot on python. Фото How to write discord bot on python

3. Once you’re happy with your choices, copy the link generated under “scopes”. Paste it in your browser to invite it to one of your servers. Note that in order to invite a bot, a user needs to have permission to “manage server”.

Programming the actual bot!

Installing the discord.py module

Then, we need to install the discord module in python. If you are on Windows, enter this line in your console :

For Linux or macOS users :

All set! We can now start programming!

Create a new *.py file in your favourite script editor. The first thing you need to do is import the discord library.

Next, remember the discord token? We’re gonna be needing it for the bot to actually run. Since discord.py bots use async to run, it means it expects defined events as triggers to reactions. At the very end of your script, you’ll need to add :

While this is a perfectly fine and simple way to do it, you might want to try and hide that token away, especially if you plan on posting your code on Github, for example. Let’s paste the token in a token.txt file, and assign it to a variable like this :

That way, you can easily edit the token at any time on the *.txt file, and it doesn’t appear on your code. Note that without the directory path mentioned in the open() function, the file has to be in the same folder as the *.py file.

Next, commands!

Basically, we tell the bot to look out for a “.ping” command and pass the context ( ctx, which for future reference is always passed first). On that event, it will answer a message in the channel the command was posted, which is why we needed to pass the context. Let’s run it and type the command in chat (make sure the bot has permission to read and post messages in the channel). This is how the interaction would look like :

How to write discord bot on python. Смотреть фото How to write discord bot on python. Смотреть картинку How to write discord bot on python. Картинка про How to write discord bot on python. Фото How to write discord bot on python

Great! Now, let’s have a little fun. We’re going to make the bot give a quote randomly. We’re going to create a quote.txt, and fill it with a few select quotes in each line. We’ll also need the random module and set the seed to None, and let it choose a line randomly.

How to write discord bot on python. Смотреть фото How to write discord bot on python. Смотреть картинку How to write discord bot on python. Картинка про How to write discord bot on python. Фото How to write discord bot on python

Make sure to test the command a few times to make sure it’s working as intended.

This can be used for pretty much anything that you want to generate randomly, like movie quotes, your favourite inspirational quotes, or if you want a random nickname generator. Anything goes as long as you edit the text file accordingly!

Make your bot warn you when errors occur!

A more serious and practical thing to do is making your bot look for error events. That way, it will warn the user if there was an issue passing the command, or if there is a missing argument for example. By passing context and the error, the bot can answer with the error as part of the message :

How to write discord bot on python. Смотреть фото How to write discord bot on python. Смотреть картинку How to write discord bot on python. Картинка про How to write discord bot on python. Фото How to write discord bot on python

That’s right, up next is a command that will inform the users of all of your bot’s commands. Since discord has a default help command, we’ll need to remove it to be able to replace it. Make sure you describe them in a short, yet precise way. We’re gonna be using discord embeds.

How to write discord bot on python. Смотреть фото How to write discord bot on python. Смотреть картинку How to write discord bot on python. Картинка про How to write discord bot on python. Фото How to write discord bot on python

You can set the colour to anything, and the contents of embeds are quite customisable. Embeds can include a title, links, a footnote, a timestamp, you can even embed pictures!

Other events and interactions: reacting to a message!

Now that we have a basic understanding of commands, let’s have a look at other events, such as messages. For this tutorial, we’ll make the bot react with an emoji on each message posted by passing a Unicode string. Let’s use the “Eyes” emoji :

How to write discord bot on python. Смотреть фото How to write discord bot on python. Смотреть картинку How to write discord bot on python. Картинка про How to write discord bot on python. Фото How to write discord bot on python

Of course, the bot can react with any emojis, even with custom emojis! In this example, there is no message filtering involved, so the bot would react to any message. If you’d like a more practical application of this, you could limit the reaction to messages containing a specific term, like this :

Final touches and our bot is ready!

Let’s add a few print() functions for console debugging, and voilà! Congratulations on making your first discord.py bot! Here is the complete and final script :

You can now edit the script as you please to make the bot fit your — or your server’s — needs. There are a lot of things you can do with the discord API, so don’t be afraid to test out some things!

For the bot to run 24/7, you could host it on your computer, but it’s not the most ideal way. You can find plenty of free or semi-free hosting services such as the EC2 on Amazon Web Services, or with Google, for example. Alternatively, if you own a Raspberry Pi and are okay with keeping it running, you could host it on that, and make the *.py script as a service so it runs on startup!

Создаём Discord-бота на Python

Всем привет, сегодня мы напишем Discord-бота на Python и discord.py + бонусом посмотрим на примеры ботов. Приступим 🙂

Перед работой

Перед тем, как начать, вам нужны:

Для установки discord.py воспользуйтесь пакетным менеджером:

Создаём нашего бота

Перейдите на Developer Portal и нажмите на New application.

How to write discord bot on python. Смотреть фото How to write discord bot on python. Смотреть картинку How to write discord bot on python. Картинка про How to write discord bot on python. Фото How to write discord bot on python

Вы создали своё приложение, на странице приложение перейдите в Bot >> Add Bot и создайте своего Discord-бота.

Сохраните токен бота! Дальше он нам понадобится!

How to write discord bot on python. Смотреть фото How to write discord bot on python. Смотреть картинку How to write discord bot on python. Картинка про How to write discord bot on python. Фото How to write discord bot on python

Если всё прошло успешно, поздравляю, половина дела сделана 😀

Добавление бота на сервер

Теперь можно добавить бота на сервер.

Перейдите в OAuth2 >> URL Generator, в Scopes выбираем Bot и ниже — права бота, копируем сгенерированный URL. Вставляем в браузер, и добавляем на наш сервер.

How to write discord bot on python. Смотреть фото How to write discord bot on python. Смотреть картинку How to write discord bot on python. Картинка про How to write discord bot on python. Фото How to write discord bot on python

Эхо-бот

Напишем традиционного эхо-бота, и разберём каждую строчку кода.

How to write discord bot on python. Смотреть фото How to write discord bot on python. Смотреть картинку How to write discord bot on python. Картинка про How to write discord bot on python. Фото How to write discord bot on python

Нужные нам импорты.

Вспомогательный словарь config в котором храним токен и префикс команд (далее расскажу зачем нужен префикс команд).

Создаём нашего бота, в аргументе передаём префикс.

Декоратор, предназначенный для обработки событий, подробнее здесь.

Создаём асинхронную функцию, с параметром ctx, представляет из себя сообщение.

Проверка, не является ли автор сообщения нашим Discord-ботом. Дело в том, что если бот отправит сообщение, это будет новым событием, и тогда получается цикл.

Отвечаем на сообщение (ctx.reply), в аргументы передаём сообщение (ctx.content).

Запускаем нашего бота, в аргументы передаём токен бота.

How to write discord bot on python. Смотреть фото How to write discord bot on python. Смотреть картинку How to write discord bot on python. Картинка про How to write discord bot on python. Фото How to write discord bot on python

Надеюсь вы разобрались с кодом, и мы можем переходить далее.

Обработка команд

Перед тем, как обрабатывать команды, нам пригодится наш префикс.

How to write discord bot on python. Смотреть фото How to write discord bot on python. Смотреть картинку How to write discord bot on python. Картинка про How to write discord bot on python. Фото How to write discord bot on python

Декоратор обработки команд

Асинхронная функция rand

Отвечаем на сообщение, в аргументы передаём случайное число от 0 до 100

Источники информации:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *