From e77d6b63cbfc5a13a83d7a1badc56c7bf624895d Mon Sep 17 00:00:00 2001 From: ilotterytea Date: Fri, 24 Oct 2025 20:01:36 +0500 Subject: feat: connect to twitch chat --- scripts/chat.js | 45 +++++++++++++++++++++++++++++++++++++++++++++ twitch.html | 11 ++++++++++- 2 files changed, 55 insertions(+), 1 deletion(-) create mode 100644 scripts/chat.js diff --git a/scripts/chat.js b/scripts/chat.js new file mode 100644 index 0000000..d26a4ba --- /dev/null +++ b/scripts/chat.js @@ -0,0 +1,45 @@ +function addMessage(author, message) { + const messages = document.getElementById("messages"); + if (!messages) { + return; + } + + const elem = document.createElement("p"); + elem.classList.add("message"); + + elem.innerHTML = `${author}: ${message}`; + + messages.append(elem); + + window.scrollTo(0, document.body.scrollHeight); +} + +function connectToChat(host, nick, password, room) { + const socket = new WebSocket(host); + + socket.addEventListener("open", () => { + socket.send(`NICK ${nick}`); + socket.send(`PASS ${password}`); + socket.send("CAP REQ :twitch.tv/tags"); + socket.send(`JOIN #${room}`); + addMessage("Chat", "Connected!"); + }); + + socket.addEventListener("message", (e) => { + const lines = e.data.split("\r\n"); + + for (const line of lines) { + const l = line.trim(); + if (l.length == 0) { + continue; + } + addMessage("Message", l); + } + }); + + socket.addEventListener("close", (e) => { + addMessage("Chat", `Disconnected: ${e.reason}`); + addMessage("Chat", "Reconnecting in 5 seconds..."); + setTimeout(() => connectToChat(host, nick, password, room), 5000); + }); +} \ No newline at end of file diff --git a/twitch.html b/twitch.html index 3a047b9..ca9db0a 100644 --- a/twitch.html +++ b/twitch.html @@ -4,6 +4,15 @@ chat widget + - + + + \ No newline at end of file -- cgit v1.2.3