Set up a Twitch chat bot using Websockets and Node.js
Tags: beginners, node, javascript
Published: 2023-04-15 14:40:07

---
title: Set up a Twitch chat bot using Websockets and Node.js
published: true
date: 2023-04-15 00:00:00 UTC
tags: beginner, nodejs, javascript
canonical_url: https://khendrikse.netlify.app/blog/set-up-a-twitch-chat-bot/
description: Just a quick example of setting up a chat bot using websockets and the Twitch Internet Relay Chat (IRC) in JavaScript.
---

**I really enjoy watching some [twitch streamers](https://khendrikse.netlify.app/blog/favorite-twitch-streamers), and because I am always delighted by the possibilities of API's and the fun that chatbots bring, I wanted to try writing a small chatbot that says hi. In this post I'll quickly bring you along in creating a quick and small prototype.**


## Prepare your Twitch account

If you haven't done so yet, make sure to create a Twitch account by [going to twitch.tv](https://www.twitch.tv/) and signing up. After you've created your account, note down your **username**. Then go to the [Twitch Developer Console](https://dev.twitch.tv/login) and login using your new Twitch account.

After this, click on "Register Your Application". Fill in the form by providing a name, adding the url `http://localhost:3000` to OAuth Redirect URLs. You can choose Chatbot for the Category. Prove that you're not a robot (we're just making one). Then click "Create". After this, you'll see an overview of your applications. Click on "Manage" for the application you just registered. This is where you'll see something called your **Client ID**.

## Prepare your code

Create a directory on your computer with the name of your chatbot, move into this folder and initialize git and npm. You can do this by doing the following inside your terminal:

```
// create a new directory
// just choose whatever name you want for your bot
$ mkdir twitch-bot

// move into your newly created directory
$ cd twitch-bot

// initialize a git repository
$ git init

// initialize your node project
$ npm init -y
```

Create a file called `index.js` which will be the main entrypoint for your code by typing `touch index.js` in your terminal.

Let's also go into our `package.json` and add an option called `"type": "module"` in the main object. Setting this [type field](https://nodejs.org/api/packages.html#type) to "module" will make sure that any file ending with `.js` is loaded as an [ES Module](https://hacks.mozilla.org/2018/03/es-modules-a-cartoon-deep-dive/).

>I'm solely doing this because I like using the `import` statement when I import dependencies. Of which I only have one for this example. Yes, what an overengineered delight.

## Adding our first dependency

Because we'll be working with websockets, and node does not support them by default, we're going to be installing the dependency called [ws](https://www.npmjs.com/package/ws). You can also use [tmi.js](https://tmijs.com/) to interact with Twitch, but I decided to only use websockets when trying this out. In your terminal type:

```
npm i ws
```

Now open up `index.js` and import your newly installed package:

```js
// index.js
import WebSocket from 'ws';

```

## Getting an access token

Because our chatbot will need an access token, let's make sure we have one. We'll be taking some advice from the [Twitch docs](https://dev.twitch.tv/docs/irc/authenticate-bot/#getting-an-access-token):

* Open a browser and enter the following URL in the address bar:
`https://id.twitch.tv/oauth2/authorize?response_type=token&client_id=<your client id>&redirect_uri=http://localhost:3000&scope=chat%3Aread+chat%3Aedit`.

* Replace "your client id" with the client ID you received when registering your bot. Replace the URL in the redirect_uri query parameter with the redirect URI you specified when registering your bot.
* Enter your Twitch credentials if asked, and then authorize the scopes.
* Get the access token from the address bar (see the access_token parameter in the fragment portion of the URI).

Now that you have your access token, let's add it to our `index.js` file:

```js
// index.js
import WebSocket from 'ws';

const TOKEN = 'your token here';
```

## Creating the websocket client and listening for events

Now let's make sure we create our websocket client. To do this we'll add the following to our `index.js` file:

`const ws = new WebSocket('wss://irc-ws.chat.twitch.tv:443');`

This is where we'll finally start interacting with Twitch's Internet Relay Chat (IRC) interface. This IRC allows us to send and receive messages to a Twitch Chat. If you want to know more, there is always the [Twitch Documentation](https://dev.twitch.tv/docs/irc/).

Now that we've created our websocket client, we'll start listening to some events. We'll listen to `error`, `open`, `message` and `close`. I'll set up `close` and `error` mostly for the purpose of being complete. The real interesting part will happen in `message` and `open`. This is how this will look in your file:

```js
// index.js
import WebSocket from 'ws';

const TOKEN = 'your token here';
const ws = new WebSocket('wss://irc-ws.chat.twitch.tv:443');


ws.on('error', () => console.error());

ws.on('open', () => {
  console.log('Opened connection');
});

ws.on('message', (data) => {
  console.log('received: %s', data);
});

ws.on('close', () => console.log('Closed connection'));

```

With this logic set up, we're all ready to start setting up the logic of actually connecting to Twitch's IRC.

## Connecting to the Twitch IRC

We now want to start connecting to the Twitch IRC. To do this we'll first ask access to Twitch by sending the message `CAP REQ :twitch.tv/membership twitch.tv/tags twitch.tv/commands`. Then we send our token using `PASS` and our username using `NICK`. This is done the following way:

```js
// index.js
import WebSocket from 'ws';

const TOKEN = 'your token here';
const ws = new WebSocket('wss://irc-ws.chat.twitch.tv:443');


ws.on('error', () => console.error());

ws.on('open', () => {
  console.log('Opened connection');

  ws.send('CAP REQ :twitch.tv/membership twitch.tv/tags twitch.tv/commands');
  ws.send(`PASS oauth:${TOKEN}`);
  ws.send('NICK your-bot-name');
});

ws.on('message', (data) => {
  console.log('received: %s', data);
});

ws.on('close', () => console.log('Closed connection'));

```

Notice the `NICK your-bot-name` part. Make sure to replace this with the name of your bot.

## Joining a chat

To test our bot, we'll be joining our own bot's chat. To see this, visit your profile on Twitch and navigate to your chat.

After you've done that, inside your `open` event, we're going to join this chat by sending `'JOIN #your-bot-name'`. To see if it all works, we'll immediately send a message once we do, by also sending `'PRIVMSG #your-bot-name :Hey! I am here!'`. The `#` is important in both messages, so don't forget those. Your code should look like this now:


```js
// index.js
import WebSocket from 'ws';

const TOKEN = 'your token here';
const ws = new WebSocket('wss://irc-ws.chat.twitch.tv:443');


ws.on('error', () => console.error());

ws.on('open', () => {
  console.log('Opened connection');

  ws.send('CAP REQ :twitch.tv/membership twitch.tv/tags twitch.tv/commands');
  ws.send(`PASS oauth:${TOKEN}`);
  ws.send('NICK your-bot-name');

  ws.send('JOIN #your-bot-name');
  ws.send('PRIVMSG #your-bot-name :Hey! I am here!');
});

ws.on('message', (data) => {
  console.log('received: %s', data);
});

ws.on('close', () => console.log('Closed connection'));

```

You can now try your code in your terminal by running `node index.js`. If all goes well, you should be able to see messages stream in through your terminal, but you should also see the message "Hey! I am here!" in your Twitch chat in your browser.

If you send a message in chat, you should also see it inside your terminal.

## Responding to messages

In order to properly respond to messages, you'll need to look into parsing them. Twitch has a great [example on this](https://dev.twitch.tv/docs/irc/example-parser/). But for now, let's just make a very very simple response to when someone says "Hi bot!".

To do this, inside the message listener, we'll check wether or not an incoming message has the string ":Hi bot". if it does, we'll respond with a message. Your code will look like this:


```js
// index.js
import WebSocket from 'ws';

const TOKEN = 'your token here';
const ws = new WebSocket('wss://irc-ws.chat.twitch.tv:443');


ws.on('error', () => console.error());

ws.on('open', () => {
  console.log('Opened connection');

  ws.send('CAP REQ :twitch.tv/membership twitch.tv/tags twitch.tv/commands');
  ws.send(`PASS oauth:${TOKEN}`);
  ws.send('NICK your-bot-name');

  ws.send('JOIN #your-bot-name');
  ws.send('PRIVMSG #your-bot-name :Hey! I am here!');
});

ws.on('message', (data) => {
  console.log('received: %s', data);
  if (data.includes(':Hi bot')) {
		ws.send('PRIVMSG #your-bot-name :Hey you, how are you doing?');
	}
});
ws.on('close', () => console.log('Closed connection'));

```

Try restarting your code again by doing `node index.js` inside your terminal. Once you've connected, visit your Twitch chat in your browser again and type "Hi bot". If all works well, you should now see that the bot responds with "Hey you, how are you doing?".

This was a very very small tutorial on how to make a simple chat bot. Feel free to play around with it as you go!