close icon
JavaScript

JavaScript Twitch Bot to Control My Hue Lights

Learn how to create a Twitch bot that allows users to control your Hue lights.

January 22, 2021

The Developer Relations team at Auth0 has spent a lot of time streaming on Twitch this past year. It's been a learning process for us, so recently we've been brainstorming on creative ways to drive engagement during our streams.

How can give we give viewers a reason to participate? A way to feel like they are part of the stream itself?

While I was pondering that question, I was also tinkering with my Philips Hue lights and how to control them with JavaScript (read the full how-to article). Anyways, I figured why not combine my Hue lights with a JavaScript Twitch bot for ultimate interaction?

So, follow along to learn how to create a Twitch bot that allows users to control your Hue lights from chat commands!

Getting Started

To run this demo yourself, you'll need to buy Hue lights and a Hue Bridge, both of which can be found on the Philips Hue website. If you don't have those, you can still follow along for a fun walkthrough and demo 😃

Outside of the hardware requirements, you'll need to have Node.js installed.

Additionally, you'll need an OAuth Token from Twitch. You can get your OAuth Token here by clicking "Connect" and logging in with your Twitch account. Make sure to copy that token as we'll use it shortly.

Lastly, you'll need to create a new JavaScript project. Create a new folder and open it in your text editor of choice. Then, from the command line, you'll want to initialize this as a JavaScript project. I'm passing the -y parameter to accept default values.

npm init -y

With your project setup create a new file called app.js in the root of your project.

Create A Twitch Bot

To create our Twitch bot, we'll use the tmi.js package. This package simplifies the process for connecting to a Twitch channel and streaming the comments as they come through.

Start by installing the package.

npm install tmi.js

Now, we can initialize the chatbot by adding the connection code. This code comes almost verbatim from the docs on Github.

const tmi = require('tmi.js');
twitchClient = new tmi.Client({
    options: { debug: true },
    connection: {
        reconnect: true,
        secure: true,
    },
    identity: {
        username: <YOUR_USERNAME>,
        password: <YOUR_AUTH_TOKEN>,
    },
    channels: [<YOUR_CHANNEL_NAME>],
});

twitchClient.connect();
twitchClient.on('message', (channel, tags, message, self) => {
    console.log(message);
    console.log(tags);
});

With that code in place, we can run it and should be able to see Twitch chat messages (and tag information) logged to the console. Run the code with the following command.

node app.js

After it is started, you'll need to open up your Twitch page, navigate to the "Chat" tab, and type in a message.

Twitch test command

Then, look in your terminal!

Twitch chat log in terminal

Easy, right?

Listen For Specific Commands

Now that we can listen for Twitch chat messages, we inspect the message itself to see if it matches a certain format. For example, typically "commands" in Twitch start with a "!". So, if we wanted to have a command to turn on the lights, it might look like this, !lightsOn. That said, here are the commands that we are going to support.

  • !lightsOn
  • !lightsOff
  • !lightsRandom
  • !lightsChristmas

For now, let's log out if the user enters one of those commands.

twitchClient.on('message', (channel, tags, message, self) => {
    console.log(message);
    console.log(tags);
    if (message.startsWith('!lightsOn')) {
        console.log('!lightsOn command');
    } else if (message.startsWith('!lightsOff')) {
        console.log('!lightsOff command');
    } else if (message.startsWith('!lightsRandom')) {
        console.log('!lightsRandom command');
    } else if (message.startsWith('!lightsChristmas')) {
        console.log('!lightsChristmas command');
    }
});

Connect Chat Commands to Hue Lights

We can listen for specific commands, so now we need to connect them to the Hue lights. I've included the code snippet for the Hue lights integration, but if you want the full tutorial for how to set those up, refer to this article. It will walk you through the following steps.

  • find the IP of your Hue Bridge
  • find the Hue Bridge user
  • find the ids for your light(s)

Here's the code for the Hue lights integration. I put it in a separate file called hueLights.js.

const axios = require('axios');

const ids = [3, 4];

const turnLightOnOrOff = async (lightId, on, hue, sat, bri) => {
    try {
        return await axios.put(
            `http://<YOUR_BRIDGE_IP>/api/<YOUR_HUE_USER}/lights/${lightId}/state`,
            {
                on,
                ...(sat && { sat }),
                ...(bri && { bri }),
                ...(hue && { hue }),
            }
        );
    } catch (err) {
        console.error(err);
    }
};

const turnLightsOnOrOff = async (on) => {
    lightIds.forEach((id) => turnLightOnOrOff(id, on));
};

const setLightsToRandomColors = async () => {
    ids.forEach((id) => {
        const hue = Math.floor(Math.random() * 65535) + 1;
        const sat = 200;
        const bri = 175;
        turnLightOnOrOff(id, true, hue, sat, bri);
    });
};

const setLightsForChristmas = () => {
    turnLightOnOrOff(ids[0], true, 27306, 150, 175);
    turnLightOnOrOff(ids[1], true, 1, 150, 175);
};

module.exports = {
    setLightsForChristmas,
    setLightsToRandomColors,
    turnLightsOnOrOff
};

With those helper functions in place, we can import them at the top of the app.js file.

const {
    setLightsForChristmas,
    setLightsToRandomColors,
    turnLightsOnOrOff
} = require('./hueLights');

Then, we can call the appropriate function based on the chat command like so.

twitchClient.on('message', (channel, tags, message, self) => {
    console.log(message);
    console.log(tags);
    if (message.startsWith('!lightsOn')) {
        turnLightsOnOrOff(true);
    } else if (message.startsWith('!lightsOff')) {
        turnLightsOnOrOff(false);
    } else if (message.startsWith('!lightsRandom')) {
        setLightsToRandomColors();
    } else if (message.startsWith('!lightsChristmas')) {
        setLightsForChristmas();
    }
});

Now that everything's in place, it's time to test.

Wrap Up

Personally, I think these projects are a lot of fun. I'm looking forward to adding more interaction in Twitch, so make sure to check out the Auth0 Twitch channel for more cool stuff to come.

  • Twitter icon
  • LinkedIn icon
  • Faceboook icon