summaryrefslogtreecommitdiff
path: root/scripts/chat.js
blob: d26a4baa8b90ad46a1c2c9f4a443dbd5128338c0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
function addMessage(author, message) {
    const messages = document.getElementById("messages");
    if (!messages) {
        return;
    }
    
    const elem = document.createElement("p");
    elem.classList.add("message");
    
    elem.innerHTML = `<span class="author">${author}:</span> ${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);
    });
}