// Twitch EventSub over WebSocket. // // - start(user) is called on boot (stored login) and after OAuth login. // - session_reconnect: connect to the given URL, subscriptions carry over, then close the old socket. // - keepalive watchdog: if Twitch goes silent longer than keepalive_timeout_seconds, reconnect. // - subscription requests refresh the token on 401 (see twitch.js). const { WebSocket } = require('ws'); const twitch = require('./twitch'); const alerts = require('./alerts'); const redeems = require('./redeems'); const EVENTSUB_URL = 'wss://eventsub.wss.twitch.tv/ws'; let ws = null; let shouldRun = false; let broadcasterId = null; let keepaliveMs = 30_000; let watchdog = null; let reconnectTimer = null; const status = { connected: false, sessionId: null, subscribed: [], failed: [], lastEventAt: null }; function start(user) { twitch.setUser(user); broadcasterId = user.twitch_id; shouldRun = true; console.log(`[eventsub] Starting — broadcaster: ${user.login} (${broadcasterId})`); closeSocket(ws); connect(EVENTSUB_URL, true); } function stop() { shouldRun = false; clearTimeout(reconnectTimer); clearTimeout(watchdog); closeSocket(ws); ws = null; status.connected = false; console.log('[eventsub] Stopped'); } function closeSocket(sock) { if (!sock) return; sock.removeAllListeners('close'); // a deliberate close must not trigger the auto-reconnect sock.on('error', () => {}); try { sock.close(); } catch { /* already closed */ } } function scheduleReconnect(delay = 10_000) { clearTimeout(reconnectTimer); if (!shouldRun) return; reconnectTimer = setTimeout(() => connect(EVENTSUB_URL, true), delay); } function armWatchdog() { clearTimeout(watchdog); watchdog = setTimeout(() => { console.warn('[eventsub] Keepalive missed — reconnecting'); closeSocket(ws); ws = null; status.connected = false; scheduleReconnect(1000); }, keepaliveMs + 10_000); } // fresh = new session (needs subscriptions); false = reconnect URL (subscriptions carry over) function connect(url, fresh) { console.log(`[eventsub] Connecting${fresh ? '' : ' (reconnect URL)'}...`); const sock = new WebSocket(url); sock.on('message', raw => { let msg; try { msg = JSON.parse(raw); } catch { return; } handleMessage(sock, msg, fresh).catch(e => console.error('[eventsub] handler error:', e.message)); }); sock.on('close', code => { if (sock !== ws) return; // an old socket we already replaced console.log(`[eventsub] Disconnected (${code})`); status.connected = false; clearTimeout(watchdog); scheduleReconnect(); }); sock.on('error', e => console.error('[eventsub] Error:', e.message)); if (fresh) { closeSocket(ws); ws = sock; } } async function handleMessage(sock, msg, fresh) { const type = msg.metadata?.message_type; if (sock === ws || type === 'session_welcome') armWatchdog(); switch (type) { case 'session_welcome': { const s = msg.payload.session; keepaliveMs = (s.keepalive_timeout_seconds || 10) * 1000; if (!fresh) { // handover from session_reconnect: swap sockets const old = ws; ws = sock; closeSocket(old); } status.connected = true; status.sessionId = s.id; console.log(`[eventsub] Session ${fresh ? 'established' : 'resumed'}: ${s.id}`); armWatchdog(); if (fresh) await subscribeAll(s.id); break; } case 'session_reconnect': console.log('[eventsub] Reconnect requested by Twitch'); connect(msg.payload.session.reconnect_url, false); break; case 'notification': status.lastEventAt = new Date().toISOString(); handleNotification(msg.payload); break; case 'revocation': console.warn(`[eventsub] Subscription revoked: ${msg.payload.subscription.type} (${msg.payload.subscription.status})`); break; } } async function subscribeAll(sessionId) { const b = broadcasterId; const subs = [ { type: 'channel.follow', version: '2', condition: { broadcaster_user_id: b, moderator_user_id: b } }, // cheers AND bits Power-ups (message effect, celebration, gigantify); replaces channel.cheer { type: 'channel.bits.use', version: '1', condition: { broadcaster_user_id: b } }, // subs, resubs, gifts, community gifts, raids, with Prime/multi-month/recipient/message details { type: 'channel.chat.notification', version: '1', condition: { broadcaster_user_id: b, user_id: b } }, { type: 'channel.channel_points_custom_reward_redemption.add', version: '1', condition: { broadcaster_user_id: b } }, // built-in rewards: highlight message, unlock emote, ... { type: 'channel.channel_points_automatic_reward_redemption.add', version: '2', condition: { broadcaster_user_id: b } }, // live poll card on the overlay { type: 'channel.poll.begin', version: '1', condition: { broadcaster_user_id: b } }, { type: 'channel.poll.progress', version: '1', condition: { broadcaster_user_id: b } }, { type: 'channel.poll.end', version: '1', condition: { broadcaster_user_id: b } }, // outgoing raid: send-off card (incoming raids come through channel.chat.notification) { type: 'channel.raid', version: '1', condition: { from_broadcaster_user_id: b } }, // Hype Train alerts (start, level up, end) { type: 'channel.hype_train.begin', version: '2', condition: { broadcaster_user_id: b } }, { type: 'channel.hype_train.progress', version: '2', condition: { broadcaster_user_id: b } }, { type: 'channel.hype_train.end', version: '2', condition: { broadcaster_user_id: b } }, ]; try { await twitch.validate(); } catch (e) { console.error('[eventsub]', e.message); } status.subscribed = []; status.failed = []; for (const sub of subs) { try { const res = await twitch.helix('/eventsub/subscriptions', { method: 'POST', body: { ...sub, transport: { method: 'websocket', session_id: sessionId } }, }); if (res.status === 202) { status.subscribed.push(sub.type); console.log(`[eventsub] Subscribed: ${sub.type}`); } else { const body = await res.text(); status.failed.push(`${sub.type} (${res.status})`); console.warn(`[eventsub] Subscribe ${sub.type} → ${res.status}: ${body}`); } } catch (e) { status.failed.push(`${sub.type} (${e.message})`); console.error(`[eventsub] Subscribe ${sub.type} failed:`, e.message); } } } function handleNotification(payload) { const type = payload.subscription.type; const event = payload.event; switch (type) { case 'channel.follow': alerts.send(alerts.fromFollow(event), event); break; case 'channel.bits.use': if (event.type === 'power_up' && event.power_up?.type) { const t = event.power_up.type; redeems.handle('power_up', t, redeems.POWER_UPS[t] || `Power-up: ${t}`, { user: event.user_name || event.user_login, input: event.message?.text || null, emote: event.power_up.emote?.id }, event); } else { alerts.send(alerts.fromBitsUse(event), event); } break; case 'channel.chat.notification': { const alert = alerts.fromChatNotification(event); if (alert) alerts.send(alert, event); else console.log(`[eventsub] chat notification ${event.notice_type} — no alert`); break; } case 'channel.channel_points_custom_reward_redemption.add': redeems.handle('reward', event.reward.id, event.reward.title, { user: event.user_name || event.user_login, input: event.user_input || null }, event); break; case 'channel.poll.begin': case 'channel.poll.progress': case 'channel.poll.end': alerts.sendPoll(type.split('.').pop(), event); break; case 'channel.hype_train.begin': case 'channel.hype_train.progress': case 'channel.hype_train.end': { const phase = type.split('.').pop(); alerts.sendHypeBar(phase, event); // persistent progress bar const alert = alerts.fromHypeTrain(phase, event); // queued alert on start / new level / end if (alert) alerts.send(alert, event); break; } case 'channel.raid': if (event.from_broadcaster_user_id === broadcasterId) alerts.raidHappened(event).catch(e => console.error('[alerts] raid out:', e.message)); break; case 'channel.channel_points_automatic_reward_redemption.add': { const t = event.reward?.type; redeems.handle('auto_reward', t, redeems.AUTO_REWARDS[t] || t, { user: event.user_name || event.user_login, input: event.message?.text || null, emote: event.reward?.emote?.id }, event); break; } } } function getStatus() { return { ...status, running: shouldRun }; } module.exports = { start, stop, getStatus };