How to make discord bot on python

How to make discord bot on python

How to make a simple Discord bot in Python

So, you use Discord. You’ve probably seen tons of bots around. These bots usually supplement the Discord experience by providing cool new features such as a money system, music, and moderation abilities. Of course, we will not go over how to implement all of this in this tutorial, but this will be a good start to making Discord bots in Python.

Getting Ready

First of all, make sure you are using Python 3.4.3–3.6.6, since those are the only versions that the Discord library currently supports. To check your Python version, run this command in the command prompt like so:

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

Once you’ve made sure you have the right version of Python, you need to import the Discord library, discord.py, using pip. Just enter the command “pip install discord”. I already have it installed, but it should work perfectly for you.

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

Creating Our Bot

Now, let’s get on to creating the bot itself. Go to https://discordapp.com/developers/applications/me, log in, and you should see a button to create a new app. Click on that button.

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

Afterwards, you should see a screen where you can enter the name of your bot and set an image for your bot. These are the only two features you really need to worry about. Set a name and picture for your bot, whatever you want, and you’re good to go.

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

Okay, now you should be on the main page for your bot application. Scroll down a bit and you should see a blurb asking you if you want to turn your application into a bot user. Obviously, this tutorial is for making a bot, so you should do it (if you didn’t, this tutorial wouldn’t work).

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

Alright, so now you should see features that are exclusive to bots. Click the “click to reveal” to reveal the token of your bot. Don’t give this out to anyone (or else they would be able to manipulate your bot!) Check the public bot checkbox if you want other users to be able to add your bot to their server besides you.

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

Coding Our Bot

Next, we need to establish our Discord client. The bot client that is connecting to discord.

Now, this is where the fun begins. Within the discord.py library, there are certain events that the bot is able to respond to, including when a message is sent and when the bot is ready. Take this example:

Now, whenever the bot is ready for use after startup, it will print out “The bot is ready!”. It runs anything that is in the function. Cool, right? We can use this to do other things, too, such as set a play status for the bot, as so:

This may look a little bit confusing, but hear me out. We have to put “await” in front of it since it is a coroutine, which basically allows multi-tasking so the bot can respond to different events at the same time. Got it? So, when we call the change_presence method on the Discord client, it changes the presence of the client to show that it is playing the game “Making a bot”, since we created a Game object with the name “Making a bot”.

Next, we can get on to actually making bot commands. We detect if a message is sent with this function that takes the parameter “message”, which will be equal to the message that was sent. We don’t want the bot to be able to respond to itself in any circumstances, so if the author of the message is equal to the client, we stop the function.

We can make some commands that our bot can respond to now. For starters, we’ll make a really simple thing, so if we say “Hello” the bot will say “World” back.

First, we check if the content of the message is equal to “Hello”. If it’s anything else, the bot will not respond with “World”. Then, the send_message method takes two parameters, the channel to send the message to, and the message to send (in the form of a string). The bot awaits until it sends this message, then looks for another response. Amazing! We just made our first bot using discord.py, but how can we connect it to our server now? Well, there’s one more piece of code we forgot.

At the end of the code, you MUST add the client.run() function, which runs the bot. It only takes one parameter, which is your bot’s token, which you should have seen earlier. Put this token in, and your bot should start up when you run the program!

Using Our Bot

Great, we have our code all done now, but how are we supposed to add this bot to the server? To do this, we need to go back to the Discord developers page. Find the little button that says “OAuth2 URL” and click it.

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

If all the bot is doing is sending messages, leave the permissions alone. However, if you want your bot to have permissions when it is added, check off the permissions you want. Do not change the Client ID, as it should already be filled in for you. All you have to do is click the copy button, and you have the link to invite the bot to your server!

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

Great, now we have our working bot in our server! Check it, out! Pretty cool, right? (Thanks to mat for starring in my bot tutorial).

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

Oh, yeah! The bot also shows the playing status, just like we wanted it to!

Создание Discord-бота на Python. Часть 1

Версия Python: 3.8.2
Версия discord.py: 1.3.3

Приветствую, хабровчане и другие пользователи интернета. Сегодня я начну цикл статей, посвящённых созданию Discord-бота с помощью библиотеки discord.py. Мы рассмотрим создание как и примитивного бота, как и «продвинутого» бота с модулями. В этой статье мы сделаем стандартную команду и ещё одну небольшую команду. Начнём!

Создание бота и получение токена

Для того, чтобы добавить бота на сервер нужно создать свое приложение и во вкладке General Information скопировать Client ID.

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

Здесь заменяем CLID на ранее скопированный Client ID.

Во вкладке Bot создаём бота и копируем токен.

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

Написание кода

Устанавливаем саму библиотеку.

Создаём файл config.py (так удобнее), и создаём там словарь.

Создаём main-файл, название может быть любое.
Импортируем библиотеки и наш файл конфига:

Создаём «тело» бота, название может быть любое:

Начинаем писать основной код.

В конце запускаем бота с помощью:

Должно получится так:

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

Бонусный туториал!

Сделаем вывод случайных картинок с лисами
Для этого импортируем еще пару библиотек:

Приступим к написанию команды.

Должно получится так:

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

Конец

На этом 1 часть закончена. Скоро будет опубликована 2 часть.

4Kaylum / DiscordPy Tutorial.md

Writing a Discord bot with Discord.py

Hey one, hey all, and welcome to a basic Discord bot writing tutorial. This is a basic tutorial that doesn’t cover coding in general, but rather how to work with the Discord.py (v1.0.0a) library and how to write a simple bot with it. General help can be found on the Discord API guild and in the documentation.

This tutorial assumes some prior knowledge of programming, and assumes you already have Python3.5 (and Pip) or later installed and added to your PATH.

With that, let’s get to it.

As with most Python libraries, Discord.py can be installed with Pip. However, since we’re using the rewrite (alpha) version, you also need to have Git SCM installed, so be sure to do that. After you have that installed (and, optionally, you’re in whatever venv you want to use) just run the command

This will install Discord.py.

After we have that installed, we need to grab a bot token from Discord. A «token» is a string that you send to a server to authenticate with.

Before you close that page, be sure to review whether you want your bot to be public or not. If the box is ticked, then anyone with the invite link will be able to add your bot to their guild, but if left unticked, only you can add the bot to any given guild.

Adding your Bot

It’s fairly important that you add your bot to the guild you want to test it on, and that’s simple enough to do. On your application page, you should be able to see «client ID» near the top. Copy that value, and paste it into this website (officially recommended by Discord). This allows you to tick the permissions you want your invite link to have, and then spits it out to you nicely at the bottom for you to share with others, or use so you can add it to your own servers. Having done that, let’s get the actual programming underway

Finally, we can get to some coding.

Start off by making a new file. It doesn’t matter what the name of it is, provided it’s not «discord», since we’ll be importing that in a second. From there, you can start to write your bot.

This snippet, though short, is a basic bot made in Python, and when run will bring your bot online. It won’t do anything (because you’ve not told it to yet), but it is a valid bot

The basis of Discord.py is to have functions that are triggered by events. These events are all documented here, but I’ll cover a couple of them now.

It’s here that some people will start to see how to make commands. What you would do is compare the message’s content with another string (the command name) and then perform actions based on that. Many other libraries are laid out like that, but Discord.py includes a syntax for writing commands in a much nicer way.

It’s now that we’ll start writing commands. There will be two included in this tutorial: a «ping» command, and an «echo» command.

The «ping» command on some bots will just spit the word «pong» back out at you, but we’re going to write it so it gives you the latency of the bot instead. Pay attention to the difference between how commands are written and how events are written.

Looking at it, it’s pretty simple, right?

The echo command is slightly more complicated, since it needs to read what the user said. Regardless, there’s only a couple of differences in the command than before.

Full Bot and its Layout

Having written these commands, you might be wondering how you include them in your main program. The answer is simple: it needs to be after you define the bot variable, and before you turn the bot on (with bot.run ). As such, a full program with the examples before could be seen as such:

When saved and run, this will act as a functional bot for you!

Building a Discord Bot in Python

If you are familiar with online communities and if you are a part of one or you own one, you must have heard about discord and in discord, you may have seen bots managing those communities. So in this article, we are going to set up our discord developer portal account and will create a discord bot. A minimal bot with basic functionalities and if you want you can always extend the functionalities of this bot according to your needs.

What is Discord?

Discord is a free chat app that provides different chat functionalities such as voice, video, and text chat it is used by millions of people around the world for professional as well as fun use.

People create communities referred to as servers in discord and other people can join these servers to hangout there to meet new people and talk about their interests. Discord also offers functionality to create private servers where only invited people can join using these private servers people can have a private talk with their close ones.

Discord Servers are filled with channels created by the owner they can be text channels, audio or video channel. These channels are used to talk about specific topics on the server.

What are Discord Bots?

Discord is used by more than 10 million people daily using these stats we can clearly see people’s interest in communities and discord is growing. People are exploring and joining new servers.

As the popularity of servers grows people tend to join that server more once the number of members grows it becomes hard for admins to manage the server this is where bots come into play. There are several tasks admin bots can perform to enhance the user experience on the server. Some of these tasks are

And the list goes on. Admins of huge discord communities always prefer enabling multiple bots on their server, after following this tutorial you can also create your own discord bot, let’s get started.

Creating a Discord Server

First and foremost we need to have a dedicated server where we are going to setup our bot. This bot will work on a single channel on this server. To create a server you need to have a discord account if you don’t have one yet you can create one by simply going to https://discord.com/.

Step 1: Click on add server (plus) button on the left sidebar this will open create server interface. Choose the template of your server.

Creating a Server

Step 2: Choose if you using this server for fun or community.

Additional server info

Step 3: Choose a good and catchy name for your server if you are using this for the community you can simply give the name of your community or business.

Step 4: You Server is now created

Creating a Channel on Server

Now we need to create a channel where this bot will be active, this bot will only respond on this channel.

Step 1: Click on add in text channels list.

Creating a channel

Step 2: Choose the type of channel as a text channel and give your channel a name

Channel Name and type

Step 3: Channel is created

But hey, did you know that GeeksforGeeks also has its own Discord server?
No? Well, your day just got a lot better! Click here to join the ever-growing tech community and be a part of GEEK ARMY.

Creating A Bot

Now that we have our account with the server ready we can go ahead and create our first bot on the discord developer portal. The discord developer portal is a platform provided by discord for people who wants to extend the capabilities of discord and use it for building more cool stuff, one of the examples is creating bots.

Step 1: Login in Portal: Go to https://discord.com/developers/applications and login with your discord account in which the server you want to build a bot for is created.

Login with Discord account

Step 2: Application refers to new functionality. For example, Bot. Click on new Application to initialize your first bot, choose a name for your application. Remember the name of the application will be the name of your bot.

Create An Application

Step 3: Creating a Bot click on Bot in the left sidebar and click on Add Bot.

Step 4: A popup will open which will ask you if you really want to add a bot click on Yes, Do it.

Verify you want to add bot

Step 5: Copy the token with the COPY button given below this token is used to authorize programs with discord.

Note: Never Share your token with anybody!

Copy Auth Token

Customizing and Authorizing Bot

Our bot is created it’s time to give permissions and define scopes of the bot. Permission refers to what our bot can do on the server, for example, sending messages. Scope refers to what role the bot will perform.

Step 1: Click on OAuth2 and click on URL Generator you will see multiple checkboxes referring to different scopes. For this bot, we are going to use bot only scope click on Bot checkbox.

Step 2: Next checkboxes are permission for our box. We are going to give this bot permission to send and reply to messages so check all the boxes related to that. You can always change these permissions later and generate a new URL.

Note: If you want to code slash commands, make sure to choose applications.commands as well in Step 1.

Give Permissions to bot

Step 3: Scroll down and you can see a URL generated for the bot click on the copy to copy this URL.

Step 4: Paste copied URL in a new tab here we are going to authorize our bot with the server. Choose the server we created earlier and click on continue.

Give Server name

Step 5: Here you will see the permissions of the bot. If you want you can edit these, click on Authorise

Step 6: Verify that you are a human with a captcha and the bot should be authorized now.

Step 7: Go to the server and you can see the name of the bot appearing in the list of offline people.

Bot appearing in Server

Writing Code for Bot

In this section, we are going to write python code for our discord bot.

Step 1: We are going to create .env file to store the renewal key for our bot we copied above, .env file will protect our credentials when we will host our code somewhere. First, create a .env named file in your project folder and then insert the following code.

Step 2: Importing modules

Create a new python file for main bot code and name it as you want and import necessary modules.

Создание бота на основе discord.py. Часть 1

Введение

Это первая статья про создание бота для Discord. В конце статьи находятся ссылки на следующие части, со временем они будут дополняться. Статьи следуют друг за другом, без каких-либо «информационных дыр». Если нашли опечатку или неточность, отпишите о проблеме в комментариях или в личных сообщениях, максимально оперативно всё поправим! А теперь переходим непосредственно к созданию бота.

В данной части

Создание тестового сервера

Включение режима разработчика

Создание приложения и получение токена

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

Установка библиотеки discord.py

Первые строчки кода

Создание сервера

Гайд будет максимально подробный, поэтому и начинать будем с создания тестового сервера. Зачем он нужен? Лишь для вашего удобства и безопасности, если у вас уже есть большой сервер, тем более не стоит сразу добавлять на него разрабатываемого бота. Никто не защищён от багов и дыр в безопасности.

Заходим в дискорд

Слева видим список серверов, листаем в самый низ до кнопки «Создать сервер«.

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

Создаём сервер по любому из предложенных шаблонов.

Включаем режим разработчика

Это необязательно, но очень желательно. В режиме разработчика появляются некоторые полезные элементы для удобства разработки, например, в меню пользователя появляется пункт, который позволяет скопировать его ID.

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

Чтобы включить этот режим, заходим в настройки.

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

В категории «Настройки приложения» ищем «Расширенные«.

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

И включаем режим разработчика.

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

Получение токена

Для начала нам нужно зайти на страницу создание приложений и нажать New Application.

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

После этого вам предложат назвать ваше приложение (Потом можно будет изменить).

How to make discord bot on python. Смотреть фото How to make discord bot on python. Смотреть картинку How to make discord bot on python. Картинка про How to make discord bot on python. Фото How to make discord bot on pythonСоздание приложени

После создания, попадаем на страницу настройки приложения. В меню выбираем «Bot«.

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

На данной странице нажимаем на «Add Bot«. Скопируем токен и сохраним его.

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

Так же, сразу можно выдать дополнительные разрешения боту, чтобы потом об этом не задумываться.

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

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

В меню ищем пункт OAuth2 –> URL Generator.

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

В поле SCOPES выбираем bot и applications.commands. В появившемся ниже поле выбираем Administrator, это более удобно для тестирования. Но когда бот будет работать в продакшене, лучше выставлять только те права, которые правда нужны, потому что никто не защищён от потери токена, а с правами администратора это может стать очень большой проблемой.

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

Копируем появившеюся ниже ссылку и вставляем в адресную строку браузера. Если у вас не выполнен вход в браузере, его необходимо произвести. После чего выбираем тестовый сервер из списка и нажимаем «Продолжить» и далее «Авторизовать«.

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

Ура! Наш бот на тестовом сервере!

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

Установка библиотеки

Для начала нужно установить python, данный этап не расписан, но желательно установить версию 3.10 (Последняя версия на момент написания 3.10.5). Если у вас Windows, для проверки можете использовать следующую команду

В ответ получите версию вашего python. Устанавливать будем не стабильную, а разрабатываемую версию, для этого пропишем следующую команду. (Это можно делать уже внутри проекта). Хотя некоторые IDE устанавливаю git вместе с собой, можете скачать его отдельно.

Если всё же хотите установить стабильную, релизную версию, пропишите следующую команду.

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

Первые строчки кода

Пришло время писать код! Программирование в статьях будет происходить в PyCharm, хоть это и довольно тяжёлая IDEA, она удобная и бесплатная для студентов.

Не советую создавать проект через внутренний интерфейс, может появиться множество ненужных папок и файлов, вместо этого создадим папку проекта вручную и откроем как пустой проект.

Для этого заходим в PyCharm, далее File –> Open.

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

P.s. Не обращайте внимания на другую тему IDE.

В появившемся окне ищем созданную папку, выбираем её и нажимаем «Ok«. Обратите внимание на то, что нужно просто нажать по папке, а не проваливаться в неё.

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

Если PyCharm автоматически не создал main.py, создайте его вручную.

Вставляем код ниже и запускаем.

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

В консоли вы увидите логи запуска бота. Они могут быть красными, не бойтесь, сначала прочитайте сами сообщения, они скорее, всего просто информационные.

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

Идём в дискорд и используем нашу первую команду.

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

Немного объясним данную структуру. Поскольку это обычная команда, вся информация хранится в ctx(Переменная одноимённого класса). Она имеет следующие поля:

И следующие команды:

Если вы знакомы с синтаксисом языка, то данный список можно получить с помощью встроенной функции dir.

На более правильно прочитать документацию про Context.

Заключение

И небольшое примечание. Статьи строятся на основании того, что у вас есть опыт и знания программирования на python.

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

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

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