Build and host your first Discord bot using Node.js and AWS

Sydney Sisco
6 min readApr 4, 2021

Discord is one of the most popular chat applications in the world; with over 140 million active users, it’s likely that you and everyone you know already use it! Making your own Discord bot can be a fun way to add custom features to your Discord server and a good way to learn a bit about using the Discord API. In this guide we’ll use Discord.js, a Node.js library that allows for easy intraction with the Discord API, to make a Magic 8-Ball bot. We’ll also host the bot in the cloud using AWS. Will we succeed? 🎱 Signs point to yes. 🎱

Note

This guide assumes you have some experience with the following:

  • Discord (as a user, not a developer)
  • Node.js & npm
  • AWS and the AWS CLI (if you want to host your bot)
  • Magic 8-Balls

What is a Discord bot and how to they work?

At a high level, Discord bots connect to Discord servers in a manner very similar to how a user does. The bot recieves events from the server just like the regular Discord client and can be programmed to take actions when specific events occur. You may be surprised to discover that a Discord bot recieves every message and every event in every channel that it has access to. Privacy in the digital age? 🎱 Don’t count on it. 🎱

source: https://giphy.com/gifs/dudeyork-dude-york-xUA7b3UudQ619Y9AIM

Getting Started

To start building your first Discord bot you’ll need a few things:

Register the Bot

The first thing we’ll need to do is create a bot using the Discord developer portal. Click New Application and enter a name for the bot. On this page we can also add an icon and description.

Next, navigate to the Bot settings using the menu on the left. Click Add Bot.

This page is used to retrieve the bot’s token. We’ll need this token once we start coding. This token is essentially the bot’s password and must be kept secret! Should you commit this token to a public github repo? 🎱 My sources say no. 🎱

The final thing to do in the developer portal is create an invite link so we can add the bot to a server for testing. Click the OAuth2 setting on the left of the page. This menu is used to craft an invite link with just the specific permissions that your bot needs. Under scopes select bot. In the new bot permissions menu that appears below, select View Channels and Send Messages.

Note

It’s always best practice to give your bot least privilege, meaning only the permissions it will need to perform its task.

Generating an OAuth link for the bot

Open the link in your browser and follow the prompts.

Inviting the bot

In your Discord server you should now see the bot in the members list. The bot will be offline until we bring it to life in the next step. Is it finally time to start programming? 🎱 Yes — definitely. 🎱

Let’s get coding

In this step we’ll set up a simple Node.js project and bring the bot online. First, create a new project directory and cd into it:
mkdir magic-8-ball && cd magic-8-ball

Initialize npm with default settings:
npm init -y

Install Discord.js and dotenv:
npm i discord.js dotenv

Next, create a .env file and add your bot's token to the file:

DISCORD_BOT_TOKEN=your_token_here

Create an index.js file and paste in this example code:

This code is enough to bring your bot online and have it respond when a user types ping in any of the chat channels in your Discord server. Return to the command line and run your app:
node index.js

Your bot should now be online! Should we celebrate this small victory before moving on? 🎱 Without a doubt. 🎱

Let the divinations begin

Now that the bot is alive, we can add the code needed to give this digital Magic 8-Ball the incredible powers of prescience! Add this code to the top of index.js where the other constants are defined.

This code defines a command prefix (the string that must be included at the start of a message in order to invoke the bot) and a function to return a specific message. Next, replace the existing message event handler with the one below. This code tells the bot to ignore messages from bots and to only respond to messages that begin with the prefix defined above.

Save the file and restart the process. You should now be able to test your bot like this:

It’s working! Is this another chance to celebrate? 🎱 It is decidedly so.🎱

Hosting your bot on AWS

You could stop at this point, but your bot will only work while you have the code running on your machine. To really complete this project we need to give the bot a home in the place where all bots wish to live: In the Cloud!
We’ll be running the bot on an AWS EC2 instance that we launch using the AWS CLI. If you don’t already have the AWS CLI configured you can read about how to do that here.

Note

This part of the guide assumes you have some experience with AWS EC2. If you’re new to AWS EC2, this resource is a great place to start.

First, we need to launch an EC2 instance, which is an AWS virtual computer. Running the command below will create an EC2 instance in your default VPC using your default security group. You will need to replace <your_key_name> with the name of your ssh key. If you don't already have an ssh key pair in your AWS account, you can learn how to do that here.

aws ec2 run-instances --image-id $(aws ssm get-parameters --names /aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2 --query 'Parameters[0].[Value]' --output text) --count 1 --instance-type t2.nano --key-name <your_key_name> --tag-specifications 'ResourceType=instance,Tags=[{Key=Name,Value=my-discord-bot}]'

The server will take a minute or two before you can connect to it. You can run the following command to get information about your new instance including the status:
aws ec2 describe-instances --filters "Name=tag:Name,Values=my-discord-bot" --query 'Reservations[*].Instances[*].{Instance:InstanceId,Subnet:SubnetId,Name:Tags[?Key==Name]|[0].Value,State:State.Name,IP:PublicIpAddress}'

Once the state reads running you should be able to connect to the server using a command similar to:

ssh -i /path/to/your/key ec2-user@your.ec2.ip.address

If you’re unable to connect to your instance, you may need to edit the default AWS security group to allow inbound traffic from your IP address.

Once connected, install nvm and node:
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.34.0/install.sh | bash
. ~/.nvm/nvm.sh
nvm install node 12

Back on your local machine, run this command from inside your project directory to upload your bot’s code to the instance:
scp -v -i /path/to/your/key -r "$(PWD)/" ec2-user@your.ec2.ip.address:magic-8-ball/

Now that your code is on the server, reconnect with ssh and start the bot as a background process:
ssh -i /path/to/your/key ec2-user@your.ec2.ip.address
cd magic-8-ball
nohup node index.js &

That’s it! Your bot is now running happily in the cloud! Thanks for reading 👀

Resources

Magic 8-Ball answers
Discord Developer Documentation
How To Build a Discord Bot with Node.js
discord.js
dotenv
setting up Node.js on AWS EC2
query for the latest Amazon Linux AMI ID

--

--

Sydney Sisco

Software Developer, AWS certified. I love sci-fi🚀📚, Soylent🥛😋, and dark mode🌙🧑‍💻.