Last active
April 5, 2025 15:23
-
-
Save creativenull/29fbb79202f0f24a76a8d098b45e5239 to your computer and use it in GitHub Desktop.
Simple twitch chat bot, connected via websockets for the browser, nodejs and deno
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* A quick, simple way to connect to a channel as a twitch chat bot. Works in the browser, deno and nodejs. | |
* Note for nodejs, you will need the `ws` package. | |
* | |
* OAUTH_TOKEN: https://twitchapps.com/tmi/ (omit 'oauth:' from the string) | |
* BOT_USERNAME: Name of the bot that will be used to post messages to the main channel | |
* CHANNEL_NAME: Name of the target channel for the BOT_USERNAME to join | |
*/ | |
// For NodeJS only: `npm install ws` | |
// import WebSocket from "ws"; | |
const OAUTH_TOKEN = ""; | |
const BOT_USERNAME = ""; | |
const CHANNEL_NAME = ""; | |
const twitchWssUrl = "wss://irc-ws.chat.twitch.tv:443"; | |
const chat = new WebSocket(twitchWssUrl); | |
chat.addEventListener("open", () => { | |
// Successful connection to twitch IRC endpoint | |
// Connecting to user channel | |
chat.send(`PASS oauth:${OAUTH_TOKEN}`); | |
chat.send(`NICK ${BOT_USERNAME}`); | |
chat.send(`JOIN #${CHANNEL_NAME}`); | |
console.log(`Successful connection to: ${CHANNEL_NAME}`); | |
}); | |
chat.addEventListener("message", (e: MessageEvent<string>) => { | |
if (e.data.includes("PRIVMSG")) { | |
console.log(e.data); | |
} else if (e.data.includes("PING")) { | |
console.log("PONG"); | |
chat.send("PONG :tmi.twitch.tv") | |
} | |
}); | |
chat.addEventListener("error", (e) => { | |
console.log("Connect error:", JSON.stringify(e)); | |
chat.close(); | |
}); | |
chat.addEventListener("close", () => { | |
console.log("Connection Terminated"); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment