How to invite bot to discord
How to invite bot to discord
Как пригласить бота в Discord
Discord – популярный мессенджер, который с каждым годом расширяет аудиторию посредством обновлений и введения новых программных возможностей. Приложение знаменито простотой пользования интерфейса и стабильной работой серверов.
Если конкретизировать, то разработчики одни из первых ввели так называемый элемент Discord Bots, который использует технологию ИИ. Перечень функций данной платформы отвечают за ведение интерактивного диалога и поиск информации. Также виртуальный помощник может подбирать и транслировать музыкальную дорожку.
Разновидности
С развитием мессенджера появилось немало виртуальных помощников, причем львиная доля разработана участниками комьюнити.
Среди всех особой популярностью обладают такие боты:
Добавление функции
Для того чтобы добавить бота в Дискорд, необходимо придерживаться следующего порядка действий:
Серверное расширение
Процедура добавления интерактивного помощника на сервер аналогична стандартным действиям установки.
Добавление на канал и в беседу
В процессе установки бота, который описан выше, необходимо в списке предложенных серверов выбрать индивидуальный канал или комнату с другими участниками. Они имеют характерное название бесед. Как только интерактивный помощник будет приглашен в группу, он появится в списке участников чата. Для того чтобы добавить его в отдельную комнату, необходимо прописать в чате этой беседы команду «++voice» (команда может быть другой, в зависимости от функционала бота).
Создание помощника
К сожалению, еще не придуман редактор по созданию собственного виртуального собеседника. На данный момент пользователю необходимо знать языки программирования по типу Java-скрипт (в частности, расширение к Java – Groovy).
Удаление
Существуют два способа, при которых можно удалить бота в Discord.
В случае, когда бот не запрашивал вашу личную информацию при установке, достаточно просто удалить его с сервера и из списков участников беседы.
В ином случае необходимо придерживаться следующих действий:
Отключение помощника
Процедура отключения виртуального бота на сервере включает в себя:
Приложение развивается с каждым днем и предлагает все новые функции и расширенные возможности новым пользователям.
Настройка бота на сервере в Discord
Если вы еще не добавили бота на сервер и не знаете, как правильно это сделать, прочитайте другой наш материал, где рассказывается как об официальных сайтах проектов, так и об открытых площадках, где они свободно распространяются.
Вариант 1: Программа для ПК
Управлять сервером более логично при помощи версии Discord для ПК, поскольку в ней вы найдете все доступные функции и упростите процесс добавления и настройки бота. Поэтому поговорим о данном варианте в первую очередь, детально разобрав каждый этап конфигурирования бота, если его изначальные параметры вас не устраивают.
Шаг 1: Использование команды помощи
Получить все необходимые сведения часто можно использованием стандартной команды помощи, поддерживаемой самим ботом. В ответном сообщении указывается список имеющихся команд и дополнительная документация, которая может пригодиться при работе с этим инструментом.
Отображаемая вспомогательная информация зависит непосредственно от разработчиков ботов, поскольку они решают, что описывать пользователям. Дополнительные сведения всегда можно получить на официальном сайте или открытой площадке, откуда был загружен бот.
Шаг 2: Настройка роли
Каждому боту при авторизации присваивается своя роль с определенными правами для возможности внесения изменений на сервере, управления участниками или отправки сообщений. Некоторые боты по умолчанию не имеют требуемых прав, поэтому разработчики просят настраивать их самостоятельно, что происходит следующим образом:
Точно таким же образом редактируются и все остальные разрешения, присутствующие в меню. Их активация осуществляется в соответствии с требованиями самого инструмента. Обычно если боту не хватает прав для выполнения конкретных действий, он отправляет личное сообщение с текстом ошибки, поэтому разобраться в предоставлении доступа не составит труда.
Шаг 3: Добавление роли боту
На определенных серверах дополнительно боту присваивается специфическая роль или же создатель предпочитает их все объединить в один список для простоты настройки. В этом случае действует такой же принцип, как и для обычных участников сервера.
Что касается добавления новых ролей на сервер, то получить полезную информацию по этому поводу вы можете в специальной инструкции на нашем сайте, щелкнув по следующему заголовку.
При необходимости можно удалить уже существующую по умолчанию роль бота, если она вам не требуется и вы хотите присвоить ему другие права.
Шаг 4: Права бота на каналах
Обычно права бота настраиваются через роль, а разрешения на голосовых или текстовых каналах подхватываются автоматически средством синхронизации. Однако иногда требуется установка параметров в виде исключения — например, когда всем ролям запрещено посылать сообщения на сервере, но там присутствует и бот, который должен функционировать. Для этого понадобится редактировать права самого канала.
Шаг 5: Параметры на официальном сайте
В завершение этого варианта рассмотрим дополнительные настройки ботов на их официальных сайтах. Подходит это только в тех случаях, когда инструмент является универсальным, поддерживает плагины и специфические параметры, как, например, популярный MEE6, которого мы и возьмем в качестве примера.
Наличие определенных параметров зависит исключительно от типа бота и подхода разработчиков, и если вы не обнаружили подобных настроек, значит, для выбранного инструмента они недоступны.
Вариант 2: Мобильное приложение
Если с добавлением ботов на сервер в Discord через мобильное приложение часто возникают трудности, то вот их настройка обычно не вызывает никаких проблем, поскольку все действия по управлению стандартны и доступны как создателю, так и администратору сервера.
Шаг 1: Использование команды помощи
Начнем с получения общих сведений о взаимодействии с добавленным ботом, что производится путем ввода команды помощи. Она отображает информацию, заложенную разработчиками специально с целью рассказать юзерам больше о своем проекте.
Шаг 2: Настройка роли
Если вы читали Вариант 1 про настройку бота через программу на компьютере, то уже знаете, что каждому из них присваивается своя роль с определенными правами. При необходимости их редактирования можно использовать и мобильное приложение, о чем и пойдет речь в следующей инструкции.
Все остальные присутствующие прав изменяйте по собственному желанию в соответствии с предназначением инструмента. Достаточно просто прочесть определение разрешения для понимания его действия.
Шаг 3: Добавление роли
Отдельно рассмотрим добавление роли для бота, если его стандартные права вас не устраивают или вы хотите объединить несколько участников для выполнения определенных задач на сервере. Управление ролями бота осуществляется точно так же, как бы это было и с другими пользователями.
Шаг 4: Права бота на каналах
Завершающий этап — редактирование разрешений для бота на текстовых и голосовых каналах сервера. Необходимость в реализации данной задачи появляется редко, но если все-таки возникнет, сделать это будет крайне просто, поскольку весь процесс точно такой же, как и для других участников сервера.
Как добавить бота в Discord на сервер и канал: проверенные способы
Создавая свое сообщество в Discord, владельцы как крупных так и маленьких каналов нуждаются в автоматизации некоторых процессов, чтобы не погрязнуть в рутине.
В таких случаях на помощь приходят боты – специальные программы (мини-приложения), которые эту самую рутину берут на себя и позволяют администраторам серверов заниматься более интересными вещами в процессе раскрутки Discord и продвижения серверов в массы.
В этой статье мы рассмотрим все доступные способы добавления бота на ваш Discord-сервер и пошагово покажем, как это сделать лучше всего.
Проверенные способы добавления бота в Discord
Перед тем как добавить бота на сервер, его нужно сначала найти. Обычно все боты тусуются здесь – Top.gg. Зайдите в каталог, выберите один из предложенных хэштегов, который наиболее точно соответствует тематике вашего Discord-сообщества, и перед вами появится список самых популярных ботов выбранной категории.
Когда вы найдете того бота, который вам нужен, все что останется сделать – это добавить его на свой сервер в Дискорде. И вот тут мы рассмотрим несколько проверенных способов добавления бота в Discord.
Способ первый: приглашение бота через инвайт из каталога
1. Откройте страничку любого бота. Кликните в правой части экрана по кнопке с текстом «Invite».
2. Вас перекинет на отдельную страницу привязки бота к серверу.
3. Здесь из выпадающего списка выберите сервер, на который вы хотите пригласить бота и нажмите «Продолжить».
4. Перед вами предстанет список прав с уже отмеченными галочками, которые убирать не нужно. Просто нажмите «Авторизовать».
5. Убедите Discord в том, что вы живой человек, а не робот, поставив галочку в соответствующем чекбоксе и пройдя капчу.
6. После успешного прохождения капчи появится сообщение, что новый бот авторизован на сервере. Теперь вы можете закрыть эту вкладку и перейти в приложение.
7. В правой колонке в Discord, где отображаются пользователи, вы увидите только что добавленного бота.
8. С помощью команды /help (или той, которая указана в документации), прописанной вами в любом текстовом чате сервера, вы получите список всех доступных команд бота. С их помощью вы можете полноценно управлять этим ботом и автоматизировать некоторые рабочие процессы.
Таким образом мы приглашаем бота прямо из каталога на наш сервер. Обратите внимание, что команды некоторых ботов могут совпадать, но вы можете выбрать при написании, какому именно боту необходимо произвести заданное действие.
Важно: если хотите послушать музыку, пригласив музыкального бота на сервер, зайдите в любой голосовой канал, пропишите в текстовом канале нужную команду (например, /play), и бот присоединится к вам – теперь будете слышать музыку и сможете управлять плейлистом.
С помощью команд /leave или /stop бота можно отключить, выгнав его из голосового канала, а через какое-то время пригласить снова.
Способ второй: создание собственного бота и подключение его к серверу
Если вы умеете разрабатывать собственных ботов, метод добавления их на сервер будет выглядеть иначе. Мы не будем углубляться в многогранный процесс разработки ботов, просто покажем, что и в какой последовательности нужно сделать, чтобы добавить собственного бота на сервер Discord.
Для начала необходимо создать приложение, затем внутри него создать бота, настроить права доступа и разрешения, и только после этих манипуляций бота можно добавлять на сервер.
1. Перейдите на специальную страницу для разработчиков и нажмите на кнопку «Новое приложение» («New Application»).
2. Придумайте название для нового приложения, после чего нажмите на кнопку «Создать» («Create»).
3. После создания приложения вы можете задать дополнительные параметры: добавить описание, изображение, хэштеги и т.д.
4. Чтобы добавить нового бота в созданное нами приложение, перейдите в раздел «Бот» («Bot») и нажмите справа на кнопку «Добавить бота» («Add Bot»).
5. Дискорд у вас спросит, действительно ли вы хотите прикрепить бота к только что созданному приложению. Подтвердите действие.
6. Готово, наш бот создан и закреплен за приложением. Теперь вы можете внести необходимые правки в описание, заменить изображение, сгенерировать новый токен, который вам может понадобиться при дальнейшей разработке. Токен можно скопировать и сохранить в отдельный файлик, чтобы не возвращаться на эту страницу каждый раз только лишь за ним. Здесь же вы можете сделать вашего бота публичным, чтобы все желающие могли добавить его на свои серверы.
7. Для получения ссылки на вашего бота и настройки различных разрешений перейдите в раздел «OAuth2», в выпадающем списке с подразделами выберите «URL Generator» и проставьте галочки в чекбоксах «Bot» и «Send Messages» (разрешения можно выбирать на свое усмотрение, мы же просто разрешили боту отправлять сообщения), после чего скопируйте сгенерированную ссылку, как показано на скриншоте.
8. Скопированную ссылку вставьте в адресную строку новой вкладки браузера и перейдите по ней. В появившемся окне выберите сервер, на который хотите добавить бота, и нажмите «Продолжить».
9. Проверьте разрешения, которые мы выдали боту на седьмом шаге, и нажмите на кнопку «Авторизовать».
10. Пройдите проверку капчи, чтобы Дискорд понял, что вы не робот.
11. После этого закройте вкладку и перейдите в Discord. Если в основном текстовом канале вашего сервера появится приветственное сообщение от новоиспеченного бота, значит, все прошло как надо и бот успешно добавлен на ваш сервер в дисе с необходимыми правами доступа.
Заключительный штрих: используя токен бота и ID канала вашего сервера подключите бота в приложение через AppMaster.io. Вся необходимая документация находится здесь. В панели управления AppMaster.io Studio сможете более расширенно настроить отправку сообщений в Discord из вашего нового приложения через различные формы.
AppMaster хорош тем, что даже не имея минимальных навыков программирования, вы сможете создать свою собственную уникальную экосистему приложений и управлять ими из личного кабинета сервиса.
Способ третий: выбор бота из списка пользователей на чужом сервере и добавление на свой
Все авторизованные на вашем сервере приложения вы можете найти в настройках пользователя приложения Discord на вкладке «Авторизованные приложения».
Здесь можете отслеживать все приложения, подключенные к вашему серверу
Есть еще один очень простой способ добавления бота на свой сервер. Допустим, вы попали на какой-нибудь крупный сервер и вам приглянулся бот, который помогает тамошним администраторам в коммуникации с пользователями.
Скопируйте или перепишите название такого бота в поисковую строку любой ПС, перейдите на официальный сайт бота или на его страницу в каталоге и пригласите бота на свой сервер, как мы это делали с помощью первого способа, описанного в данной статье.
JavaScript Discord Bot Tutorial
Introduction
In this tutorial, we will walk through the process of creating a bot in JavaScript. We will start by creating a Discord server, creating a bot account, and inviting it to the server. Then we will demonstrate how to write JavaScript (Node.js) code to power the bot. By the end, you will have your very own bot that can be invited to any server that you have full control over.
If you are interested in learning how to make a Discord bot in Python, check out Make a Discord Bot in Python and Part 2. Be sure to also check out all of the other Discord related tutorials on DevDungeon.
Video tutorial
Create a Discord server
In order to create a Discord server you will need to have a Discord account. If you don’t have a Discord account already, sign up and log in at https://discordapp.com/channels/@me. Once you are registered, you can either use the web browser version or you can download the app. They both behave the same. Once you are logged in to the app, look to the bottom-left corner, for the plus (+) sign. Click on the plus sign and it will ask if you want to create or join a server. Click «Create a Server.» Provide a name, and click «Create.» The new server will appear in the left column.
Create a Discord app
The next step is to create a Discord App. We aren’t writing any code yet, we are just registering the app with Discord. Start by going to https://discordapp.com/developers/applications/me and create a new app. On your app detail page, save the Client ID. You will need it later to invite the bot to a server. Try to give your app a unique name.
Create a bot user for your app
After creating app, you need to take one further step and add a bot user to the app. You can do this on the app details page. On the app details page, scroll down to the section named bot, and create a bot user. Save the token, you will need it later to run the bot. If you get an error saying «Too many users have this username, please try another» then you need to rename your application to something more unique.
Note that by default, a bot has limited permissions. It can send and receive messages, add reactions, and do things a normal low-privileged user could do on a server, but it cannot perform admin actions like kicking members or managing channels. To perform those admin actions you would need to add the specific permissions to the bot as well as perform additional authentication steps. We are not going to cover that in this tutorial. We will stick with the default permissions like a regular non-admin user.
Authorize/invite the bot to your server
After you have registered your app and created the bot user for your app, you are ready to invite(authorize) the bot to your server. To do this, you will need the Client ID for your app. You can get this from your app’s «General Information» page.
When you have your Client ID, visit the URL https://discordapp.com/oauth2/authorize?client_id=XXXXXXXXXXXX&scope=bot but replace XXXXXXX with your client ID. Choose the server you want to add it to and select authorize.
The Client ID does not necessarily need to be kept secret. If you want to share your bot and allow others to invite the bot to their server, then you can share this link. It will allow them to invite your bot to their server. The bot’s token is different though. Always keep the token a secret, as that is the equivalent to your bot’s password. Anyone with the token can log in as your bot.
After you authorize the bot for the server, it should then show up in the member list of the server as an offline user. Once we write some code and run it, the bot will appear online.
Prepare your Node.js project workspace
First, you will need to have Node.js installed. If you don’t already have it installed, get it from Nodejs.org. I will be using Node.js 10.10.0. You will need Node.js 8.0.0 or newer. You will also need npm but that should come packaged with Node.js.
Once you have Node.js installed, you will need to create a new directory to store your project. Once you have a new directory, open your system terminal/command prompt/shell and navigate to your new directory. You can create the directory in your home folder or anywhere you have permission. You may prefer to create a folder on your desktop.
Keep your terminal open. You will need it in the next step.
Install the Discord.js module
The next step is to install the Discord.js module and its dependencies. Use npm in the command prompt to install the module:
You might see warnings. Those are OK, it is just telling you about some optional modules. As long as you do not see any errors it should be good. Keep your terminal open here so you can run the program you create in the next step.
At the time of this writing, Discord.js is at version 11.4.2. Future version might change how the code works.
Write a simple test bot
At this point, you should have your development environment ready to go with Node.js and the necessary Discord.js module installed. You should also have your own Discord server, app, and bot user that are ready to be utilized. We should take a moment to make sure everything is set up properly. Let’s write the simplest bot possible just to make sure it works. Let’s create a new JS file and write some code to have the bot log in. You can name the file my_bot.js though the file name is not important.
Create/open the new file in your favorite editor, and put the following code in the file:
You will need to replace the XXXXXXXXXXX with your bot’s secret token. This is equivalent to your bot’s password, so keep it secret! You can find the bot’s token by going to https://discordapp.com/developers/applications/ and then clicking on your app. On the app detail page, click on the «Bot» section. On the bot detail page, look for the «Token» section. You will need to «click to reveal token.»
Save the file and run the code from the terminal:
The output should say Connected as [your bot’s name]. If you check the server’s member list, the bot should appear online as well. If you can see the bot online in the server, then everything is working properly and we can move on to making the bot actually do something fun! The JavaScript file will continue to run although it doesn’t do anything except connect, so use CTRL-C to terminate the program or exit the terminal to kill the process. It is normal for your bot to still appear online for a few minutes after the program is terminated. After a few minutes it will appear offline again.
If you have any errors or get stuck at this spot, try joining the DevDungeon Discord server (https://discord.gg/JWsSHJC) or post a comment to ask for help.
Get a list of servers the bot is connected to
Once your bot is connected, the client object keep a list of servers it is connected to. In Discord terminology, it is called a guild. The client object has an property named guilds which we can access through client.guilds. In the following example, we iterate through the list of servers(guilds) and print out the name of each one. Most likely your bot is only connected to just one server, your test server. Bots can be connected to many servers at once though.
The Discord.js Client object has many other properties, like how long it has been connected, all channels available, and what emojis are available. To see a full list of properties on the Client object, check out the official documentation for the Client object at https://discord.js.org/#/docs/main/stable/class/Client.
Get a list of channels from a server
In the previous example we saw how to get a list of servers the client has access to. Each server can have many channels. The guild object has a property named channels that we can access. That will give us the list of channels for that specific guild(server). Another option is to get channels property from the client object instead of the guild object. If we use client.channels as opposed to guild.channels then we will get the list of all channels from all servers.
In this example, we will extend the code from the previous section. We will still list each server we are connected to, but we will also list each channel’s name, type, and ID for each server.
Note that there are multiple types of channels including text, voice, and category. The type «category» is not a channel that can be used directly, it is just a label for a group of channels.
Find a channel you would like to use to send messages. There is usually a text channel named «general» that you can use. Take note of the channel ID of the text channel you would like to use. You will need it in the next section to send a message to the channel. For our example, let’s pretend the channel ID is 123456789.
Sending a message to a channel
In the previous example we demonstrated how to get all of the channels available. You should have identified a text channel that you want to use. You need the channel.id. For our example, we will pretend the channel ID is 123456789, but you will want to replace that with the actual channel ID. The following code will print «Hello, world!» to the specified channel as soon as the bot connects.
Posting an image or file to a channel
This example will extend the previous example that sends a message to a text channel. Instead of sending a regular text message though, we are going to send an attachment. An attachment can be an image or it can be a file. The attachment can come from your local hard disk or from a web URL. The code below demonstrates how to create an attachment from a local file and then send it to the channel as well as how to create an attachment from an HTTP URL. Note that for the localFileAttachment to wor, you will need to replace the example filepath with the path to a real file on your computer. The webAttachment should work as it links to the DevDungeon logo but you can change it to any image or file on the web.
Replying to a message
In all of the previous examples, we have taken action as soon as the bot connected by using the client.on(‘ready’) event. In this example, we are going to trigger our code whenever a message is received. The client object actually has several events that we can use as triggers. For example: whenever a channel is created, whenever a message is deleted, or when a user updates their presence(e.g. starts playing a game). See the full list of events that you can use on the Client documentation page at https://discord.js.org/#/docs/main/stable/class/Client. For this example we are using the message event, which gets triggered whenever a message is received, either via private message or in a text channel.
The code below will respond any time a message is received with an acknowledgement. Note that the message event gets triggered even when the bot sends a message. This means the bot could enter an infinite loop where it keeps responds to its own messages. To prevent that, the first thing we are going to do is make sure the message received did not come from our bot itself. If it does, we will just return and take no action. If the message received comes from another user, it will continue and reply with the acknowledgement message.
To test the code below, run the bot and using your own Discord user (not the bot) send a message to a text channel on your server that the bot has access to. You can also send the bot a direct/private message and it will respond in the same channel.
Tagging a user
Let’s extend the previous example to also tag the user who sent the message. To tag the user, we can take the user who sent the message, receivedMessage.author, and use the toString method to get the properly formatted tag.
Checking if your bot was tagged in a message
Let’s extend the previous example even further by only responding to messages if the bot user was tagged. We will have to inspect the message content and see if our bot’s tag was mentioned. We do this by converting our bot’s user to a string, and then seeing if the message includes that string.
Creating commands
A common task with Discord bots is to create «commands». A command in this sense is a message that triggers a special action. Commands are often specified by beginning a message with a special character. For example !help or ?help or something similar.
In this example we will create a few functions to break up the logic. We will still have our event triggered when a message is received, but this time, we will see if the message starts with an exclamation mark (!) and if it does, we will route it to a custom processCommand function. The processCommand function is responsible for taking the full message from the user and breaking it in to pieces. The user can provide extra parameters to the command by separating words with a space. For example, commands can have no parameters or multuiple parameters like this:
Inside the processCommand function, after we remove the leading exclamation mark and separate the command from the arguments, we then inspect the main command and then pass the logic to another function. We create a helpCommand and a multiplyCommand. Depending on what command is triggered, the corresponding function is called.
There are limitless ways to abstract out a command handler, but this method should be simple enough to understand and be flexible enough for the needs of most people. I provided two sample commands in order to provide a template for creating your own commands. Try extending this example with a custom command of your own. Here are a few ideas:
Try running this code and then sending a message to the bot or to the channel with !help and !multiply.
Changing game presence/activity
Changing the bot’s activity is relatively simple. We just need to call setActivity() on the bot’s user object. By default it will say «Playing ____» but you can also change the verb to «Streaming», «Listening», or «Watching». Try out the code below. After running the code, look at the bot in the member list of the server and you should see it’s status change.
Adding a reaction emoji to a message
Playing audio files in voice chat
Playing audio in voice channels requires installing extra dependencies. We will not cover this topic here, but you can find more details and instructions in the official documentation on this page: https://discord.js.org/#/docs/main/stable/topics/voice. Time permitting in the future, this topic might be covered here in more detail.
How to run a bot 24/7
JavaScript Discord Bot Tutorial – Code a Discord Bot And Host it for Free
This tutorial will show you how to use JavaScript and Node.js 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, Node.js libraries, and a cloud computing platform called Repl.it.
If you’d rather code your discord bot using Python instead of JavaScript, read this tutorial instead.
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 Node.js 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.
4. Give the application a name and click “Create”.
5. Go to the “Bot” tab and then click “Add Bot”. You will have to confirm by clicking «Yes, do it!»
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.
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.
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.
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.js Library
We’ll be using the discord.js Node library to write the code for the bot. discord.js is an API wrapper for Discord that makes it easier to create a Discord bot in Node.js / JavaScript.
How to Create a Repl and Install discord.js
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 «Node.js» as the language. This means the programming language will be JavaScript.
How to Set Up Discord Events for Your Bot
discord.js 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 is taken directly from the discord.js documentation. We will be adding more features to the bot later.
Add this code to main.js. I’ll explain what all this code does shortly.
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.
The client.on() is used to check for events. It accepts an event name, and then a callback function to be called when the event takes place. In this code, the ready event is called when the bot is ready to start being used. Then, when the Discord server has a new message, the message event is called.
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.
Now go to your Discord room and type «ping». Your bot should return «pong».
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 the node-fetch module, add a getQuote() 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 node-fetch module. This module allows our code to make an HTTP request to get data from the API.
The getQuote() function is pretty straightforward. First, it uses the node-fetch 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.
Then the function converts the response from the API to JSON and creates a string to return. 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 the message «ping». Now it looks for «$inspire». Instead of returning «pong», it gets the quote with getQuote() and returns the quote. We use msg.channel.send() to send the message to the channel. Also, the code checks if the message comes from the bot itself and if it does, it leaves the function so it does not do anything.
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 an array that contains the sad words that the bot will respond to.
Add the following line after the client variable is created:
sadWords = [«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 an array of encouraging messages that the bot will respond with.
Add the following array after the sadWords list you created:
How to Respond to Messages
Now we need to update our bot to use the two lists we created.
Now we will update the message function to check all messages to see if they contain a word from the sadWords 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.
At the top of the code, under the other import statements, add:
This will allow us to use the Repl.it database. When you run the code, Repl.it should install the database module automatically. If for some reason it doesn’t, you may have to go into the Shell tab (not the Console) and type «npm install @replit/database».
After where the encouragements array is created, insert the following code to add the encouragements to the database if needed:
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 getQuote() function:
The updateEncouragements() function accepts an encouraging message as an argument.
First it gets the «encouragements» from the database. Then, it adds the new encouragement to the array, and stores the updated array back in the database under the «encouragements» key.
The deleteEncouragement() function accepts an index as an argument.
It gets the list of encouragements from the database stored under the «encouragements» key. If the length is more 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 message function. After the code, I’ll explain the new sections.
The sad words section has been updated to use the encouraging messages from the database so user submitted messages can be used.
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 updateEncouragements 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.
The index is split off from the Discord message starting with «$del». Then, the deleteEncouragement() 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 starterEncouragements 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.
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.content.split(«$responding «)[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.
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 express to start a web server. The server returns «Bot is running!» 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 index.js to import the server.
To start the web server when index.js 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 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».
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».
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 JavaScript, and run it continuously in the cloud.