Adam. R

Run a Discord.js Bot on Ubuntu

Created September 7, 2021

Install Dependencies

  1. Install Node.JS To do this just follow my tutorial on how to install Node.JS on Ubuntu by Clicking here Make sure to also install npm.

  2. Install Node Version Manager (nvm), which is used to update Node.js. For example:

curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.37.2/install.sh | bash

👉Note: Use the command for the latest version, which is found here: [Use the command for the latest version, which is found here: https://github.com/nvm-sh/nvm#installing-and-updating

  1. Reboot the server or vm Reconnect to the server console.
  2. Verify the nvm installation:
command -v nvm

It should return:

nvm

If it returns nothing, or an error, run the following:

export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"
  1. After you've installed nvm, update Node.js:
nvm install 14.15.1

Create the Project

  1. Switch to the root user's home directory.
  2. Create a project folder.
mkdir tutorial-bot
  1. Switch to the folder.
cd tutorial-bot
  1. Initialize your Node.js project.
npm init
  1. Answer the questions. Leave the defaults unless you need to change them.
  2. Check your package.json file.
cat package.json

It should look something like this:

{
  "name": "tutorial-bot",
  "version": "1.0.0",
  "description": "Tutorial Bot",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

Install Libraries

Libraries make writing code easier. For this guide, you need the Discord.js library. As you add capabilities to your bot, look for other useful libraries on the npm website

Install the Discord.js library.

npm install discord.js --save

The --save flag adds the library as a dependency in your package.json file.


I am not going to write the code for the bot right now. Just write it in nano or vim.


Install a Node.js Process Manager

  1. Install the PM2 process manager to manage your bot.
npm install pm2 -g
  1. Start the bot with pm2.
pm2 start index.js

Verify the bot is online.

pm2 logs

You should see:

0|index | Ready!

If you see that then your bot is running!


Just invite the bot to your server and thats all!

If you updated the index.js folder and want to keep the bot online while updating the changes? Then just run:

pm2 reload index.js

Give it a while depending on how much you updated the code. Sometimes you will need to stop the bot. Do it by running:

pm2 stop index.js

If you found this usful then please comment and follow me! Also check out my website where I also post everything from here