Как поставить бота на хостинг discord
Перейти к содержимому

Как поставить бота на хостинг discord

  • автор:

Hosting a Python Discord Bot for Free with Fly.io

As Heroku is no longer going to be free after November 28, 2022, I am sharing another way to host a Discord bot 24/7 for free.

You will be able to host any kind of bot on Fly.io with few limitations by following the steps below. You can also optionally attach a PostgreSQL database for storing data.

Deploying a Python Discord Bot to Fly.io

This article was originally a video tutorial, which you can check out here:

1. Install the flyctl command line tool

Mac OS

If you have the Homebrew package manager installed, flyctl can be installed by running:

Exit fullscreen mode

If not, you can run the install script:

Exit fullscreen mode

Windows

Run the Powershell install script:

Exit fullscreen mode

Arch Linux

Run the package installer:

Exit fullscreen mode

Linux

Run the install script:

Exit fullscreen mode

2. Create an account by running flyctl auth signup and finishing through the browser

After installing flyctl, you should now be able to use it in the command line. Use flyctl auth signup to launch your browser and complete the account creation steps. If you already have an account, you can use flyctl auth login .

3. Add a Dockerfile with the Python version and dependency install method

Method 1: requirements.txt

Create a list of your dependencies in a requirements.txt . You can find out what you have installed using pip freeze .

Exit fullscreen mode

Exit fullscreen mode

To tell Fly.io to install these dependencies, create a file called Dockerfile (no file extension) with the following contents:

Exit fullscreen mode

In this case python bot.py is the command used to run the bot. If your bot starts in a different file, you should change that here.

Method 2: Using Poetry

If you are using Poetry for dependencies, your Dockerfile will look more like this:

Exit fullscreen mode

Poetry Dockerfile is based on this tutorial by Replicate.com. Thanks Abraham Murciano for the correction.

4. flyctl launch

In the project folder, run flyctl launch

Give your project a name, type Y or N depending on if you want a Postgresql database or not, type N to not have it deploy.

This will create a fly.toml , but you can delete most of it so that it looks similar to this:

Exit fullscreen mode

5. flyctl deploy

Type flyctl deploy to deploy the first version!

Once it is completed, your bot will be running on Fly.io!

6. Set the environment vars

If you will be deploying your bot without your .env or configuration files, you will need to set secrets for fly.io to know about.

This will include all environment variables, for example:

Exit fullscreen mode

To deploy further versions, you can run flyctl deploy or see below for automatic deploys from GitHub.

Continuous deployment from GitHub

You can find the video for this part here:

  1. Run flyctl auth token to get a Fly API token
  2. Go to your repo’s Settings > Secrets > Actions and click New repository secret
  3. Enter FLY_API_TOKEN as the name and your token from step 1 as the value
  4. Create a folder, .github/workflows/ and inside create a file that uses the flyctl action on push. You may name it what you like, for example, fly.yml .

Exit fullscreen mode

Make sure the branch name is correct for your default branch.

Conclusion

Thanks for reading!

I hope you found this tutorial useful.

Check out the full video for further explanations and be sure to like and subscribe!

How to host a discord.py bot with Heroku and Github

Analytics Vidhya

Right now, the only means of getting your bot online is to run the program on your computer. This tutorial will show you how to get it running remotely with Heroku.

Note: This tutorial assumes you had (1) made a discord.py bot with all dependencies installed onto a virtual environment, (2) created an Heroku account, and (3) familiar with the basics of Github. It does not go into technical details, rather it is a list of easy-to-follow steps.

INITIAL PROJECT DIRECTORY

This should roughly be how your project directory looks like before following this tutorial.

Discord Bot Hosting in 2023: Updated Guide

Discord Bot Hosting Featured - Discord Bot Hosting

It doesn’t matter if you just want to have your bot 100% available for your server’s users, or if you want to grow and support hundreds of servers in the future.

The Definitive Guide To Hosting A Discord Bot

No matter what you’re going after, hosting your own Discord bot is the way to go!

In this detailed Discord bot hosting guide, we’re going to walk through the exact steps to get your bot up and running 24/7 in under an hour.

We’ll go over the best Discord bot hosting methods, and then walk through how to set up your very own reliable bot hosting.

After reading this guide you’ll know all the tricks to get a bot deployed on a VPS (Virtual Private Server), hosted, and live in under an hour, and best of all you’ll be able to replicate this process for years to come.

Here’s How You Get Your Bot Up and Running 24/7

Setting up your own bot hosting might seem complicated, but it’s actually much easier than it looks. The key is to understand what we’re actually doing step by step, and not just blindly following along without thinking or reading the explanations.

This is exactly why we go through each step in-depth, letting you actually understand and learn why we’re doing things the way we are.

Smart Reliable Hosting, 24/7 Uptime, And Happy Discord Community

What this guide will cover

We’re going to start by going over how to set up a JavaScript / Node.js bot on your own VPS host and then talk through some alternative options like Amazon AWS, Google Cloud, and even how to host your own Discord bot on a Raspberry Pi.

Picking a reliable VPS host

The key to having solid reliable hosting for your bot is to use a well-known reputable third-party hosting provider. For the purposes of this guide, we’ll be using Vultr VPS (you can create an account here) due to its reliability, solid uptime, and low cost.

A good hosting provider will allow you to have:
  • Reliable Uptime – I’ve been using Vultr as a VPS host for websites & bots for years, and have experienced 99.9% uptime as indicated by uptime analysis tools like Uptime Robot.
  • Simple Control Panel – Navigating around your VPS control panel to change settings should be incredibly easy and simple. We’ll have detailed screenshots and steps for configuring your Discord bot in the coming sections, so you’ll be able to see how simple it is to navigate firsthand.
  • DDoS Protection – If your server gets popular, there may be a third party that attempts to take it down through a distributed denial-of-service (DDoS) attack. Fortunately, Vultr VPS servers give you the option to add DDoS protection if you choose.
  • Reliable Operating System – The most affordable, cost-effective, and efficient VPS server operating system (OS) for hosting your Discord bot is a Linux Server. Using Windows Server, for example, requires you to pay an extra licensing fee. By using a reliable Linux distribution like Ubuntu Server, you can get up and running and pay just a few dollars ($) per month.
  • Frequent Backups – If something happens and you lose your data, having a backup will save you. A reliable VPS provider will offer backup options and an easy recovery mechanism.
  • SSD Storage & NVMe – To ensure your server doesn’t have any bottlenecks and can handle a large number of requests, you’ll want to find a Discord bot host that offers fast storage through SSD (Solid State Drives) and NVMe (NVM Express Storage Access and Transport Protocol). The better your server’s hardware, the more it’ll resemble enterprise-grade hardware.
  • Reliable Support Team – If you have any questions about your Discord bot hosting server, a dependable support team will save you from endless headaches and scrambling to find answers yourself. Usually, all you have to do is submit a support ticket for quick support.
  • FTP Access & SSH Support – Most VPS hosts offer this right out of the box. FTP (File Transfer Protocol) will allow you to connect to your server and browse your files through a tool like FileZilla. SSH (Secure Shell) allows you to connect to your server through a terminal to install software, send commands, and configure various server settings.

Dedicated Server vs. Shared Server

Using a VPS for hosting your discord bot will allow you to fully utilize the server resources you pay for, without sharing them among multiple web applications or websites.

A shared hosting server is slower and more sluggish when compared to a dedicated server.

By following the VPS setup process in this guide, you’ll be able to set up a crisp and fast VPS host that makes your bot run surprisingly quickly.

Location, Location, Location

Since you have complete control over your VPS server’s location, when we get to the section of this guide where you choose your server’s zone, I’d recommend choosing one close to where most of your Discord users live.

Vps Server Location Matters

If that’s not possible, or if your audience is worldwide, I’d go with a centrally located server with low ping and excellent connection speeds.

If your audience is global, it’s never a bad idea to choose a major city in the United States; In my personal experience, this has been both reliable and quick for all of my servers.

For this guide, we’ll be going over a complete Discord bot hosting setup on Vultr.

I’ve used Vultr for five years and have never had uptime or reliability issues.

Ready to dive in? Let’s do it!

The Best Discord Bot Hosting Method

The best method for hosting Discord bots and having near 100% uptime is a third-party Virtual Private Server (VPS).

Vps Virtual Private Server Locations Worldwide - Nyc, London, Sydney, San Francisco

A Virtual Private Server is, as its name suggests, a “virtual” server that’s up and running 24/7 from your chosen location worldwide.

Even though it requires a little bit of setup to get up and running, the result is well worth it.

I like VPS hosting because it’s both extremely affordable (think, a few dollars a month) and super reliable (you won’t have to worry about your server going down, practically ever).

The flexibility you have with your own Virtual Private Server is completely unheard of when you compare it to having your own self-hosted solution or even using a managed Discord bot host.

In the next few sections, we’re going to walk through the process of setting up a VPS through Vultr, getting your bot up and running, and then testing out that connection to make sure your bot is working as intended.

Getting Your Code Ready and Version Controlled Through GitHub

Before we can begin setting up your VPS Hosting, there’s one very important thing we can’t forget: Version Control.

I want to start off by saying this step is optional but highly recommended.

What is Version Control?

Version Control in software is a way to keep track of every single change made to bits of code throughout the entire lifecycle of that code, from start to finish.

To put it simply, every single time you change something in your code (whether you add some functionality, fix/remove some bugs, etc.), you then “check-in” or “commit” your changes.

Benefits of Version Controlled Code

Once your changes are “checked in,” you’ll be able to go back and compare those changes to past versions, letting you clearly see what changed.

You’ll also be able to revert back to an old version if you accidentally break something.

This is great if you’re just starting out and want to have the freedom to experiment with your bot.

Taking note of all the reasons above, this is why we’re going to set up our Discord Bot Version Control system through GitHub first.

And if you’re wondering, “Why GitHub?” Two Reasons: It’s free, and it’s easy!

Version Control Your Discord Bot Through Github

We’re not going to walk through a detailed setup right now, as it’s out of the scope of this article (we’re talking about bot hosting, after all).

But there are some great resources you can follow along with to get version control set up from scratch.

Git Learning Resources

The first place you should browse around is the GitHub Guides help page. This has everything from quick lessons on how Git works all the way to more advanced Git topics.

If you want to go “straight to the source,” as they say, then I’d recommend starting with this guide on GitHub flow.

Once you’ve gone through that one and understand the basics, GitHub’s Hello World guide is a great starting point for going through the whole version control process from start to finish with some sample files.

Once you’ve placed all of your code under version control, you can rest easy knowing all of your changes are tracked and preserved!

Now let’s move on to the fun stuff — actually hosting your Discord bot through a third-party server.

Vultr VPS

And it begins… This is the part of the guide where we finally start setting up and configuring your Virtual Private Server to run your Discord bot 24/7.

We will be using Vultr as our VPS of choice since they have an awesome deal for WriteBots readers: Get $100 instantly to spend on hosting if you sign up with a brand new account! You get the $100 for several weeks, which is enough to test a lot of different bots.

Img 61Ff06Aa1D1A3 - Discord Bot Hosting

We’ll be showing all of this with an example ping-pong bot made in JavaScript / Node.js, but it can easily be modified to fit any programming language on any platform.

Suggested Reading: If you’re interested in coding/creating a Discord bot from scratch, take a peek at our detailed guide on how to make a Discord bot. We cover every aspect from start to finish, letting you create your next bot in confidence.

Your first step is to create an account on Vultr.

Once you have your account set up and you’re all logged in, we’ll begin setting up our bot step by step in the next section.

Step by Step Setup

You’ve created your account and you’ve logged into Vultr. You should be at the primary home screen that looks something like this:

Img 61Ff06Aa62A76 - Discord Bot Hosting

See that blue circle with the “+” inside? That’s what we’ll click next to deploy our new VPS.

Img 61Ff06Aa9Fae4 - Discord Bot Hosting

You can select either “Cloud Compute” ($2.50/mo lowest tier) or “High Frequency” ($6/mo lowest tier, but faster) and then choose a location that’s closest to the majority of your audience.

Note that some locations have more options for hosting types than others, such as the New York (NJ) location which offers more monthly hosting options.

If you don’t know what location you should choose, picking any of the US locations is always a safe bet.

Img 61Ff06Ab08E84 - Discord Bot Hosting

Next, you’ll have to choose your “Server Type” and “Server Size”.

For Server Type, I’d recommend going with 64-bit Ubuntu 21.10. It’s stable and has a lot of documentation around it on the web. Ubuntu is an easier Linux to work with for beginners, which also makes it a great choice.

For Server Size, I recommend choosing an option between $3.50/mo – $5/mo to start. I can hear you saying it already, “But why not the $2.50/mo option? It’s cheaper, isn’t it?” Well, the $2.50/mo option in Vultr only includes an IPV6 Address. It’s only the $3.50/mo and higher options that include an IPV4 address, which is needed to access your server using a “normal-looking” IP address (see below).

If this sounds “alien” to you, a quick explanation is how IPV4 vs. IPV6 addresses look:

Here’s an IPV4 IP Address: 127.0.0.1

Here’s an IPV6 IP Address: 3FFE:F200:0294:AB0D:0394:4567:8911:ABDE

You’ll be using this “IP Address” to connect to your server and upload your bot’s files, etc. You don’t want to be typing that IPV6 address each time, do you? Having an IPV4 address is much cleaner.

Of course, if you don’t mind it and are willing to research a bit, you can choose the $2.50/mo option with an IPV6 address. This is entirely up to you — but I’d recommend IPV4, or the $3.50/mo and up options, for beginners.

Img 61Ff06Ab48D60 - Discord Bot Hosting

For the next section, you can skip past “Additional Features” (unless you want to add Auto Backups and DDoS Protection), “Startup Script”, and “SSH Keys” for now.

The one piece you’ll want to fill out is the “Server Hostname & Label” section. This is where you name your server.

Once you’ve given your server a name and are satisfied with your settings, you can click the “Deploy Now” button!

Img 61Ff06Ab8061D - Discord Bot Hosting

You’ll see your new VPS server appear on the “Products” page in Vultr, and you’ll see a spinning orange indicator showing that it’s currently deploying/installing.

It can take up to

5 minutes for your server to be fully deployed.

Img 61Ff06Ab8F639 - Discord Bot Hosting

Once the indicator stops spinning, you’ll see that your server is “Running” and ready to go!

You should also be able to see the IP Address of your server next to its name.

Img 61Ff06Aba15C1 - Discord Bot Hosting

Congratulations! You’ve successfully set up your first VPS.

We just have one little problem… it’s empty and there’s nothing currently running.

In the next section, we’ll talk about how to connect to your VPS, load all of your bot files into it, and get your bot up and running on your Discord server.

Getting Your Discord Bot Running 24/7, 365

You’ve “deployed” your empty VPS, and it’s sitting there waiting for your next command… what should you do next?

Well, here’s what we’re going to do: Load up all your bot files and start up your Discord bot! We’ll walk through doing this step-by-step in the next few sections of this bot hosting guide.

Logging Into Your VPS Server

But first, we’re going to want to take a look at our VPS in more detail. Click the name of your server on the Vultr “Products” page to dig deeper:

Img 61Ff06Abaf266 - Discord Bot Hosting

Once inside, you’ll see something like this:

Img 61Ff06Abbddf0 - Discord Bot Hosting

You may notice that orange message lingering at the top, saying that it might take a few minutes to boot up and activate your server. You can ignore this message after you give your server about 5 minutes to boot up.

You can also see your server administrator, also known as root, “username” and “password” (click the little eye to show your password, and the paper icon to copy the password).

This is what you’ll use to log in to your server and have full control over its configuration.

Logging In Through Secure Shell (SSH) on Windows, Mac, and Linux

The best way to login into your server and start sending commands is through the Secure Shell Protocol (SSH). Whether you’re using Windows (10+), Mac, or Linux, each of these operating systems will allow you to connect to your server through SSH.

We’re going to walk through the process on Windows, Mac, and Linux so that you can connect to your server and start setting up your Discord bot.

Windows SSH Connection to VPS

For Windows 10 and up, SSH is included inside of Command Prompt, making it very convenient to connect to your server.

Image - Discord Bot Hosting

In the examples below, I’ll be using Windows 10 to connect to my newly created Vultr VPS.

  1. Open up Command Prompt on your machine
  2. Once the command prompt is opened, type the SSH command, substituting the “xx.xx.xx.xx” for your server IP found on your Vultr control panel:
    ssh root@xx.xx.xx.xx
  3. If you get a message saying, “The authenticity of the host can’t be established”, this is okay. Type “yes” into the command prompt and hit enter.
  4. Copy your password from Vultr and paste it into the Command Prompt window. Note that for security purposes, the characters of your password will not show up in the black console window as you’re typing them, or if you copy/paste them. This is normal. Hit enter to submit your password and log in.
  1. Once you’ve logged in, you’ll see the terminal window become: “root@your-server-name”. Congratulations, this means you’ve successfully logged into your server!
  1. Now that you’re logged in, you can move on to the “Learning Three Easy Linux Commands” section below.
Mac SSH Connection to VPS

If you’re on a Mac, you can easily connect to your VPS through Secure Shell (SSH) by using your terminal. The following steps will show you exactly how it’s done.

  1. Open your Mac terminal.
  2. Referencing the image below, type the SSH command following the format below, and replace xx.xx.xx.xx with your VPS IP:
    ssh root@xx.xx.xx.xx
  3. On the “Authenticity of this host can’t be established” message, simply type “yes” in the terminal and press enter.
  4. Copy and paste the password of your VPS from the Vultr control panel into your terminal. You can also manually type the password if you choose.
  5. Success! You should be logged in to your server’s root home folder.
Linux SSH Connection to VPS

To connect to your VPS on Linux through Secure Shell (SSH), all you need to do is follow a few simple steps.

  1. Open your terminal.
  2. Type the SSH command, replacing xx.xx.xx.xx with the IP address of your VPS server (found on the Vultr control panel).
    ssh root@xx.xx.xx.xx
  3. If you get a message saying “The authenticity of the host can’t be established”, type “yes” and hit enter.
  4. Copy and paste your password from your VPS information page on Vultr
  5. You should be successfully logged in and ready to configure your Discord bot!

Once you’ve logged in, you’ll automatically find yourself in the “home” directory, which is indicated by the tilde “

Now it’s time to set up your directory, get node.js and npm setup, and then load all of your bot’s files.

Learning Three Easy Linux Commands

Before we get into the details, you’re going to learn a few very easy-to-remember Linux commands.

Linux Command mkdir: Make a Directory

The first command is to make a folder or a “directory”. The command is short for “Make Directory”, and is spelled out like so: mkdir.

Here’s how you would use this command in action:

Based on where you currently are in the console window, this command will create a folder and name it “my-special-folder”. Easy-peasy.

Linux Command ls: List All Files In the Current Directory

The next command we’re going to learn is used to list all of the files in the current directory you’re in.

Here’s how you would use it:

You would type two characters, “ls”, and what you would see in your console is a list of files currently in that folder. It’s a simple command.

Linux Command cd: Go to a Directory of Choice

The final command you’re going to learn is how to “jump” into another directory. Since all we’re doing is typing and not actually clicking to jump from folder to folder, you’ll have to use the “Change Directory” command, which in shorthand turns out to be: cd.

Here’s how you would use it to jump from the current directory to a subfolder called “test”:

And an example: (## are comments)

And that’s all there is to the “change directory” command.

Putting These Commands Together and Setting Up Your Project

So, before we even get started, let’s type “ls” in the window. Since we don’t currently have any files in our home directory, you should get — nothing! There’s a chance you’ll have a “snap” folder, but this can be ignored.

Img 61Ff06Ad1C3C5 - Discord Bot Hosting

Now, if we create a directory named “ping-pong-bot” and then type “ls” again, we should see that directory be created on our server. Let’s give it a shot.

Img 61Ff06Ad23Fd9 - Discord Bot Hosting

And there we have it… It worked. We created a folder (directory) called “ping-pong-bot”, and then saw it appear once we listed everything in our current directory.

All that’s left for us to do now is use the “Change Directory” command to go inside the ping-pong-bot folder:

Img 61Ff06Ad2Cde8 - Discord Bot Hosting

And there we have it, we’re in the /ping-pong-bot/ directory!

Installing Node.js and Node Package Manager

Next, we’re going to install node.js on our server.

This can be done with a few quick Ubuntu commands (type each line one at a time):

Img 61Ff06Ad36758 - Discord Bot Hosting

Once you type that command you’ll see it read the package and ask you if you want to install it.

You’ll want to type “y” for yes, and the installation will continue. It may take a few minutes to fully install, so be patient at this stage.

Optional Step: If you get a “Kernel outdated” message, and a pink screen like shown below, click “Enter” on the first screen, and then hit “Tab” to jump to the <Ok> button. Once <Ok> is selected in red, click “Enter” again to restart the recommended services on your VPS.

Img 61Ff0639E186F E1644103301204 - Discord Bot Hosting Img 61Ff063A62C44 E1644103314564 - Discord Bot Hosting

Once you’re back in the subfolder you created, node.js has been installed:

Img 61Ff06Ad42565 - Discord Bot Hosting

Now we’ll want to do the same thing with NPM, which is “Node Package Manager”

Type this command to install it:

You’ll have to type “y” again for yes to continue installation, just like when you installed node.js in the previous step.

Once you’ve installed node.js and npm, time to check the installation.

To do that, we can use two commands to check their versions:

Img 61Ff06Ad4D6B7 - Discord Bot Hosting

We’re getting version numbers for node and npm, but these are out of date!

The next section will guide you through updating these versions.

Updating NodeJS and NPM

In order for our Discord bot to work correctly, we have to have a NodeJS version of 16.x and above. By running a few simple commands, we can update our Node and Npm installations:

Img 61Ff08D8671B6 - Discord Bot Hosting

You should see higher version numbers, and your node -v command should return a version 16 and above.

Setting Up Our Node.js Project

Now we want to “initialize” our project using the Node Package Manager.

This is done through one simple command, and it’ll bring up a “wizard” where you follow along with the steps and type in your responses.

Important: Before you type the “npm init” command, make sure you’re still in the right folder!

Node will be creating all of your project’s files in the folder you are currently in, so double-check the path to make sure you’re still in the right one.

Here’s what the setup process for “npm init” should look like.

I just kept hitting “enter” to go with default values, and the only thing I changed was the “Description” field.

Img 61Ff08D88Bf9E - Discord Bot Hosting

Once you type “yes” at the end, your node project will have been created.

Installing the Discord.js Library to Make Life Simple

To make life super easy we’re going to be using the “discord.js” library in our ping pong bot.

A library is a set of pre-written code that interfaces with the Discord API; this is what lets us send/receive commands from Discord to/from our server.

Additional Reading: If you want to learn more about setting up discord.js and libraries, check out this guide on how to make a Discord bot. You can also jump straight to the libraries part of the guide, or directly to the JavaScript bot creation portion.

In any case, installing the “discord.js” library is very simple, involving just one Linux command.

In your Vultr server console (or your own SSH client; see the SSH client section of this guide), while in your bot’s directory, type the following command:

You’ll see different colored text while the installation process finishes.

Img 61Ff08D8B2468 - Discord Bot Hosting

By adding –save to the end of our “npm install” command we made sure that our package.json file was updated to include discord.js as a dependency.

We’ll verify our installation in the next section.

Verifying Our Installation

It’s time to make sure everything is installed correctly.

The first thing you’ll want to do is type “ls” to list all of the files in this directory. You should see the new “package.json” file that was created when we ran “npm init” and also a new folder titled “node_modules”:

Img 61Ff08D8Cde6D - Discord Bot Hosting

The node_modules folder contains our new “discord.js” dependency that we just installed.

We also want to double-check the “package.json” file to make sure “discord.js” was added as a dependency.

We can do this by running the “cat” command:

After this command has been executed, we should see its contents with the “discord.js” dependency included successfully:

Img 61Ff08D8F214E - Discord Bot Hosting

Success! Everything we need has been installed.

All that’s left for us to do is upload our bot’s files to the server and get our bot up and running! We’ll do this in the next section step by step.

Uploading Your Bot’s Files

Whew! The tough part of our setup is all finished!

From here on out, all that’s left for us to do is to (1) Upload your bot’s files and (2) Launch your Discord bot!

Remember how in the last section, we ran “npm-init” and used the default “Entry Point” or “main” filename: index.js?

You can either modify your node package.json file and change the entry point file name to whatever you’d like, or you can leave it at its default “index.js”.

Note: If you want to modify your “package.json” file straight from the command line, you can do it with nano! Nano is a Linux text editor that lets you modify files on the fly.

To learn how to use nano, check out this guide to nano. But before you read that guide, this is very important: Whenever they write “^X” or “^K”, anything with a carat (^) before a letter, the carat is the CTRL key on your keyboard!

This means that “^X” is CTRL+X on your keyboard. I just wanted to clear this up, as it’s very commonplace to get stuck with the nano text editor.

Important: To use nano, you’ll need your own SSH client. Take a look at the SSH section of this guide above (Windows, Mac, Linux) for more details on setting this up.

If you look inside of your package.json file (by typing the command: “cat package.json”), you’ll see what your current “main” is set to.

Img 61Ff08D919F99 - Discord Bot Hosting

Anyways, let’s actually upload our bot’s main file containing all of our code.

Here’s what our “index.js” will contain:

This is a simple bot that uses the “discord.js” library to write a message as soon as the bot is all started up and loaded saying, “Ping Pong Bot Loaded!”

As soon as someone types a message that says “Ping”, our bot will reply, “Pong!” Super simple.

IMPORTANT – DO NOT SKIP: Don’t forget to create your bot application and get a token. If you haven’t done this yet, check out this guide on how to get a discord bot token. It walks you through setting up a “bot app” on Discord and revealing your token.

Once you have your token, be sure to replace the “your-bot-token-goes-here” inside of index.js with your token. This is critical, and your bot won’t connect to Discord otherwise.

To make uploading our files as easy as possible, we’re going to connect to our server through an application called “Filezilla”.

Filezilla Client Logo

Note: You can download FileZilla directly from this link.

Once you’ve downloaded FileZilla, open up the client! You should see a screen similar to this (except your color scheme may be different from mine):

Vultr Vps Sftp Secure File Transfer Protocol Filezilla Connection

You’ll want to click that icon in the upper left-hand corner in order to set up a connection to your server.

Vultr Vps Sftp Secure File Transfer Protocol Filezilla Connection - New Site Button

And then, you’ll want to click the “New Site” button.

This is where you’ll have to go back to Vultr and get your IP Address, Username, and Password from your “Server Information” Page:

Vultr Server Information Page - Root Credentials

You’ll need this information for the next few steps in order to connect to your server.

What you want to do next is to select the following settings:

  • Protocol: SFTP – SSH File Transfer Protocol
  • Port: LEAVE EMPTY
  • Logon Type: Normal
  • User: root (from Vultr)
  • Password: (from Vultr)

Then click on the “Connect” button!

Vultr Vps Sftp Secure File Transfer Protocol Filezilla Connection - Site Manager Setup

Since this is your first time connecting to your server, and because we’re connecting securely through the “SSH File Transfer Protocol,” you’ll have this message come up:

Vultr Vps Sftp Secure File Transfer Protocol Filezilla Connection - Unknown Host Key Dialog Box (Certificate)

Click the “Always trust this host” checkbox to acknowledge the message and hide this prompt whenever you connect in the future.

You should then connect and see all of your server’s files in the “Remote Site” right-hand side of FileZilla!

Filezilla Sftp Secure File Transfer Protocol - Vultr Vps Connection

We can see our ping-pong-bot folder listed, and can now click through and browse around on our server just like we would on our computer.

The first thing you want to do is browse into your bot folder (in my case, I clicked into ‘ping-pong-bot’).

Now, I’m going to go on my computer, create a text file called “index.js”, and paste the bot code from the last section.

I’ll then save this file and drag it into the ping-pot-bot folder on FileZilla to upload it.

… so I did just that. I created the “index.js” file on my computer and saved it. Don’t forget to include your token!

Atom.io Text Editor - Discord Bot In Discord.js (Ping Pong)

Then I dragged the file into the ‘ping-pong-bot’ folder on FileZilla, and saw it uploaded successfully:

Vultr Vps Sftp Secure File Transfer Protocol Filezilla Connection - Uploading Index.js File To Vultr

To double-check this, we can go into our Vultr server console (or SSH client) and type “ls” to list all files:

Img 61Ff08Daa6A52 - Discord Bot Hosting

Yep, “index.js” is definitely there!

And as a final sanity check, we can even do “cat index.js” to see its contents:

Img 61Ff08Dacde01 - Discord Bot Hosting

Yep.. that definitely looks like our ping pong bot’s code, alright!

Important Step: If you haven’t already generated your Discord bot token and added it to your bot’s index.js file on your Discord server, follow along with the discord bot token guide to get all of this setup.

Img 61Ff08Db059D5 - Discord Bot Hosting

The final step in this process is to get our bot up and running and then test it out on Discord!

Getting your Discord bot up and running

We are on the final few steps before we can actually see our bot in action on Discord.

Continuing the Process: Installing a Process Manager

The next thing we need to do is install a process manager. Why you might ask?

Well, a reliable process manager is going to let us run multiple bots on our VPS (if we so choose), and perform all of the memory management required to keep every task operating at its peak.

Pm2 (Process Manager 2) Logo

PM2 (Production Process Manager for Node.js) is an awesome choice that’s very widely used with Node.js projects.

Check out PM2’s website for more details on its capabilities as well as installation instructions.

Installing PM2 is super simple and requires running this command on your server’s command line (or SSH shell).

Make sure you “cd” (change directory) to your main bot’s project folder before running this command:

You should see the installer doing its thing:

Img 61Ff0Ad5E50F8 - Discord Bot Hosting

… and as soon as the progress bar stops scrolling, PM2 should have been installed successfully!

To test if PM2 was installed successfully, we can list all currently running processes (which should be none, since we haven’t started any!):

Img 61Ff0Ad5Efce8 - Discord Bot Hosting

Yep, just as expected, no running processes. Time to fire up our bot!

We can do this through another simple command using pm2:

Note: You should change “index.js” to whatever your bot’s main code filename is.

Note: pm2 start will fail if you forgot to “cd” into your “ping-pong-bot” directory. Double-check this.

After you run the “pm2 start” command, should see a message from PM2 saying that it started an instance of your bot, and your bot should now be successfully running!

Img 61Ff0Ad607Fb1 - Discord Bot Hosting

Success! We can see App Name shows “index”, and or Status shows as “online”!

If you ever want to stop your bot (or any process you start with PM2), all you have to do is run the following command:

And if you ever want to list all your currently running processes, you can run a simple “pm2 list” command on your server.

Troubleshooting: If you run “pm2 list” and your bot shows as “errored” in red text (see screenshot below), this might be because you didn’t add your Discord bot token to index.js. I can’t stress enough how important it is that you did this.

To see exactly what your Discord bot’s error message is, type the command:

This will open up the PM2 error log, letting you see the Discord.js error messages that prevented your bot from running. Copy and pasting these messages into a search engine is the quickest way to get a sense of direction.

Img 61Ff0Ad61779B - Discord Bot Hosting

If your bot is up and running, running pm2 list should show as green and “online”:

Img 61Ff0Ad626Fdd - Discord Bot Hosting

Congratulations! You have just hosted your first bot on a Virtual Private Server, all on your own! Give yourself a pat on the back — getting this far is a big deal!

You now know how to host one bot and even multiple bots on a single VPS!

For multiple bots, you would do the same exact thing we did here and just start up another process on PM2. Easy peasy.

In the next section, we’ll see our bot live on our Discord server and watch it actually running in the wild… let’s do it.

Testing Our Bot on a Live Discord Server

The last step is testing our bot out “in the wild” on an actual Discord server!

Important: In case you haven’t generated a token yet and added your bot to Discord. Read through our guide on how to get a Discord bot token for step-by-step instructions on adding your bot. Make sure your token is inside “index.js” or you may see errors.

I have already added “ping-pong-bot” to my Discord server, and since our process is actively running in PM2, we can see this bot as ONLINE!

Success!

Discord Bot In Server - Ping Pong Bot Is Online

All that’s left for me to do is test out my code by typing “Ping”. If all works as it should, my bot should say “Pong!” in the chat.

Let’s give it a try…

Discord Bot In Server - Responding To Ping Command (Working Bot)

It works. Our bot is officially up, running, and online!

Shutting Off Your Discord Bot

As a final step, you might want to stop or restart your bot if you’ve made changes to your code, or just want to start up another bot.

As I mentioned earlier, PM2 lets you run multiple bots (as many as your server permits). Since node.js is rather light, on Vultr’s $5.00/mo plan you should be able to run several bots with at least 100+ connections.

This is a rough estimate, of course, and depends on how much memory your code actually uses (and how big your bot is). The point here is, you should be able to easily host multiple Discord bots without issue!

And if you ever wanted to upgrade, you could easily “clone” your Vultr VPS over to a larger more powerful instance.

Anyways, lets first list the processes we have running in PM2 with the “list” command:

Linux Command Line Console - Pm2 (Process Manager 2) List Command Executed

And then we can stop our app by typing “pm2 stop <app name>”:

Linux Command Line Console - Pm2 (Process Manager 2) Stop Command Executed

To verify, let’s go on Discord and check if our bot is offline:

Discord Bot In Server - Bot Is Offline (Turned Off In Pm2 Process Manager)

Crickets. Our bot is definitely offline.

Final Thoughts on VPS Discord Bot Hosting

And this concludes our Discord Bot Hosting guide.

You should now know everything you need to know to get your JavaScript / Node.js bot up and running on your own, personal Virtual Private Server.

If you want to host your bot in a similar language such as Python, all you need to do is install Python on your Vultr, and… you’re good to go! (you just won’t be able to use PM2)

The same goes for any programming language or code you want to run.

Even if you wanted to run a “Discord Bot Maker” instance, you could do so by installing Windows on your VPS and starting it up from there (just remember that Windows VPS servers are more expensive monthly than Linux, which is why we tend to go with a popular Linux distro like Ubuntu).

Either way, you’ve achieved what most won’t — hosted your own Discord bot on your own VPS.

For that, I want to say congratulations and good luck on your botting journey!

Alternative Discord Bot Hosting Options

Hosting your Discord bot on your own VPS is the best option, but not the only option.

If setting up a VPS just isn’t for you, or if you simply like exploring alternative hosting options, then this is the section for you.

We’re going to cover hosting your own Discord bot on the Heroku platform, we’ll talk about Amazon AWS, and then to conclude we’ll go through an example of hosting your very own Discord bot on a Raspberry Pi.

Let’s get moving!

Heroku

Heroku is a cloud application platform that lets you deploy your apps in the cloud and get them running nonstop, 24/7.

Heroku Logo

It works for hosting Node.js, Ruby, Java, PHP, Python, and Go code.

Heroku is free if you just want to experiment with your bot, but paid if you want your server to be up and running nonstop. The free version of Heroku lets you deploy an app (they call them “dynos”), but it’ll go to sleep after every 30 minutes of inactivity.

As of the time this article was written, the cheapest paid plan for Heroku came in at $7/mo.

This is considerably more than hosting a bot on your own VPS where you can:

Heroku is especially handy if you have most of your bot’s code on GitHub since there’s an “automatic deploy” option that pulls your code from GitHub and copies it over to your Heroku Dyno.

Important Note: If you put your code on GitHub and use “automatic deploy”, make sure your repository is set to private because it’ll have to include your Discord bot token! Never make your repository public with your token visible.

Heroku Node.js Page For Discord Bot Hosting

In either case, Heroku can be a good hosting option depending on what you want to get out of it. Let’s go through the process of setting it up.

Setup Guide: Hosting Your Discord Bot on Heroku

For our example setup, we will be powering up a Discord bot written in JavaScript / Node.js on Heroku. This bot will also be using the Discord.js library to interface with the Discord API.

Here is the Discord.js on Heroku guide we’ll be following along with.

The guide starts by going over some Heroku basics and then introducing the files you need in your project for hosting on Heroku (package.json, Procfile, .gitignore, and index.js).

You’ll then install all of the prerequisites you need to get your bot up and running, including Node.js, Git, GitHub, and the Heroku CLI (command-line interface).

You’ll then run the “npm init” command (just like we did in our VPS hosting portion of this guide, up above) to create your package.json file, and then create a Procfile.

Heroku uses the “Procfile” or “Process File” to determine what processes are started on each of your “Dynos.” For clarity, a “Dyno” is your virtual Heroku Container or “miniature server” in a sense.

Once you’ve done that you’ll get your code transferred to your Heroku Dyno, and then deploy your app!

That’s all there is to it. You have successfully deployed your JavaScript / Node.js bot on Heroku!

Note: If you want more reliable hosting and complete ownership of your Discord bot’s server, I recommend following the first part of this guide and setting up your own VPS.

AWS (Amazon Web Services)

AWS, or “Amazon Web Services”, has been taking the world by storm. In fact, there are hundreds of Fortune 500 companies using AWS to power their internet infrastructures.

Amazon Web Services Logo

This makes AWS sound like a pretty reliable bet, doesn’t it?

Amazon Web Services Ec2 (Elastic Compute Cloud) Homepage For Discord Bot Hosting

For clarity, AWS is the “overarching” platform containing all of Amazon’s services. For hosting our Discord bot specifically, we’ll be using Amazon EC2 — Short for ECC or “Elastic Compute Cloud”.

This is where we’ll be able to deploy our own mini-server through EC2, and then get it up and running with our Discord bot.

Note: Even though Amazon EC2 has great value in your first year, we recommend setting up your own VPS Discord bot hosting for a slightly easier setup (see the first part of this guide for details). EC2 offers 750 free hours for the first year on their “EC2 Micro Instances” — after that, you’ll be paying for uptime.

For our AWS / EC2 hosting example, we’re going to be creating an EC2 Cloud Instance and deploying a JavaScript / Node.js bot.

Here is the Node.js bot deployment on EC2 guide we’ll be following along with.

That guide is super in-depth and covers everything you’ll need to know for deployment to EC2 — perfect for our purposes!

You’ll start by creating a server instance through EC2 (running on Ubuntu, to be exact), and then launching that instance.

Once it’s launched you’ll set up SSH (Secure Shell) access to your AWS server, and then upload your files through SFTP.

What you’ll be doing here is very similar to the process we took in the first part of this guide to set up VPS bot hosting on Vultr. One of the big differences I noticed is using the “Forever” Node module for consistent 24/7 uptime rather than using “PM2” as we did in our guide.

Once you’ve gotten your EC2 instance configured with all of your bot files loaded, you’ll launch your bot!

This method does require some light Linux knowledge and commands, but it’s not that difficult to follow along from start to finish.

Raspberry Pi

Raspberry Pi Logo

A Raspberry Pi is a “miniature computer” — and that’s right, you can host your own Discord bot from your own R-Pi and have it up and running 24/7 (as long as you don’t lose power!)

As of the time this guide was written, the latest version of the R-Pi available on the market was 4.0, but you can still find older Raspberry Pi versions for sale on the web.

Raspberry Pi 4 Homepage For Discord Bot Hosting

Hosting our Discord bot on a Raspberry Pi is going to be very similar to the process we took to host on a VPS since we’ll still be using JavaScript / Node.js and working on a Linux platform.

Note: Your Raspberry Pi can be a very reliable Discord bot host, but it only goes so far as you’re able to keep it up and running. If you have a bot used by lots of different servers, your R-Pi may struggle to keep up with memory/resources. This is why we still recommend hosting your own Discord bot on a VPS.

Here are the guides you can follow along for Raspberry Pi Hosting:

If you want to host a JavaScript / Node.js bot, install Linux on your Raspberry Pi and follow our VPS instructions exactly as they’re written – easy as that!

If you want to host a Python bot with Discord.py, follow along with this Python Raspberry Pi hosting guide. Difficulty: Intermediate

No matter which guide you choose, both will get you to a working Raspberry Pi server for your Discord bot.

I mentioned earlier that the process of an R-Pi is going to be very similar to how we hosted our bot on a VPS.

This is because it’ll start out with you connecting to your Raspberry Pi, then installing either Node.js or Python.

Once you’ve installed your code runtime environment, you’ll move on to loading your bot files into the Raspberry Pi.

And finally, once all of your bot’s files are loaded, you’ll be able to start them up and get your bot running! The Node.js guide uses PM2 for process management (just like we did in our VPS hosting guide above), and the Python guide uses the Python runtime environment to launch your Discord bot.

Once you’ve launched your bot, make sure to periodically check in on your Raspberry Pi to ensure things are running smoothly.

And when your bot grows and starts being used by more servers (and more users simultaneously), you can always transfer over to VPS hosting to handle more bandwidth.

Free Discord Bot Hosting

Most of the Discord bot hosting options we’ve covered up until now have been paid or premium solutions.

These are, of course, the best options for reliable hosting — but what if you wanted to do it absolutely free?

Well, you’re in luck because there are a few ways you can host your Discord bot for free without any Virtual Private Servers or Cloud Instances.

The first method we’ll talk about is “Glitch,” and the second method we’ll cover is simple “Self-Hosting” from your own computer.

Remember: Both of these hosting methods won’t be as reliable as an official, third-party VPS host, but we can get some fairly decent reliability by implementing a few “unique tricks.” Stay tuned for those.

WriteBots VPS Offer: Get a free $100 to spend on hosting your own Discord Bot when you sign up today!

Self-Hosting

Self Hosting Your Discord Bot - Writebots

This is the ultimate free hosting option — running your Discord bot from your very own computer.

Of course, this will only work well if you (1) Have your computer up and running 24/7 without going into sleep mode and (2) Have a fast internet connection to handle API requests to your Discord bot.

Fortunately, hosting on your own computer is extremely simple.

All you have to do is install your code runtime environment (whether that’s Node.js, Python, Java, etc.), and then run your bot… that’s it.

Once your bot is running it’ll connect to and communicate with the Discord API, and run as it normally should.

If you’re just getting started with Discord bots, this is a great way to test your bot and make sure it’s working correctly.

If you’re looking for more permanent solutions, then you should consider getting your own private VPS server to host your bot and keep it up 24/7, 365.

This is the simplest way to host a Discord bot and one that you should definitely have tried first when testing your bot or just starting out.

Hosting Specific Types of Discord Bots

So far, we’ve talked about hosting Discord bots at a very “general” level. We just assumed that your bot is a “black box” with some code, and your goal is to get it up and running on a reliable server.

This is all well and good until we get to some more specific examples of bots that need to be hosted.

In this section, we’re going to go over the process of hosting a Discord Music Bot, Discord.js Bot, and even bots made with Discord Bot Maker.

Discord.js Hosting

Hosting a bot made with Discord.js is one of the most common methods on the web today.

This involves having Node.js up and running and then installing the Discord.js module via. NPM (the Node Package Manager).

Discord.js Homepage For Discord Bot Hosting

We cover Discord.js hosting in extreme detail in the first part of this guide.

If you follow along with the beginning of this hosting guide from start to finish, you’ll pick a reliable VPS host, get your code version controlled, set up your VPS server, and then load up your Node.js / Discord.js code.

By the end, you’ll have a fully configured VPS server running your Discord bot all day, every day.

And again, since we already covered this in detail in the first part of this guide, we’re going to point you over there to get your Discord.js bot hosted and ready!

Music Bot Hosting

Discord Music Bot Hosting - Writebots

Hosting a music bot is, as you would imagine, more difficult than any regular Discord bot.

Since music bots actively buffer and stream data, they take up a lot more bandwidth and a lot more memory than your typical Discord chatbot.

For this reason alone, we’d recommend going with a VPS hosting solution to bring up your music bot to its maximum potential.

Follow along with our VPS Bot Hosting Guide for more details on how to get your bot up and running with third-party hosting.

The process should be exactly the same, except for the additional audio modules/codecs your bot requires. Unfortunately, this isn’t a “one size fits all” with every music bot using different modules and/or codecs.

One of the most popular codecs is FFmpeg, so your Discord Music Bot may be using it as a dependency.

Either way, your next steps are two-fold: (1) Find out which codecs/modules your music bot uses (2) Install those modules on your VPS in addition to the rest of the modules you need to run your bot.

Once you have all of your modules/codecs installed, you’ll be able to start up your bot and then test it out on your Discord server.

Discord Bot Maker (DBM) Hosting

Hosting A Discord Bot Maker Bot On A Vps

Ah, Discord Bot Maker.

I’m personally not a fan of the software (it’s too limited in my opinion, compared to what you can create on your own), but there are those of you out there who love it and want to host your own bot with it.

I can respect that.

This part of the guide walks through everything you need to know about hosting a bot made with Discord Bot Maker. It should be very simple to follow.

To host your Discord Bot Maker creation, you have one of two options:

Option 1: Self-Host your Discord bot on your own personal computer

Option 2: Get a third-party VPS with Windows on it and then install/run DBM.

DBM Hosting Deal for a Windows VPS: Since you’re a WriteBots reader, there’s an awesome deal where you can get $100 free to put towards VPS hosting just for signing up! Take advantage of this before it disappears, and don’t forget to choose the “Windows” server option.

If you’re going with “self-hosting,” all you need to do to host your DBM bot is just… to start up Discord Bot Maker and run your bot!

And if you decide to go with a Windows VPS Host, you’ll have to connect remotely through RDP (Remote Desktop Connection) and then install DBM that way.

Once you’ve done that, you’ll have your very own Discord bot created in DBM and hosted on your own server. Great work!

The Impact of Reliable Hosting on Your Discord Server

Having reliable hosting for your Discord bot is crucial to your user experience.

Imagine if one of your frequent Discord Server users joined a channel with your bot, tried to use your bot, and kept getting the disconnected or “offline” message every single time.

I don’t know about you, but I’d be upset/annoyed if it happened consistently.

Having reliable bots on your server that are up and running no matter what time of day it is — that’s how you grow your server to new levels.

Don’t make a bad impression on your new and seasoned Discord users.

Get reliable hosting for your bots.

Final Thoughts

We’ve covered a lot here.

This guide should’ve taught you everything from hosting your JavaScript/Node.js bot through a Virtual Private Server (VPS), all the way to specific types of hosting for bots made on Discord Bot Maker or the Raspberry Pi.

No matter your goal with hosting your Discord bot, I sincerely hope this guide gave you all of the answers you needed.

Leave a comment below and let me know if there’s anything you’re stuck with, have a suggestion on, or think is missing from this guide.

I wish you the best of luck with your Discord bot hosting endeavors!

Как поставить бота дискорд на хостинг

Боты в Дискорде играют незаменимую роль. Они помогают администрировать серверы, развлекать пользователей, расширяют функционал мессенджера и интегрируют каналы с другими приложениями. Чтобы боты всегда были на связи, их устанавливают на специальный компьютер, который постоянно имеет доступ к интернету и никогда не выключается. Такие компьютеры называются хостингами. Расскажем, как выбрать хостинг для работы и залить туда бота для Дискорда.

Хостинги для ботов

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

screenshot_1

CLOUD4BOX

По сути, для работы бота не подойдет обычный хостинг, который используется для сайтов. Вместо этого сайт предлагает покупку выделенного сервера (DS) или виртуального сервера (VPS). Разница между ними в том, что виртуальным сервером могут одновременно пользоваться несколько участников.

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

Выделенные серверы дороже. Например, VPS с конфигурациями, указанными ниже, будет стоить 2406 рублей. Выделенный сервак дороже, он стоит 4800 рублей в месяц.

Конфигурация Значение
CPU 9×3.0 GHz
RAM 16 GB
Disk 240 GB (SSD)
IP IPv6
Канал 1 Гбит/с
Ядро ОС Linux

В целом, для ботов подойдут и обычные VPS, так как им не нужна гибкая настройка. Предупредим сразу: компания не предлагает услуги из категории «hosting free», да и в таких услугах нет смысла. Бесплатный сыр, как известно, только в мышеловке.

screenshot_2

Более подробно о сайте и услугах читатель может узнать на офф сайте.

SPRINTHOST

А на очереди у нас очередной российский поставщик услуг, предлагающий выгодные и практические решения. В отличие от конкурента выше этот провайдер не мучает пользователей гибкой настройкой, а предлагает сразу готовые решения. Особенно полезно, если клиент плохо разбирается в устройстве компьютера. Да, и такое бывает, особенно если бота заливает не разработчик, а тот, кто перекупил его. Здесь также доступны обычные хостинги для сайтов. VDS и выделенные серверы. Самое дорогое предложение (VDS) стоит 340 рублей, а это мало, учитывая сборку компа.

screenshot_3

SIMPLE CLOUD

«Зарегистрируйся и получи 100 рублей» – гласит надпись на главной странице сайта. Уже заманчиво, а вы еще не видели предоставляемые услуги. Компания предлагает услуги поддержки облачного хостинга, но также не позволяет вручную собрать аппаратную конфигурацию. Вместо этого пользователю предлагается 16 разных решений (по сути их 8, но пользователь может увеличить вдвое ОЗУ в каждом). Стоимость самого дорогого тарифа – 22 400 рублей, но при этом клиент получит 128 GB ОЗУ и 400 GB SSD. Для бюджетников доступен тариф за 150 рублей, но там только 512 MB ОЗУ и 5 ГБ памяти.

screenshot_4

Botghost

У этого варианта существует ряд преимуществ:

  1. Разработан именно для ботов. Говоря точнее, поддерживается интерфейс создания бота без программирования. Причем это бесплатно.
  2. Англоязычный сайт. Для тех, кто не верит в российские сайты.
  3. Прямая интеграция с Дискордом. Не придется поднимать npm, сервер, закидывать файлы.

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

screenshot_5

Как поставить Дискорд бота на хостинг

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

Были времена, когда люди все делали сами. Конечно, поручить тяжелый физический труд они могли автоматизированным машинам. Однако умственные операции, где нужно производить логический анализ, поручить было некому. С недавнего времени эта проблема решилась программами с готовыми логическими инструкциями, которые называются ботами. Расскажем, как создать собственного бота в сервисе Дискорд, который считается одним из лучших мессенджеров в 2022 году.

С чего начать

Может, где-то на просторах интернета и «гуляют» готовые конструкторы (их иногда называют Creator) ботов, они довольно ограничены по функционалу. Так как невозможно предсказать все желания пользователя. Потому мы будем рассматривать разработку Discord bot на основе языка программирования JavaScript(JS), а точнее платформы Node.js. Первым делом необходимо создать приложение в базе Discord.

screenshot_1

Для этого выполните следующие действия:

  • Перейдите по этой ссылке. Рекомендуем сделать это не на телефоне, а через компьютер.

screenshot_2

screenshot_3

  • Введите название для приложения. В будущем оно будет отображаться как имя бота.

screenshot_4

screenshot_5

  • Найдите поле «Token». Кликните по ссылке под ним. Должен появиться длинный текст из разных символов. Это и есть токен, с помощью которого происходит обращение к боту.
  • Скопируйте его и сохраните куда-то. Без него обращение невозможно. Также не рекомендуем показывать этот токен кому-либо, так как этот кто-то сможет управлять вашим приложением.

screenshot_6

Готово. Местечко для приложения мы уже подготовили. Осталось установить сам код на выделенном хостинге.

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

В нашем случае будет использовать VDS (виртуальный выделенный сервер) с ОС Ubuntu 18.04. Если вы новичок, то рекомендуем остановиться именно на этом дистрибутиве. Сам сервер необходимо арендовать. Для обучения можно найти и бесплатный хостинг. Для подготовки сервера выполняем следующие действия:

  • Запустите сервер и откройте терминал. В Ubuntu достаточно нажать ПКМ по рабочему столу и выбрать «Терминал».
  • Введите следующие команды:
    sudo apt update

sudo apt install docker npm.

screenshot_7

Таким образом мы установили npm, который нужен для установки пакетов node.js. Уже непонятно? Тогда рекомендуем для начала ознакомиться с базовым курсом по JS и Node.js. Впрочем, если полностью следовать инструкциям, дополнительный материал для изучения не понадобится.

Создание основных файлов бота

Теперь переходим к разработке самого программного кода. Любой исполняемый код должен помещаться в текстовом файле в отдельной директории. Подробный алгоритм подготовки окружения:

  • Откройте терминал.
  • Перейдите в домашний каталог с помощью команды «cd /home».
  • Создайте директорию с произвольным названием. В нашем случае это будет mkdir newbot.

screenshot_8

Готово, окружение подготовлено. Переходим к файлам.

Добавление команд

Первый делом создайте в этой директории файл package.json с помощью команды «touch package.json». С помощью текстового редактора заполните файл следующими строками:

«name»: «*здесь укажите имя бота*»,

«version»: «*его версию (на свое усмотрение) *»,

«description»: «*описание, которое будут видеть пользователи*»,

«author»: «электронный адрес автора»,

screenshot_9

Обратите внимание на строку «»main»: «main.js»». Внутри кавычек указывается исполняемый файл. В нашем случае это main.js. Создайте в этой же директории файл с таким названием, а после введите следующий готовый код:

const Discord = require(‘discord.js’);

const bot = new Discord.Client();

const token = process.env.token;

const prefix = process.env.prefix;

if (message.content === `$hello`)

if (message.content === `$server`)

screenshot_10

Это простейший скрипт, который будет приветствовать пользователя и по команде «Server» выводить количество участников. Теперь создадите файл .env, в котором необходимо написать следующие строки:

token=*токен, который был скопирован при создании бота*

prefix=»*символ, с которого будут начинаться команды*»

В звездочках указаны места, куда нужно ввести свои данные. При подготовке кода эти звездочки писать не нужно.

screenshot_11

Тестирование

По сути, скрипт выше не взаимодействует со стандартным интерфейсом JS, а «общается» сразу посредством discord API. Следственно, проверить его работоспособность сразу не получится. Единственное, что может сделать пользователь на этом этапе, так это проверить, запустится ли код вообще. Для этого необходимо из терминала ввести команду «npm start», находясь в директории с проектом. Если никаких ошибок не возникло, то переходите к следующему этапу.

Docker-контейнер

Docker – это специальное окружение для проекта, которое позволяет запустить код, вне зависимости от параметров основной системы. Он также поможет собрать сам проект и запустить его локально на сервере. Для этого создайте файл Dockerfile со следующим содержимым:

RUN npm install

Теперь создайте файл .dockerignore, где будут храниться не используемые при сборке компоненты. Добавьте в него эти строки:

Для запуска и сборки используем следующие команды:

docker build -t author/test

docker run -p 42150:8080 -d author/test

screenshot_12

Как добавить своего бота не сервер

Можете спокойно выдохнуть, на этом все сложности заканчиваются. Добавления займет не более 1 минуты. Для инсталляции (от слова «install») снова вернитесь в окно создания приложения. Но теперь перейдите в раздел «OAuth2». В разделе «Scopes» выберите пункт «Bot». Сервис выдаст ссылку, которую нужно вставить в адресную строку.

screenshot_13

Дальше у вас спросят, в какой сервер добавить бота. Когда эти процедуры завершатся, можете смело проверять ваше творение. Пока бот может выполнять только одну команду: «!server». Вместо «!» будет указан префикс, который вы использовали в скрипте. В идеале должна вернуться строка следующего вида:

Сообщество: *название сообщества*

Участников: *количество участников*

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

Что это за бот

Разработчики практически ежедневно создают новых ботов, наделенных различными функциями. Некоторые из них исчезают без следа, а кое-какие становятся популярными. Данный бот для Дискорд-мессенджера, кроме базовых функций, в совершенстве владеет мастерством диджея.

screenshot_1

FredBoat – это музыкальный помощник, виртуоз треков, волшебник хостингов и маэстро аудиофайлов. В искусстве обращения с контентом боту нет равных. В своем классе Фред – наилучший. Поэтому, если вам нужен не просто Discord-бот, а полноценный аудиобот, стоит присмотреться к FredBoat.

Основные возможности

FredBoat является бесплатным музыкально ориентированным приложением с множеством функций. Главная фишка бота – легкость настройки. Фреду можно перепоручить подключение к хостингам с аудиконтентом. Помощник блестяще справится, найдет и загрузит нужный.

screenshot_2

Шустрый виртуальный диджей пробежится по ресурсам, начиная с привычного Ютуба и заканчивая Твичем. Бот не пропустит Soundcloud, Bandcamp, Vimeo, Mixer, любые ссылки на аудиотреки. Работает не только с сохраненными файлами, но и со стримами, транслируя музыку напрямую.

Искать нужные песни легко: нужно просто вбить в строку поиска название. Дальше FredBoat сам подключится к облачным хранилищам. Вовсе не обязательно загружать треки, вводить прямые ссылки. Бот разберется с файлами без помощи человека, отсортирует и подаст в готовом виде пользователям. Допускается проигрывание в случайном порядке, микс, повтор заданного трека (всего списка воспроизведения).

screenshot_3

Стоит она немного, 2 доллара ежемесячно. За эти деньги пользователь станет участником сообщества почитателей, спонсоров бота FredBoat Hangout. Заодно ему представится возможность формировать собственные плейлисты на Spotify.

screenshot_4

Команды FredBoat для Discord

Наш музыкальный помощник подчиняется заданному разработчиком набору команд. Ознакомиться с ними можно на сайте. Или пробежаться по основным, представленным ниже. Начинается ввод с указания префикса «;;». Как здесь:

  1. «;;play url». Базовое действие, предназначенное для прямого проигрывания трека по заданной ссылке.
  2. «;;play words». Поиск трека на облаке (YouTube, Soundcloud).
  3. «;;queue». Показывает очередь воспроизведения бота.
  4. «;;nowplaying». Позволяет увидеть текущую проигрываемую композицию.
  5. «;;skip». Пропуск трека.
  6. «;;voteskip». Пропуск воспроизводимого файла по голосованию (должно быть не менее 50 %).
  7. «;;stop». Остановка плеера.
  8. «;;pause». Режим паузы.
  9. «;;resume». Возобновление воспроизведения.
  10. «;;join». Подключение бота к голосовому каналу.
  11. «;;leave». FredBoat будет отключен от голосового канала.
  12. «;;repeat». Повтор воспроизведения.
  13. «;;shuffle». Смешивание композиций, случайный порядок.
  14. «;;reshuffle». Отключение смешивания.
  15. «;;fwd time». Перемотка вперед на заданное время.
  16. «;;rew time». Отматывает назад на установленный промежуток времени.
  17. «;;seek time». Устанавливает заданное время воспроизведения.
  18. «;;restart». Перезапуск трека.
  19. «;;volume». Управление громкостью.
  20. «;;help command». Доступные команды.

screenshot_5

Кроме музыкальных, у бота есть прочие возможности. Иначе бы он не был таким универсальным. Они так и называются – Non-music Commands. Раздел «Конфигурация» («Configuration») содержит действия по настройке базовых функций. Это, собственно, обращение к демонстрации текущего состояния («;;config»), показ подключенных модулей («;;modules»), выбор языка меню («;;language»). Еще есть «;;prefix», «;;admin», «;;dj». Догадаться об их назначении не так уж сложно.

Блок «Модерация» не поражает обилием опций. Но ведь по профилю это музыкальный бот, а не админский. В категории находятся команды для назначения бана конкретным пользователям («;;hardban», «;;softban»), удаления с сервера («;;kick»). Этого вполне достаточно для модерации.

Раздел утилит содержит дополнительные команды («;;avatar@username», «;;brainfuck code», «;;serverinfo», «;;math»). Можно даже узнать погоду для данного региона, введя «;;weather location». Группа действий, предназначенных для развлечения («Fun») собрана в соответствующей строке. Завершает перечень категория «Информация», где собраны подсказки, краткие инструкции к боту.

screenshot_6

Установка на свой сервер

screenshot_7

Либо опуститься чуть ниже, где под блоком с иконкой ФредБота и небольшим блоком с информацией также есть 2 интерактивных панели – «Add to Discord» и «Read the docs». Нажимаем первую, оказываемся на страничке входа в Дискорд-аккаунт. До запуска бота остается пара шагов.

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

screenshot_8

Как использовать

ФредБот – это, по сути, музыкальный автомат. Поэтому базовый набор команд предназначен для воспроизведения, перемешивания, перемотки треков и подобных действий. Разобраться с управлением легко даже без знания английского. Разработчик позаботился о том, чтобы снабдить FredBoat дружественным интерфейсом.

Запуск воспроизведения – «Play», остановка – «Stop». При этом можно задать название композиции. Дальше бот сам найдет ее на хостингах.

screenshot_9

Проблемы и решения

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

Создание Discord – бота на .NET Core с деплоем на VPS-сервер

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

Надеюсь, данная статья поможет многим начинающим.

Предыстория

Все началось в одну бессонную осеннюю ночь, которую я проводил на Discord – сервере. Так как я относительно недавно к нему присоединился, я стал его изучать вдоль и поперёк. Обнаружив текстовый канал «Вакансии», я заинтересовался, открыл его, и отыскал среди не интересующих меня предложений, это:

«Программист (разработчик бота)
Требования:

  • знание языков программирования;
  • способность к самообучению.
  • умение разбираться в чужом коде;
  • знание функционала DISCORD.
  • разработка бота;
  • поддержка и сопровождение работы бота.
  • Возможность поддержать и повлиять на приглянувшийся проект;
  • Приобретение опыта работы в команде;
  • Возможность продемонстрировать и улучшить имеющиеся навыки.»

Это мгновенно меня заинтересовало. Да, за данную работу не платили, но от тебя никаких обязательств не требовали, да и в портфолио лишним не будет. Поэтому я написал админу сервера, и он попросил написать бота, который будет показывать статистику игрока в World of Tanks.

Подготовительный этап

Создание Discord – бота на .NET Core с деплоем на VPS-сервер

Discrod
Прежде, чем приступить к написанию нашего бота, его необходимо создать для Discord. Вам необходимо:

  1. Войти в Discord аккаунт по ссылке
  2. Во вкладе “Applications” нажать на кнопку “New Application” и назвать бота
  3. Получить токен бота, войдя в вашего бота и найдя в списке “Settings” вкладку “Bot”
  4. Сохранить где-нибудь токен

Также, необходимо создать приложение в Wargaming, чтобы получить доступ к API Wargaming. Тут тоже все просто:

  1. Заходим в аккаунт Wargaming по данной ссылке
  2. Заходим в «Мои приложения» и нажимаем на кнопку «Добавить новое приложение», дав имя приложения и выбрав его тип
  3. Сохраняем ID приложения

Для тех, кто не знает, или забыл, как устанавливать приложения из NuGet.Инструкция для Visual Studio

  1. Переходим во вкладку Проект – Управление пакетами NuGet;
  2. Нажимаем на обзор и в поле поиска вводим “DSharpPlus”;
  3. Выбираем и устанавливаем framework;
  4. PROFIT!

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

Написание логики

Создание Discord – бота на .NET Core с деплоем на VPS-сервер

Работа с Discord бот происходит через функцию static async Task MainTask(string[] args);
Чтобы вызвать данную функцию, в Main необходимо прописать

Далее, вам необходимо инициализировать своего бота:

Где token – токен вашего бота.
Потом, через лямбду, прописываем необходимые команды, которые должен выполнять бот:

В конце данной функции, необходимо прописать await discord.ConnectAsync(); и await Task.Delay(-1);

Это позволит выполнять команды на фоне, не занимая основной поток.

Теперь необходимо разобраться с Wargaming API. Тут все просто – пишете CURL-запросы, получаете ответ в виде JSON – строки, вытягиваете оттуда необходимые данные и делаете над ними манипуляции.

Пример работы с WargamingAPI

Внимание! Все токены и ID приложений хранить в открытом виде строго не рекомендуется! Как минимум – Discord банит такие токены, когда они попадают во всемирную сеть, как максимум – бот начинает пользоваться злоумышленниками.

Деплой на VPS – сервер

Создание Discord – бота на .NET Core с деплоем на VPS-сервер

После того, как вы закончили с ботом, его необходимо разместить на сервере, который постоянно работает 24/7. Это связанно с тем, что когда работает ваше приложение, то работает и бот. Как только вы выключаете приложение, засыпает и ваш бот.

Много VPS серверов существует на этом свете, как на Windows, так и на Linux, однако в большинстве случаев, на Linux в разы дешевле размещать.

На Discord – сервере мне посоветовали vscale.io, и я тут же создал на нем виртуальный сервер на Ubuntu и залил бота. Я не буду описывать, как работает данный сайт, а сразу перейду к настройки бота.

Далее, вам необходимо залить бота на Git – сервис, вроде GitHub и ему подобные и склонировать на VPS — сервер, или, другими путями скачать вашего бота. Учтите, что у вас будет только консоль, GUI не будет. Совсем.

После того, как вы скачали вашего бота, вам необходимо его запустить. Для этого, вам необходимо:

  • Восстановить все зависимости: dotnet restore
  • Построить приложение: dotnet build name_project.sln -c Release
  • Перейти к построенной DLL;
  • dotnet name_of_file.dll

Поздравляю! Ваш бот запущен. Однако, бот, к несчастью, занимает консоль, и выйти из VPS – сервера так просто не выйдет. Также, в случае перезагрузки сервера, придется по новому запускать бота. Тут есть пару выходов из ситуации. Все они связаны с запуском при старте сервера:

  • Добавить запуск скрипта в /etc/init.d
  • Создать сервис, который будет запускаться при старте.

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

Выводы

Ранее мы сделали руководство по размещению сервера Minecraft в Digital Ocean. В этом посте вы получите пошаговое руководство по настройке собственного бота Discord на VPS (виртуальном частном сервере). В этом посте мы выбрали платформу облачного хостинга Digital Ocean. Однако ту же процедуру можно воспроизвести на Amazon (AWS) или Microsoft Azure. Мы будем использовать Ubuntu Server, который доступен на всех облачных платформах.

Загрузите Simple Discord Music Bot

В этом посте мы не будем углубляться в разработку ботов Discord. Вместо этого мы будем использовать свободно доступного бота Discord на GitHub — Простой музыкальный бот Discord. Как следует из названия, это очень простой музыкальный бот Discord с обработчиком команд discordjs.guide для легкого обучения и адаптации. Другие функции включают:

  • Система очередей
  • Контроль громкости
  • Пауза / Возобновить

Настройка VPS-сервера в Digital Ocean

В этом посте Digital Ocean предлагает бесплатный кредит в размере 100 долларов США на 60 дней при первой регистрации. Все, что вам нужно сделать, это подтвердить счет на 5 долларов с помощью PayPal или кредитной карты. Это хорошее предложение для начала — два полных месяца бесплатного хостинга. Зарегистрируйте учетную запись и войдите в Панель управления.

Создать каплю

Вы увидите возможность выбрать дистрибутив, который хотите использовать. Выберите Ubuntu. На момент написания этой статьи доступной стабильной версией Ubuntu является Ubuntu 2.04 LTS. Однако, если вы хорошо разбираетесь в системах Linux, не ограничивайтесь. Не стесняйтесь исследовать другие дистрибутивы, такие как Debian, Fedora, CentOS и другие.

Выберите распространение

После выбора вашего дистрибутива вам нужно будет выбрать план. Это в основном аппаратная архитектура вашего VPS. Для этого конкретного урока я выберу базовый план за 10 долларов в месяц. Он поставляется с 2 ГБ оперативной памяти, 50 ГБ SSD и 2 ТБ для передачи данных.

Выберите план

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

Далее вам нужно будет выбрать метод аутентификации. У вас есть два варианта: SSH и пароль. Если вы раньше использовали SSH для настройки VPS, используйте SSH. Если вы плохо разбираетесь в этих технических условиях, используйте вместо этого пароль.

Примечание. В каплях, использующих ключи SSH, аутентификация по паролю по умолчанию отключена. Это делает их более защищенными от атак Bruteforce.

Если вы решите использовать аутентификацию SSH, вам нужно будет создать ключ SSH или использовать существующий ключ для тех, кто ранее создавал VPS в цифровом океане. В моем случае я буду использовать ключ SSH, который я настроил для сервера Minecraft.

Настроить метод аутентификации

Настроить метод аутентификации

Затем выберите имя хоста для вашей капли. Я назову свой Discord-Bot-One. Когда закончите, нажмите Create Droplet внизу окна. Ваши капли будут созданы. Этот процесс может занять от нескольких секунд до минуты или двух. Когда закончите, вы увидите новое окно, в котором будут перечислены все ваши капли.

Капля раздора

Подключитесь к вашему VPS

После того, как наш VPS настроен и работает, теперь мы можем подключиться к нему и настроить бота Discord. Я покажу вам три способа подключения к VPS в Digital Ocean.

Подключиться к VPS через Терминал

Если вы пользователь Linux, то вы должны быть хорошо знакомы с Терминалом. Скопируйте общедоступный IP-адрес своего VPS и введите в Терминале команду ниже.

ssh root @ Например, ssh root@14*.***.***.79

Примечание: root — это имя пользователя по умолчанию.

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

Подключиться через Терминал

Подключиться через Терминал Подключиться к VPS через Putty

Если вы используете Windows, Putty пригодится при подключении к вашему VPS. Вы можете скачать его здесь ссылка на сайт. Есть и другие утилиты, например BitVise, но для этого конкретного урока мы будем использовать Putty.

Шпатлевка

Вы увидите окно консоли с запросом, войдите как. Введите root и нажмите Enter. Теперь, если вы выбрали аутентификацию по паролю, вам будет предложено ввести пароль. Если вы выбрали аутентификацию SSH, Putty обнаружит ключи SSH на вашем компьютере и сразу же начнет сеанс.

Создайте новый каталог для файлов Discord Bot

После успешного входа на ваш VPS-сервер нам нужно создать каталог для хранения файлов наших ботов Discord. Выполните команду ниже. В моем случае я назову каталог «Discord_Bot_Test».

sudo mkdir Discord_Bot_Test

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

Создать каталог

На изображении выше вы можете видеть, что мы успешно создали каталог. Чтобы перейти в новую папку, используйте команду cd the, как показано на изображении ниже.

Новый каталог

Загрузите / загрузите файлы Discord Bot на свой VPS

Теперь мы поговорим немного о технических моментах. Если ваши файлы бота Discord загружены на GitHub или любой другой веб-сайт, мы можем загрузить файлы на наш VPS с помощью команды wget.

Если файлы находятся на вашем компьютере, мы можем использовать FTP-приложение, такое как FileZilla, или, если вы хорошо разбираетесь в командах Linux, вы можете использовать команду SCP для загрузки файлов с вашего локального компьютера на VPS.

  • Загрузите файлы Discord Bot с веб-сайта на свой VPS

Если ваши файлы размещены на GitHub или любом другом веб-сайте, используйте приведенный ниже синтаксис команды wget, чтобы загрузить их на свой веб-сайт:

В моем случае я загрузил файлы бота Discord Music с GitHub. Файл находится в заархивированном формате; Я распакую его с помощью утилиты unzip, которую можно установить с помощью команды apt install unzip. Чтобы распаковать файл, используйте следующий синтаксис:

Когда я набираю команду ls, вы видите, что у меня есть папка discord-music-bot-master, содержащая файлы Discord Bot.

Файлы бота Discord

Файлы бота Discord

  • Загрузите файлы Discord Bot со своего компьютера на VPS с помощью FileZilla

Кроме того, вы можете скачать FileZilla с этого ссылка на сайт. Если вы используете Linux, в частности, дистрибутив на основе Debian, установите FileZilla с помощью следующей команды.

sudo apt установить Filezilla

При первом запуске FileZilla вы увидите окно ниже.

Окно FileZilla

Заполните выделенные поля, как показано ниже:

  • Хост: введите общедоступный IP-адрес вашего VPS.
  • Имя пользователя: пользователь по умолчанию — root.
  • Пароль: если вы установили аутентификацию по паролю, вам нужно будет ввести пароль. Если вы использовали аутентификацию SSH, оставьте поле пустым.
  • Порт: введите порт 22 (SSH)

После этого нажмите кнопку Quickconnect, чтобы подключиться к вашему VPS. После успешного установления соединения вы увидите окно, подобное приведенному ниже. Слева мы видим локальные файлы и каталоги на нашем компьютере. Справа у нас есть файлы на VPS.

FileZilla

Чтобы загрузить файлы с локального ПК на VPS, перетащите файлы со своего ПК (слева) в нужный каталог на VPS (справа). Так просто! Когда закончите, закройте окно FileZilla и продолжите соединение SSH на Putty или Terminal.

Запустите свой Discord Bot

На данный момент у нас есть все готово для запуска нашего бота Discord.

Примечание: в этом руководстве мы используем бота, который был разработан на Javascript — Простой музыкальный бот Discord. В частности, Discord.js и Node.js. Если вы разработали своего бота на таком языке, как Python, описанные ниже действия вам не подойдут.

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

Версия NodeJs

узел -vВерсия NodeJs

Затем мы запустим команду npm install, чтобы загрузить необходимые пакеты модулей узлов, необходимые для нашего проекта. Выполните команду в каталоге, содержащем файл package.json.

NPM Установить пакеты

NPM Установить пакеты

Чтобы добавить свой токен Discord, переименуйте .env_example в .env и заполните значения:

Поскольку это скрытый файл (начинается с точки), мы воспользуемся командой ls -a для вывода списка всех файлов. Когда закончите, перейдите в каталог src и запустите бота.

Запустить бота

cd src node index.jsЗапустить бота

Вот и все! Наш бот Discord запущен и работает.

Однако есть одна проблема. Вы заметите, что пока бот работает, вы можете делать что угодно в Терминале, и если вы остановите процесс, это также убьет нашего бота. На следующем шаге мы рассмотрим, как обеспечить круглосуточную работу нашего бота за кулисами.

Установить PM2

PM2 — это пакет npm, который вы можете легко установить на свой VPS с помощью следующей команды:

npm установить pm2 -g

После успешной установки перейдите в папку src, содержащую файл index.js. Теперь запустите бота Discord с помощью приведенной ниже команды.

Запустить бота с PM2

pm2 запустить index.jsЗапуск бота с PM2

Как видно из изображения выше, PM2 запустил нашего бота и присвоил ему идентификатор. Вы можете продолжать выполнять другие задачи, пока бот все еще работает. Другие полезные команды PM2 для управления вашими задачами:

  • pm2 logs : показывает журналы выбранного вами процесса.
  • pm2 list: перечисляет все запущенные процессы pm2.
  • pm2 stop : PM2 останавливает выбранный процесс.

Чтобы просмотреть все остальные команды PM2, выполните pm2 —help.

Вывод

В этом посте мы предоставили вам пошаговое руководство по настройке бота Discord на виртуальном частном сервере. Наша предпочтительная облачная платформа — Digital Ocean. Однако процесс установки такой же, поскольку большинство облачных платформ поддерживают Linux VPS. Если у вас возникнут какие-либо проблемы при выполнении любого из вышеперечисленных шагов, пожалуйста, оставьте комментарий ниже.

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

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