Thomas Step

This is where I share my thoughts.

Blog


Blog Categories


About Me


View My GitHub Profile


29 July 2019

Deploying a Discord Bot to Heroku

by Thomas

I have been working with a friend to start a discord bot for a server. I recently worked to deploy that bot to Heroku but I couldn’t find a single source that helped from start to finish. I’m going to assume that you mostly know what you are doing (in regards to programming) while writing this. You will need a Heroku account, Heroku CLI, Node, and a Discord account and bot token. I suggest using the Discord JS package to setup your bot and communicate with the Discord API. You can just copy and paste the example on their homepage to get up and running before you add some more parts in. Also, make sure that your bot is a git repo; it just makes everything with Heroku easier. In the example on Discord JS’s homepage you can see the client.login(‘token’) portion. That part is what you need the Discord bot’s token for. I suggest using an environment variable in Heroku which can be configured under your Heroku dashboard -> Settings -> Config Vars. I used a key of TOKEN and pasted my token as the value. Then in your code you can use something like client.login(process.env.TOKEN). Environment variables are super useful for hiding secrets and making code configurable depending on environment (like staging, production, etc.) and even between users.

At this point in time you need to actually deploy your code to Heroku. You can use heroku login and then heroku create. Use git remote -v to make sure that the Heroku app was successfully created. You can also rename your app if you want which also entails changing the git remote URLs. You probably don’t need to rename your app though because no one will probably ever know the Heroku app’s name. One error that I kept running into was a Heroku R10 error because I originally deployed without a Procfile. Heroku does not let you attach to a single port like 8080 for a website, instead you need to use environment variables for the port if you are creating a website that people view in a browser. The default dyno for an app is a web dyno. This is where the problem comes in. The web dyno is expecting your app to attach to its port defined in the PORT environment variable set by Heroku, but since the Discord bot doesn’t use a port to listen to incoming calls this never happens. Heroku does not like that so it throws an error and will stop your bot. The cure for this is to use a worker dyno. Create a Procfile in your project’s root directory and type in worker: npm start to tell Heroku you want a worker dyno. Now you can commit and push to Heroku. To push to Heroku use git push heroku master. Your bot should be up and running. I cannot comment on performance or anything yet. I am currently just using the free version of Heroku. We’ll see what happens in the future, but I might need to upgrade to a paid version.

tags: dev - infrastructure