colorbot-twitch/index.js

109 lines
2.4 KiB
JavaScript

const tmi = require("tmi.js");
const convert = require("color-convert");
const chalk = require("chalk");
const sleep = (waitTimeInMs) => new Promise(resolve => setTimeout(resolve, waitTimeInMs));
let defaultcolor = process.env.TWITCH_BOT_DEFAULT_COLOR || "F1C40F";
let [ hue, sat, light ] = convert.rgb.hsl(convert.hex.rgb(defaultcolor));
let connected = false;
if (!process.env.TWITCH_BOT_KEY || !process.env.TWITCH_BOT_USERNAME) {
console.log(
"TWITCH_BOT_KEY and TWITCH_BOT_USERNAME must be available as environment variables"
);
process.exit(1);
}
const colorMode = process.env.TWITCH_BOT_COLOR_MODE || "loop";
const client = new tmi.Client({
connection: {
reconnect: true,
secure: true
},
identity: {
username: process.env.TWITCH_BOT_USERNAME,
password: process.env.TWITCH_BOT_KEY
},
channels: [process.env.TWITCH_BOT_USERNAME.toLowerCase()]
});
client.on("connected", onConnected);
client.on("disconnected", onDisconnected);
client.connect();
function onConnected(addr, port) {
console.log(`* Connected to ${addr}:${port}`);
connected = true;
updateColor();
}
function onDisconnected(reason) {
console.log(`* Disconnected: ${reason}`);
connected = false;
}
function generateRandomColor() {
hue = Math.floor(Math.random() * 360);
sat = 20 + Math.floor(Math.random() * 60);
light = 40 + Math.floor(Math.random() * 40);
}
function incrementColorLoop() {
if (hue < 351) {
hue += 2;
} else {
hue = 0;
}
}
function updateColor() {
if (!connected) {
console.log('tried to update color while not connected.');
return;
}
if (colorMode === "random") {
generateRandomColor();
} else {
incrementColorLoop();
}
const color = convert.hsl.hex(hue, sat, light);
console.log(
`* Updating username color to`,
chalk.hex(`#${color}`)(`#${color}`)
);
client.color(`#${color}`);
}
const intervalTime = process.env.TWITCH_BOT_INTERVAL * 1000 || 10000;
interval = setInterval(function () {
updateColor();
}, intervalTime);
const sigs = ['SIGINT', 'SIGTERM', 'SIGQUIT'];
sigs.forEach(sig => {
process.on(sig, () => {
console.log(sig + " received");
clearInterval(interval);
console.log(
`* Updating username color to`,
chalk.hex(`#${defaultcolor}`)(`#${defaultcolor}`)
);
client.color(`#${defaultcolor}`).then(() => client.disconnect());
console.log("Waiting 3 seconds before exiting...");
sleep(3000).then(() => {
process.exit(0);
});
});
});