How to create discord bot

How to create discord bot

Создание простого Discord бота с помощью библиотеки discord.py

Асинхронная библиотека discord.py содержит все что нужно для бота, с помощью нее даже можно работать с голосовыми каналами сервера. В этой статье я расскажу как создать простенького бота для вашего discord сервера.

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

Получение токена и Client ID для вашего бота

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

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

А в разделе настроек создать бота и скопировать его токен. Задача не сложная, думаю все с этим справятся.

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

Собственно пишем бота

Устанавливаем discord.py с помощью pip:

После успешной установки создаем файл bot.py, где будем писать бота.

Импортируем все необходимое:

Создаем переменную с вашим токеном, про который я писал выше:

Создаем тело бота:

Для начала сделаем простенькую команду, аргумент которой бот будет просто пересылать:

И в конце запускаем бота с вашим токеном:

В итоге должно получится вот такое:

Теперь необходимо добавить бота на сервер. Сделать это можно с помощью ссылки:

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

Теперь можно запускать бота:

После нескольких секунд, можно заметить его в сети:

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

И наконец-то попробовать отправить команду:

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

Заключение

Вот так можно легко запустить у себя на сервере бота. Как можно заметить библиотека делает практически все за тебя и остается только добавлять свой функционал с использованием python. В следующий раз я покажу как следить за событиями, подключатся к голосовым каналам (избегая проблем с linux и Windows), использовать роли и права участников и другое.

Making Your First Bot with Discord.Net

One of the ways to get started with the Discord API is to write a basic ping-pong bot. This bot will respond to a simple command «ping.» We will expand on this to create more diverse commands later, but for now, it is a good starting point.

Creating a Discord Bot

Before writing your bot, it is necessary to create a bot account via the Discord Applications Portal first.

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

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

Confirm the popup.

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

Adding your bot to a server

Bots cannot use invite links; they must be explicitly invited through the OAuth2 flow.

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

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

Scroll down further to Bot Permissions and select the permissions that you wish to assign your bot with.

This will assign the bot with a special «managed» role that no one else can use. The permissions can be changed later in the roles settings if you ever change your mind!

Open the generated authorization URL in your browser.

Click on Authorize.

Only servers where you have the MANAGE_SERVER permission will be present in this list.

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

Connecting to Discord

If you have not already created a project and installed Discord.Net, do that now.

Async

To establish an async context, we will be creating an async main method in your console application.

As a result of this, your program will now start into an async context.

Warning

If your application throws any exceptions within an async context, they will be thrown all the way back up to the first non-async method; since our first non-async method is the program’s Main method, this means that all unhandled exceptions will be thrown up there, which will crash your application.

Discord.Net will prevent exceptions in event handlers from crashing your program, but any exceptions in your async main will cause the application to crash.

Creating a logging method

Before we create and configure a Discord client, we will add a method to handle Discord.Net’s log events.

To allow agnostic support of as many log providers as possible, we log information through a Log event with a proprietary LogMessage parameter. See the API Documentation for this event.

If you are using your own logging framework, this is where you would invoke it. For the sake of simplicity, we will only be logging to the console.

You may learn more about this concept in Logging Events/Data.

Creating a Discord Client

Finally, we can create a new connection to Discord.

Since we are writing a bot, we will be using a DiscordSocketClient along with socket entities. See Terminology if you are unsure of the differences. To establish a new connection, we will create an instance of DiscordSocketClient in the new async main. You may pass in an optional DiscordSocketConfig if necessary. For most users, the default will work fine.

Before connecting, we should hook the client’s Log event to the log handler that we had just created. Events in Discord.Net work similarly to any other events in C#.

Next, you will need to «log in to Discord» with the LoginAsync method with the application’s «token.»

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

Pay attention to what you are copying from the developer portal! A token is not the same as the application’s «client secret.»

We may now invoke the client’s StartAsync method, which will start connection/reconnection logic. It is important to note that this method will return as soon as connection logic has been started! Any methods that rely on the client’s state should go in an event handler. This means that you should not directly be interacting with the client before it is fully ready.

Finally, we will want to block the async main method from returning when running the application. To do this, we can await an infinite delay or any other blocking method, such as reading from the console.

Important

Your bot’s token can be used to gain total access to your bot, so do not share this token with anyone else! You should store this token in an external source if you plan on distributing the source code for your bot.

In the following example, we retrieve the token from a pre-defined variable, which is NOT secure, especially if you plan on distributing the application in any shape or form.

We recommend alternative storage such as Environment Variables, an external configuration file, or a secrets manager for safe-handling of secrets.

The following lines can now be added:

At this point, feel free to start your program and see your bot come online in Discord.

Warning

Getting a warning about A supplied token was invalid. and/or having trouble logging in? Double-check whether you have put in the correct credentials and make sure that it is not a client secret, which is different from a token.

Warning

For your reference, you may view the completed program.

Building a bot with commands

To create commands for your bot, you may choose from a variety of command processors available. Throughout the guides, we will be using the one that Discord.Net ships with. Introduction to the Chat Command Service will guide you through how to setup a program that is ready for CommandService.

For reference, view an annotated example of this structure.

It is important to know that the recommended design pattern of bots should be to separate.

This page was last modified at 04/28/2022 19:48:11 +08:00 (UTC).

Создание Discord-бота, используя библиотеку discord.js | Часть №1

Введение

В этой статье я подробно расскажу о том, как работать с библиотекой discord.js, создать своего Discord-бота, а также покажу несколько интересных и полезных команд.

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

Начало работы

Если вы уже знакомы с приведёнными ниже материалами, — смело можете пролистать этот раздел.

Для начала работы с кодом нам нужно установить среду разработки, это может быть:

Среда разработки выбирается по удобству использования и практичности, она у вас может быть любая, но мы рассмотрим её на примере Visual Studio Code, так как она является одной из самых приемлемых для новичков, а также для опытных программистов.

Для установки переходим по этой ссылке.

How to create discord bot. Смотреть фото How to create discord bot. Смотреть картинку How to create discord bot. Картинка про How to create discord bot. Фото How to create discord bot
Выбираем свою операционную систему и запускаем скачивание.

Для создания бота мы используем среду выполнения node.js. Для её установки нам необходимо перейти на этот сайт.

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

На данный момент нас интересует версия долгосрочной поддержки (LTS), скачиваем её.

В Visual Studio Code присутствует возможность устанавливать расширения.
Для этого, кликните по отмеченной ниже иконке.

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

В открывшемся окне вписываем название название/идентификатор нужного нам расширения, после чего устанавливаем его.

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

Из полезных расширений могу отметить:

Создание бота

Теперь, когда вы установили все нужные компоненты, мы можем приступить к созданию самого бота.

Здесь всё просто. Переходим на портал разработчиков и нажимаем на кнопку с надписью «New Application» — она находится в правом верхнем углу.

В открывшемся окне вписываем имя бота, после чего, нажимаем на кнопку с надписью «Create».

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

На этой странице мы можем изменить имя бота, загрузить для него иконку, заполнить описание.

Теперь наша задача — воплотить бота в жизнь. Для этого переходим во вкладку «Bot».

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

Нажимаем на кнопку с надписью «Add Bot» и воплощаем бота в жизнь.

Поздравляю! Вы создали аккаунт для вашего бота. Теперь у него есть тег, токен, ник и иконка.

Подготовка к написанию кода

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

Первым делом создаём папку, после чего открываем её в VS Code (Файл > Открыть папку) / (Ctrl + K Ctrl + O)

Далее нам нужно открыть терминал (Терминал > Создать терминал) / (Ctrl + Shift + `)

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

Теперь мы должны создать файл с неким «описанием» нашего бота, сделаем это через терминал.

Вписываем данную строку в терминал и нажимаем Enter:

После каждой появившейся строки нажимаем Enter или вписываем свои значения.
Значения в этом файле можно будет изменить в любой момент.

Далее, мы должны поочерёдно вводить в терминал эти строки:

«Install» также можно сокращать в «I», но необязательно.

Итого, если вы следовали инструкциям и всё сделали правильно, в вашей папке должны были появиться 3 объекта:

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

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

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

Существует множество вариантов для его написания: используя один файл, два, несколько, и т.д

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

Но не волнуйтесь, весь код вам писать не придётся.

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

Мы можем сделать это двумя способами:

Разберём хранение параметров в отдельном файле.

Итак, создаем файл config.json

Вставляем в него следующий код:

* Для получения токена зайдите на портал разработчиков, перейдите во вкладку «Bot» и скопируйте его.

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

* Самым распространённым среди разработчиков префиксом является !

Далее нам нужно создать файл bot.js и вставить в него данный код:

Теперь создаём файл comms.js, в нём будут сами команды.

В нём должен быть следующий код:

Чтобы добавить больше команд — просто объявляйте больше функций и добавляйте их в список, например:

И вот, мы вышли на финишную прямую!

Осталось всего ничего — запустить бота.

Для этого открываем терминал и вставляем в него следующую строку:

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

Готово! Бот запущен и вы можете им пользоваться, ура!

Чтобы пригласить бота на свой сервер, воспользуемся нам уже известным порталом разработчиков.

Перейдём во вкладку OAuth2, пролистаем чуть ниже, выберем «Bot» и отметим нужные боту привилегии.

Теперь осталось скопировать ссылку-приглашение и добавить бота на свой сервер.

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

Существует два способа:

Для этого, сначала мы должны скопировать ссылку-приглашение.
После чего перейти в файл bot.js и вставить данную строчку кода сюда:

Итоговый код должен быть таким:

Чтобы указать несколько привилегий, мы должны перечислить их в квадратных скобках, через запятую:

* Все привилегии указываются заглавными буквами

Список доступных привилегий:

ADMINISTRATOR
CREATE_INSTANT_INVITE
KICK_MEMBERS
BAN_MEMBERS
MANAGE_CHANNELS
MANAGE_GUILD
ADD_REACTIONS
VIEW_AUDIT_LOG
PRIORITY_SPEAKER
STREAM
VIEW_CHANNEL
SEND_MESSAGES
SEND_TTS_MESSAGES
MANAGE_MESSAGES
EMBED_LINKS
ATTACH_FILES
READ_MESSAGE_HISTORY
MENTION_EVERYONE
USE_EXTERNAL_EMOJIS
VIEW_GUILD_INSIGHTS
CONNECT
SPEAK
MUTE_MEMBERS
DEAFEN_MEMBERS
MOVE_MEMBERS
USE_VAD
CHANGE_NICKNAME
MANAGE_NICKNAMES
MANAGE_ROLES
MANAGE_WEBHOOKS
MANAGE_EMOJIS

Я не советую вам из привилегий выбирать только ADMINISTRATOR, поэтому лучше указать только те привилегии, которые бот действительно использует для корректной работы

Полезные и интересные команды

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

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

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

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

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

Не стоит пугаться большого кода, здесь всё предельно просто.

Заключение

Вот и подошла к концу первая часть обучения, как вы могли заметить, создать бота, используя библиотеку discord.js очень просто.

Итого, из этой статьи мы выяснили:

Надеюсь, что вам понравилась моя статья и вы узнали из неё что-то новое.

Python Discord Bot Tutorial – Code a Discord Bot And Host it for Free

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

This tutorial will show you how to build your own Discord bot completely in the cloud.

You do not need to install anything on your computer, and you do not need to pay anything to host your bot.

We are going to use a number of tools, including the Discord API, Python libraries, and a cloud computing platform called Repl.it.

There is also a video version of this written tutorial. The video is embedded below and the written version is after the video.

How to Create a Discord Bot Account

In order to work with the Python library and the Discord API, we must first create a Discord Bot account.

Here are the step to creating a Discord Bot account.

1. Make sure you’re logged on to the Discord website.

3. Click on the “New Application” button.

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

4. Give the application a name and click “Create”.

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

5. Go to the “Bot” tab and then click “Add Bot”. You will have to confirm by clicking «Yes, do it!»

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

Keep the default settings for Public Bot (checked) and Require OAuth2 Code Grant (unchecked).

Your bot has been created. The next step is to copy the token.

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

This token is your bot’s password so don’t share it with anybody. It could allow someone to log in to your bot and do all sorts of bad things.

You can regenerate the token if it accidentally gets shared.

How to Invite Your Bot to Join a Server

Now you have to get your Bot User into a server. To do this, you should create an invite URL for it.

Go to the «OAuth2» tab. Then select «bot» under the «scopes» section.

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

Now choose the permissions you want for the bot. Our bot is going to mainly use text messages so we don’t need a lot of the permissions. You may need more depending on what you want your bot to do. Be careful with the «Administrator» permission.

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

After selecting the appropriate permissions, click the ‘copy’ button above the permissions. That will copy a URL which can be used to add the bot to a server.

Paste the URL into your browser, choose a server to invite the bot to, and click “Authorize”.

To add the bot, your account needs «Manage Server» permissions.

Now that you’ve created the bot user, we’ll start writing the Python code for the bot.

How to Code a Basic Discord Bot with the discord.py Library

We’ll be using the discord.py Python library to write the code for the bot. discord.py is an API wrapper for Discord that makes it easier to create a Discord bot in Python.

How to Create a Repl and Install discord.py

You can develop the bot on your local computer with any code editor. However, in this tutorial, we’ll be using Repl.it because it will make it simpler for anyone to follow along. Repl.it is an online IDE that you can use in your web browser.

Start by going to Repl.it. Create a new Repl and choose «Python» as the language.

If you prefer to code the bot locally, you can use this command on MacOS to install discord.py:

If you are using Windows, then you should use the following line instead:

How to Set Up Discord Events for Your Bot

discord.py revolves around the concept of events. An event is something you listen to and then respond to. For example, when a message happens, you will receive an event about it that you can respond to.

Let’s make a bot that replies to a specific message. This simple bot code, along with the code explanation, is taken from the discord.py documentation. We will be adding more features to the bot later.

Add this code to main.py. (You can name the file something else if you like, just not discord.py.) I’ll explain what all this code does shortly.

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

Inside the file add the following line, including your actual token you copied previously:

Now let’s go over what each line of code is doing in your Discord bot code.

We have the code for the bot so now we just have to run it.

How to Run the Bot

Now click run button on the top to run your bot in repl.it.

If you are writing the bot locally, you can use these commands in the terminal to run the bot:

On other systems:

Now go to your Discord room and type «$hello». Your bot should return «Hello!».

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

How to Improve the Bot

Now that we have a basic bot working, we’ll improve it. It is called «Encourage Bot» for a reason.

This bot will respond with a message of encouragement whenever someone sends a message containing a sad or depressing word.

Anyone will be able to add encouraging messages for the bot to use and the user-submitted messages will be stored in the Repl.it database.

The bot will also return a random inspirational quote from an API when someone types the message «$inspire» into the chat.

We’ll start with adding the «$inspire» feature.

How to Add Inspirational Quotes to the Bot

We will get inspirational quotes from an API called zenquotes.io. We need to import a couple more Python modules, add a get_quote() function, and update our bot code to call the function.

Here is the updated code. After the code, I’ll explain the new parts.

We now have to import the requests module. This module allows our code to make an HTTP request to get data from the API. The API returns JSON, so the json module makes it easier to work with the data returned.

The get_quote() function is pretty straightforward. First, it uses the requests module to request data from the API URL. The API returns a random inspirational quote. This function could easily be rewritten to get quotes from a different API, if the current one stops working.

Next inside the function, we use json.loads() to convert the response from the API to JSON. Through trial and error I figured out how to get the quote from the JSON into the string format I wanted. The quote is returned from the function as a string.

The final part updated in the code is toward the end. Previously it looked for a message that started with «$hello». Now it looks for «$inspire». Instead of returning «Hello!», it gets the quote with quote = get_quote() and returns the quote.

At this point you can run your code and try it out.

How to Add Encouraging Messages to the Bot

Now we will implement the feature where the bot responds with encouraging messages when a user posts a message with a sad word.

How to Add Sad Words to the Bot

First we need to create a Python list that contains the sad words that the bot will respond to.

Add the following line after the client variable is created:

sad_words = [«sad», «depressed», «unhappy», «angry», «miserable»]

Feel free to add more words to the list.

How to Add Encouraging Messages to the Bot

Now we’ll add a list of encouraging messages that the bot will respond with.

Add the following list after the sad_words list you created:

Like before, feel free to add more phrases of your choice to the list. I’m just using three items for now because later we’ll add the ability for users to add more encouraging phrases for the bot to use.

How to Respond to Messages

Now we will update the on_message() function to check all messages to see if they contain a word from the sad_words list. If a sad word is found, the bot will send a random message of encouragement.

Here is the updated code:

This is a good time to test the bot. You know enough now to create your own bot. But next you’ll learn how to implement more advanced features and store data using the Repl.it database.

How to Enable User-submitted Messages

The bot is completely functional, but now let’s make it possible to update the bot right from Discord. A user should be able to add more encouraging messages for the bot to use when it detects a sad word.

We are going to use Repl.it’s built-in database to store user-submitted messages. This database is a key-value store that’s built into every repl.

Users will be able to add custom encouraging messages for the bot to use directly from the Discord chat. Before we add new commands for the bot, let’s create two helper functions that will add custom messages to the database and delete them.

Add the following code after the get_quote() function:

The update_encouragements() function accepts an encouraging message as an argument.

First it checks if «encouragements» is a key in the database. If so, it gets the list of encouragements already in the database, adds the new one to the list, and stores the updated list back in the database under the «encouragements» key.

If the database does not already contain «encouragements», a new key by that name is created and the new encouraging message is added as the first element in the list.

The delete_encouragement() function accepts an index as an argument.

It gets the list of encouragements from the database stored under the «encouragements» key. If the number of items in the encouragements list is greater than the index, then the list item at that index is deleted.

Finally, the updated list is stored back in the database under the «encouragements» key.

Here is the updated code for the on_message() function. After the code, I’ll explain the new sections.

We check if «encouragements» is already in the database keys (meaning that a user has submitted at least one custom message). If so, we add the user messages to the starter encouragements.

The next new section of code is used to add a new user-submitted message to the database. If a Discord message starts with «$new», then the text after «$new» will be used as a new encouraging message.

We call the update_encouragements helper function with the new message, and then the bot sends a message to the discord chat confirming that the message was added.

The third new section (at the end of the code above) checks if a new Discord message starts with «$del». This is the command to delete an item from the «encouragements» list in the database.

First a new variable called encouragements is initialized as an empty array. The reason for this is that this section of code will send a message with an empty array if the database does not include an «encouragement» key.

If the «encouragement» key is in the database, the index will be split off from the Discord message starting with «$del». Then, the delete_encouragement() function is called passing in the index to delete. The updated list of encouragements is loaded into the encouragements variable, and then the bot sends a message to Discord with the current list.

Final Bot Features

The bot should work so this is a good time to test it. We will now add a few final features.

We will add the ability to get a list of user-submitted messages right from Discord and we will add the ability to turn off and on whether the bot responds to sad words.

I will give you the full final code of the program, and then I’ll discuss the updates below the code.

The first section added to the code is right under the starter_encouragements list:

We create a new key in the database called «responding» and set it to «True». We’ll use this to determine if the bot should respond to sad words or not. Since the database is saved even after the program stops running, we only create the new key if it doesn’t already exist.

Next, after the code to make the bot respond to the «$del» command, there is new code to respond to the «$list» command when sent as a Discord message.

Finally, the bot sends the list of encouragements as a Discord message.

The final new section comes next. This code makes the bot respond to the «$responding» command. This command takes an argument of either «true» or «false». Here is a usage example: «$responding true».

The code first pulls off the argument with value = msg.split(«$responding «,1)[1] (like before, note the space in «$responding » ). Then there is an if/else statement that appropriately sets the «responding» key in the database and sends a notification message back to Discord. If the argument is anything but «true», the code assumes «false».

The code for the bot is complete! You can now run the bot and try it out. But there is one more important step that we will discuss next.

How to Set Up the Bot to Run Continuously

If you run your bot in repl.it and then close the tab it is running in, your bot will stop running.

But there are two ways you can keep your bot running continuously, even after you close your web bowser.

The first way and simplest way is to sign up for paid plan in Repl.it. Their cheapest paid plan is called the Hacker Plan and it includes five always-on repls.

You can get three months free using this link (limited to first 1000 people): https://repl.it/claim?code=tryalwayson2103

Once you have signed up for that plan, open your Repl and click the name at the top. Then select the «Always On» option.

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

There is another way to keep your code running even on the free tier but it is a little more complicated. Repl.it will continue running a web server even after the tab is closed. But even a web server will only run for up to an hour without any use.

Here is what the repl.it docs say:

Once deployed, the server will continue to run in the background, even after you close the browser tab. The server will stay awake and active until an hour after its last request, after which it will enter a sleeping stage. Sleeping repls will be woken up as soon as it receives another request; there is no need to re-run the repl. However, if you make changes to your server, you will need to restart the repl in order to see those changes reflected in the live version.

To keep the bot running continuously, we’ll use another free service called Uptime Robot at https://uptimerobot.com/.

Uptime Robot can be set up to ping the bot’s web server on repl.it every 5 minutes. With constant pings, the bot will never enter the sleeping stage and will just keep running.

So we have to do two more things to get our bot to run continuously:

How to Create a Web Server in repl.it

Creating a web server is simpler than you may think.

Then add the following code:

In this code, we use Flask to start a web server. The server returns «Hello. I am alive.» to anyone who visits it. The server will run on a separate thread from our bot. We won’t discuss everything here since the rest is not really relevant to our bot.

Now we just need the bot to run this web server.

Add the following line toward the top of main.py to import the server.

To start the web server when main.py is run, add the following line as the second-to-last line, right before the bot runs.

When you run the bot on repl.it after adding this code, a new web server window will open up. There is a URL shown for the web server. Copy the URL so you can use it in the next section.

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

How to Set Up Uptime Robot

Now we need to set up Uptime Robot to ping the web server every five minutes. This will cause the bot to run continuously.

Once you are logged in to your account, click «Add New Monitor».

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

For the new monitor, select «HTTP(s)» as the Monitor Type and name it whatever you like. Then, paste in the URL of your web server from repl.it. Finally, click «Create Monitor».

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

We’re done! Now the bot will run continuously so people can always interact with it on Repl.it.

Conclusion

You now know how to create a Discord bot with Python, and run it continuously in the cloud.

How to make a Discord bot

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

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

Over the last five or so years, Discord has consistently shown that it is the instant messaging platform for not only gamers but anyone looking to message, video chat, or stream with friends online. Among the reasons why are Discord bots. Bots can help you do everything from automate mundane tasks to start playing music across your server, and in this tutorial, we’re going to show you how to make a Discord bot.

Difficulty

Duration

What You Need

Although automation is the main reason to use a Discord bot, you can really program one to do anything (anything that you can cram in some JavaScript code, at least). You don’t need any programming knowledge to get started, either. Our guide will get you started making your own Discord bots, even if you’ve never touched a line of code before.

How to make a Discord Bot

Step 1: Download Node.js and set up a Discord account.

Node.js is a JavaScript runtime that’s free and open source, and you’ll need it to actually make your bot work. Download it at nodejs.org and install it before you get started on anything else.

Obviously, you’ll also need a Discord account and your own server to use to test your bot. If you haven’t created one yet, go to Discord.com and create one. If you do have one, log in to your account and open up the server in which you want your bot to live.

You’ll also need a text editor program, like Notepad++ on Windows, to code with.

Step 2: Now you’ll need to create an application on Discord to make your bot work. This takes a little doing, but it’s not too complex. The goal here is to get an authorization token for the bot so that Discord recognizes your code and adds it to the bot on its servers.

First, head to discordapp.com/developers/applications/me. Your account should be logged in, so you’ll go straight to your account’s list of applications. Hit New Application to get started. Give the bot a name, then hit the button marked Save Changes.

Now, on the right-hand menu, click Bot. Once in the new menu, click Add Bot under the Build-a-Bot option. If you only have one application — the one we just made — it should appear automatically. Otherwise, select it.

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

Step 3: In the box marked App Bot User, look for the words Token: Click to Reveal. Click that link and you’ll reveal a string of text. That’s your bot’s authorization token, which allows you to send it code. Don’t share it with anyone — that token allows whoever has it to create code for the bot, which means whoever has it can control your bot. If you think the token has been compromised, the good news is that you can easily generate a new one with the Generate a New Token button. Mark down your token. You’ll need it in just a second.

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

Step 4: Now scroll up to the box marked App Details and find your Client ID, a long number. Copy the number and add it to this URL, in the place of word CLIENTID.

The final URL should look like this, but with your client ID number in it instead of this fake one: https://discordapp.com/oauth2/authorize?&client_id=000000000000000001&scope=bot&permissions=8

Copy the URL with your client ID number in it into your browser. That’ll take you to a website where you can tell Discord where to send your bot. You’ll know it worked if you open Discord in an app or your browser and navigate to your server. The channel will say a bot has joined the room, and you’ll see it on the right side menu under the list of online members.

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

Step 5: While you’re doing that, you can also take a moment to create a folder in an easy-to-reach place on your computer where you can store all your bot’s files. Call it something simple, like “DiscordBot” or “MyBot,” so you know exactly what it is.

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

Step 6: You’re going to create three files for your bot from your text editor. In the first, paste this code:

“token”: “Your Bot Token”

Make a new file, and put in this code:

“description”: “My First Discord Bot”,

“author”: “Your Name”,

Replace the author name with your name if you want; you can also change the description to something else if you want something more in line with what you’re making, which will be handy for remembering what your bot is supposed to do.

Save this file as “package.json” in your Discord bot folder.

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

Step 7: There’s one more text file to make, and this is the important one that controls your bot’s behavior. You’ll want to be familiar with JavaScript to really have full control of your bot and know what you’re doing, but if you’re new to coding and just want to make something, you can copy and paste this code into the file to make a simple bot that will greet you in your server.

(Thanks to Medium user Renemari Padillo, whose bot tutorial helped us create this one. Check out his tutorial for code troubleshooting and other advice.)

var Discord = require(‘discord.io’);

var logger = require(‘winston’);

var auth = require(‘./auth.json’);

// Configure logger settings

// Initialize Discord Bot

var bot = new Discord.Client(<

bot.on(‘ready’, function (evt) <

bot.on(‘message’, function (user, userID, channelID, message, evt) <

This code sets up a Discord bot that will respond to certain messages — specifically, anything that starts with a “!” character. In particular, we’re programming the bot to respond to the command “!intro”, so if anyone types that in your server while the bot is in it, the bot will respond with a programmed message. In our code, we defined the message as, “Greetings! Welcome to the server!” You can change both the prompt message and the response message by redefining them in the code above. Just make sure to maintain the single quotation marks around the messages.

Save this last text file as “bot.js” in your Discord bot folder.

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

Step 8: On a Windows PC, you can easily get to the Command Prompt by clicking the Windows icon and typing «Command Prompt» in the field. Once it’s open, type “cd” followed by the file path to your folder. On our test computer, the command looks like this: “c:UsersPhil’s DesktopDesktopDiscordBot.” That should change the command prompt line to include the file path to your folder.

Alternatively, you can navigate to your folder in Windows and hold Shift while right-clicking on a blank area of the folder, then choose Open Command Prompt.

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

Step 9: Now it’s time to make use of Node.js. In the Command Prompt, with your Discord bot folder in the file path line, type “npm install discord.io winston –save.” This will automatically install files you need to for your Discord bot into the folder directly.

Also use the following command line prompt to install additional dependencies: npm install https://github.com/woor/discord.io/tarball/gateway_v6

That should provide you with all the files you need.

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

Step 10: Now you’re ready to go. To try running your bot, type “node bot.js” in the Command Prompt (make sure you’re still navigated to your Discord bot folder).

To test your bot’s functionality, get back on your Discord server and try typing in “!intro,” or “!” followed by the prompt message you created in your “bot.js” file. If you coded your bot correctly, sending this command will cause your bot to reply to you with your set message.

Congratulations, you are the proud creator of a Discord bot.

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

The great thing about Discord is the community of shared interest and skill. Users on Discord are always making new tools to improve the service, including bots. Some creators will upload their bots to public databases and allow others to download the bots and use them for their servers. The bots listed in databases can have a variety of functions coded into them, so you’ll likely be able to find what you need. Before making your bot, do a little exploring on Discord to see if someone else has already made just the bot you need.

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

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

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