Creating a Twitch Chat Bot
This tutorial will show you an easy way to create your own Twitch chat bot for your channel. We will be writing this in JavaScript using NodeJS. This is how I created the chat bot component of Stevelabs.
The completed tutorial files are available on GitHub.
Prerequisites
I will leave the setup of the above to you.
Live Tutorial
Create Your Project
Open a terminal and navigate to an empty directory. Initialize a new NodeJS project using this command:
npm init
It will ask you some questions. The defaults will work fine, but feel free to add your own personalized information. After you answer the questions and confirm the results, NPM will create your package.json file.
Since we will be using the tmi.js package, we must install it to our project using this command:
npm install tmi.js --save
Note that --save
will automatically update your package.json file.
Create Your Configuration File
Create a new text file in your project directory called config.json.
{ "username": "CHANNEL_USERNAME", "password": "OAUTH_PASSWORD" }
Replace CHANNEL_USERNAME
with your Twitch channel username and OAUTH_PASSWORD
with your channel’s OAuth password.
Create Your Application
Create a new text file in your project directory called index.js. This is your main application file.
Include Your Configuration
const config = require('./config.json');
This will include your configuration JSON as an object assigned to the variable named config
.
Include The tmi.js Library
const tmi = require('tmi.js');
This will include the tmi.js library and assign it to the variable named tmi
. As you may have noticed, require
can be used to include your own files as well as installed packages.
Create Your Client
The client is what you will use to listen to events in your Twitch channel chat, as well as send messages to it.
const client = new tmi.Client({ connection: { secure: true, reconnect: true }, identity: { username: config.username, password: config.password }, channels: [ config.username ] });
Now you can access the client using the variable called client
. The constructor of the Client
class accepts an object containing your configuration. See the documentation for an explanation of all the available options.
Connect Your Bot To Chat
You’ve created your client, so now it is time to connect to Twitch.
client.connect() .then(() => { console.log('connected to Twitch chat'); }) .catch(err => { console.warn('failed to connect to Twitch chat'); console.log(err); });
The connect
method takes no arguments and returns a Promise. You can chain then
and catch
method calls to a promise to handle the results. This is a common pattern in asynchronous JavaScript.
Put code you want to run when the connection is successful within the then
callback and handle any errors within the catch
callback. Here, we are writing messages to the console.
Respond To Chat Messages
Let’s start interacting with chat! In this example we will respond to “!hello” with “Hello, user!”
client.on('chat', (channel, userstate, message, self) => { if (message.trimLeft().startsWith('!hello')) { client.say(channel, `Hello, ${userstate['display-name']}!`); } });
The on
method of your client is used to start listening for events. It accepts two arguments: the name of the event and a callback function to run when the event happens. See the documentation for a list of available events.
The “chat” event sends back the following data as arguments to the callback function:
- The name of the channel (
channel
) - Information about the user (
userstate
) - The message that was sent (
message
) - Whether the message was sent by the client (
self
)
Note that we are using client.say
to send a message to the chat. It takes two arguments: the name of the channel to which to send and the message text to send.
The userstate
argument is an object containing a lot of useful information. You can use console.log(userstate)
to explore the available data.
In many cases you will want to check the self
boolean to ignore messages sent by your bot to avoid an infinite loop!
Respond To More Events
Here is another example showing how to respond to cheer events:
client.on('cheer', (channel, userstate, message) => { console.log(`${userstate.username} cheered ${userstate.bits} bits with message: ${message}`); });
This example simply logs the event to the console, but you can do anything you want here. Notice that userstate.bits
contains the number of bits cheered. Some of the events add some data to the userstate
object.
For more examples, see the documentation. The only event that is missing is new followers. You must use a webhook for that, but that is for another tutorial.
Run Your Application
To run your bot, run this command from within your project directory:
node .\index.js
If everything is correct, you should see “connected to Twitch chat.” Otherwise you will see an error.
Now, if you go type “!hello” in your Twitch channel chat, your bot should respond. If it does, then congratulations, it’s alive!
The End
You have reached the end of the written tutorial. Thank you for reading and I hope you found it useful. Feel free to post a comment here if you run into any problems.