Creating a Twitch Chat Bot

Posted Aug 20, 2020 at 2:44 pm

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

  • NodeJS (get)
  • Your favorite text editor or IDE
  • Your Twitch OAuth password (get)

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.

Motion Tracking in DaVinci Resolve

Posted Aug 19, 2020 at 3:28 pm

How to Play Poker

Posted Aug 25, 2011 at 3:19 pm

A very detailed explanation.

How to Use StumbleUpon

Posted Mar 20, 2011 at 7:04 pm

Some More Screencasts

Posted Oct 3, 2010 at 6:26 pm

Follow me on Twitter to see them the instant they’re available.

How To Use The Google

Posted Sep 30, 2010 at 4:28 pm

How to Convert Demos to Video

Posted Dec 16, 2009 at 2:12 pm

All Half-Life and Source based games include a utility for recording games in a special format called a demo. The recorded footage is only readable by the game itself. Here’s a step by step tutorial to convert these recorded demos into video format.

Recommended Method

This is the method I always use, and is the “safe” method that I recommend.

What You Need

  • Demo file(s)
  • VirtualDub (download)
  • Plenty of hard drive space

To install VirtualDub, just unzip it to the desired location. To use it, run ”’VirtualDub.exe”’ or ”’VeeDub64.exe”’ depending on the version.

Converting

  1. Run TF2 and reduce the resolution (I use 720×480 or 1280×720 for HD). You should also restart the game after this or some things may be out of proportion. Also change any other settings for the desired effect (such as disabling the HUD or voice; see below for useful commands).
  2. In the console type the following commands (replace ”demoname” with the name of the demo file):
    startmovie moviename
    playdemo demoname

    The demo will now play while the game records the frames to TGA files at 30 fps.

  3. When the demo is completed or you have all the footage you want, in the console type:
    endmovie

    You should now have lots of TGA images and a WAV in the mod directory.

  4. Run VirtualDub and go to File > Open video file. Browse to your Steam\SteamApps\account\Game Name\mod directory and select the first image in the series (moviename0000.tga). Click Open. It will now import all the images in the sequence.
  5. Go to Audio > WAV Audio and select the moviename.wav file. Click Open.
  6. If you plan to edit the file in another program, you can leave it uncompressed. Otherwise you can choose compression options in Video > Compression….
  7. Go to File > Save as AVI and save the output to the desired location. When the process completes, you will have an AVI file that can be edited or played back with other tools.

Clean-up

The easiest way to remove all the TGA files is to use the following commands in the Command Line:
cd Path-to-mod-folder
del *.tga
del moviename.wav

Alternate Method

I have not tested this very much and there seems to be issues with audio synchronization, but it is a much easier and faster process.

What You Need

  • Demo file(s)
  • Plenty of HDD space

Converting

  1. Run TF2 and reduce the resolution (I use 720×480 or 1280×720 for HD) in windowed mode. You should also restart the game after this or some things may be out of proportion. Also change any other settings for the desired effect (such as disabling the HUD or voice; see below for useful commands).
  2. In the console type the following command:
    startmovie moviename avi

    A prompt will ask for compression options (may not work in full-screen). Choose a good balance between size and quality or leave it uncompressed.

  3. In the console type the following command (replace demoname with the name of the demo file):
    playdemo demoname

    The demo will now play while the game records to an AVI file.

  4. When the demo is completed or you have all the footage you want, in the console type:
    endmovie

You should now have a complete AVI video in the game directory.

Useful Commands

  • demoui – Nice GUI for opening and controlling demos
  • sv_cheats 1 – Required for some of the below
  • voice_enable 1/0 – Enable/disable voice
  • cl_drawhud 1/0 – Enable/disable the HUD