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

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

  • 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?

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

Getting Started

Register the Bot

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

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

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

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

Note

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

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