DEV Community

gortron
gortron

Posted on

Making Your First Twitch Bot

Introduction

In this post, I'll walk through implementing a Twitch bot. Specifically, I'll be going through initial configuration to connect to Twitch with Node and the tmi.js package, as I feel the documentation available makes this less straightforward than it should be.

I'll be referencing code from this repo, which I put together for this post.

Implementation

Start with the instructions and sample code (or pull from my GitHub repo, linked above) that Twitch provides here. Once you've created an account for your bot, registered it for the tmi.js packages' OAuth, and have a local clone of my/or GitHub's repo, then you're ready to set up your .env file and bot.js script to connect to Twitch.

The code Twitch provides in their getting started guide asks you to put your OAuth credentials and other environment variables directly into the bot.js script. This is an anti-pattern, and makes it easy to expose credentials you want to keep secret.

Instead, we'll use the dotenv.js package to manage environment variables.
1) Add the dotenv package with yarn add dotenv
2) Add a .env file to your project's root directory
3) Add the following code to the .env file:

BOT_USERNAME=<YOUR BOT'S USERNAME>
OAUTH_TOKEN=<YOUR BOT'S TMI OAUTH TOKEN>
CHANNEL_NAME=<TARGET CHANNEL'S NAME>

Example syntax:

BOT_USERNAME=mytwitchbot
OAUTH_TOKEN=oauth:fsjgslgd4jkdfgsds5sjskl
CHANNEL_NAME=mytwitchusername

4) Update code in bot.js to reference the environment variables:

const opts = {
    identity: {
      username: process.env.BOT_USERNAME,
      password: process.env.OAUTH_TOKEN
    },
    channels: [process.env.CHANNEL_NAME]
  };
  const target = opts.channels[0]

Your set up is complete! To run, call node bot.js in your shell.

Conclusion

In this post, you reviewed how to configure your environment variables to connect to Twitch. I hope it was helpful. Feel free to reach out to me if you have trouble connecting your own bot to Twitch.

Top comments (0)