Skip to content

Instantly share code, notes, and snippets.

@hlfbt
Last active April 10, 2022 01:28
Show Gist options
  • Save hlfbt/eb2c060872f9e01ef648b84d8e9561b1 to your computer and use it in GitHub Desktop.
Save hlfbt/eb2c060872f9e01ef648b84d8e9561b1 to your computer and use it in GitHub Desktop.
Twitch Color Switcher for you bad bad kids out there. Enable with `enableColorSwitcher(<switching_interval_in_seconds>)` and disable again by reloading or calling `disableColorSwitcher()`.
let oauthToken = document.cookie.match(/auth-token=([0-9a-z]+);/)[1];
const updateChatColor = function (chatColor) {
fetch('https://gql.twitch.tv/gql', {
method: 'POST',
body: JSON.stringify({
query:
`mutation Chat_UpdateChatColor(\$input: UpdateChatColorInput!) {
updateChatColor(input: \$input) {
user {
id
chatColor
}
}
}`,
variables: {
input: {
color: chatColor
}
}
}),
headers: {
'Authorization': `OAuth ${oauthToken}`
}
});
};
const hslToRgb = function (h, s, l) {
let r, g, b;
if (typeof h === 'object' && typeof s === 'undefined') {
[h, s, l] = Object.values(h);
}
if (s == 0) {
r = g = b = l;
} else {
const hue2rgb = function (p, q, t) {
if (t < 0) t += 1;
if (t > 1) t -= 1;
if (t < 1/6) return p + (q - p) * 6 * t;
if (t < 1/2) return q;
if (t < 2/3) return p + (q - p) * (2/3 - t) * 6;
return p;
};
let q = l < 0.5 ? l * (1 + s) : l + s - l * s;
let p = 2 * l - q;
r = hue2rgb(p, q, h + 1/3);
g = hue2rgb(p, q, h);
b = hue2rgb(p, q, h - 1/3);
}
return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)];
};
const generateRandomHsl = function () {
return {
h: Math.random(),
// Generates mostly bright-ish pastel colors
s: 0.7,
l: 0.9
// Generates dark colors as well (use the random l value if you also want darker, but possibly less pastel colors)
// s: 1 - (Math.random() * 0.15),
// l: 0.4 + (Math.random() * 0.2)
};
};
const rgbToHex = function (...rgb) {
return '#' + rgb.slice(0, 3).map(c => ('00' + c.toString(16)).slice(-2)).join('');
};
var colorSwitcherInterval = null;
const enableColorSwitcher = function (intervalInSeconds) {
colorSwitcherInterval = window.setInterval(function () {
let color = hslToRgb(generateRandomHsl());
updateChatColor(rgbToHex(...color));
}, intervalInSeconds * 1e3);
};
const disableColorSwitcher = function () {
window.clearInterval(colorSwitcherInterval);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment