Chat statistics: per-viewer messages, emotes, commands; raw chat kept 30 days
Server reads chat via EventSub channel.chat.message (works without OBS) and counts each message at once into chat_user, chat_user_day, chat_emote (Twitch + 7TV by name) and chat_command. Raw messages are a 30-day buffer (hourly cleanup); deletes, timeouts/bans and chat clears remove stored text at once; hidden chatters are not counted. chatlog.forgetUser() for removal requests. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
30f42a65e8
commit
cd751e3a07
5 changed files with 156 additions and 2 deletions
|
|
@ -41,9 +41,12 @@ Estimate: about half a day once chat is read server-side.
|
||||||
- Store only: message id, time, user id + login + display name, text, badges, emotes, first-message / reply flags.
|
- Store only: message id, time, user id + login + display name, text, badges, emotes, first-message / reply flags.
|
||||||
- Honour moderation: `channel.chat.message_delete`, `channel.chat.clear_user_messages` (timeouts/bans) and
|
- Honour moderation: `channel.chat.message_delete`, `channel.chat.clear_user_messages` (timeouts/bans) and
|
||||||
`channel.chat.clear` remove or blank the stored messages.
|
`channel.chat.clear` remove or blank the stored messages.
|
||||||
- Retention: raw messages 12 months (then deleted), aggregated statistics kept.
|
- Retention: raw messages 30 days (then deleted), aggregated statistics kept.
|
||||||
- "Delete this user's messages" control for removal requests; a line in the Twitch panels that chat is logged
|
- "Delete this user's messages" control for removal requests; a line in the Twitch panels that chat is logged
|
||||||
for stream statistics.
|
for stream statistics.
|
||||||
- Size: a few MB per month in SQLite.
|
- Size: a few MB per month in SQLite.
|
||||||
|
|
||||||
Status: proposed 2026-11-22, waiting for her OK on the defaults above before logging starts.
|
Status: **logging built 2026-11-22** (src/chatlog.js), with her choices: per-viewer counts (messages, per day,
|
||||||
|
emotes incl. 7TV, !commands, first/last seen) parsed as messages arrive; raw messages kept **30 days** only;
|
||||||
|
moderation removes stored text; hidden chatters (bots) not counted. Still to do: a statistics page, and a
|
||||||
|
"forget this viewer" button for removal requests (`chatlog.forgetUser()` exists).
|
||||||
|
|
|
||||||
130
src/chatlog.js
Normal file
130
src/chatlog.js
Normal file
|
|
@ -0,0 +1,130 @@
|
||||||
|
// Chat statistics. Every chat message (EventSub channel.chat.message, read on the server) is counted right away
|
||||||
|
// into per-viewer totals; the raw message is only a 30-day buffer.
|
||||||
|
//
|
||||||
|
// chat_user per viewer: messages, first/last seen
|
||||||
|
// chat_user_day per viewer per day: messages (activity over time)
|
||||||
|
// chat_emote per viewer per emote: uses (Twitch emotes from the message, 7TV channel + global by name)
|
||||||
|
// chat_command per viewer per !command: uses, last used
|
||||||
|
// chat_raw the messages themselves, deleted after RAW_DAYS
|
||||||
|
//
|
||||||
|
// Moderation: a deleted message, a timeout/ban (clear_user_messages) or a chat clear removes the stored text at
|
||||||
|
// once (Twitch developer rules); the counts stay, they hold no message content.
|
||||||
|
// Accounts in Settings → Hidden chatters (bots) are not counted.
|
||||||
|
const db = require('./db');
|
||||||
|
|
||||||
|
const RAW_DAYS = 30;
|
||||||
|
let ready = false;
|
||||||
|
|
||||||
|
function init() {
|
||||||
|
if (ready) return;
|
||||||
|
db.raw().exec(`
|
||||||
|
CREATE TABLE IF NOT EXISTS chat_raw (
|
||||||
|
id TEXT PRIMARY KEY, -- Twitch message id
|
||||||
|
at TEXT NOT NULL, -- ISO time
|
||||||
|
user_id TEXT NOT NULL, user_login TEXT, user_name TEXT,
|
||||||
|
text TEXT, emotes TEXT, -- emotes: JSON [name, ...] as counted
|
||||||
|
command TEXT,
|
||||||
|
first_msg INTEGER DEFAULT 0
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS chat_raw_at ON chat_raw(at);
|
||||||
|
CREATE INDEX IF NOT EXISTS chat_raw_user ON chat_raw(user_id);
|
||||||
|
CREATE TABLE IF NOT EXISTS chat_user (
|
||||||
|
user_id TEXT PRIMARY KEY, user_login TEXT, user_name TEXT,
|
||||||
|
messages INTEGER DEFAULT 0, first_seen TEXT, last_seen TEXT
|
||||||
|
);
|
||||||
|
CREATE TABLE IF NOT EXISTS chat_user_day (
|
||||||
|
user_id TEXT NOT NULL, day TEXT NOT NULL, messages INTEGER DEFAULT 0,
|
||||||
|
PRIMARY KEY (user_id, day)
|
||||||
|
);
|
||||||
|
CREATE TABLE IF NOT EXISTS chat_emote (
|
||||||
|
user_id TEXT NOT NULL, emote TEXT NOT NULL, -- emote name as typed
|
||||||
|
source TEXT, emote_id TEXT, uses INTEGER DEFAULT 0, last_used TEXT,
|
||||||
|
PRIMARY KEY (user_id, emote)
|
||||||
|
);
|
||||||
|
CREATE TABLE IF NOT EXISTS chat_command (
|
||||||
|
user_id TEXT NOT NULL, command TEXT NOT NULL, uses INTEGER DEFAULT 0, last_used TEXT,
|
||||||
|
PRIMARY KEY (user_id, command)
|
||||||
|
);
|
||||||
|
`);
|
||||||
|
ready = true;
|
||||||
|
setInterval(prune, 60 * 60 * 1000).unref();
|
||||||
|
prune();
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- 7TV emotes (channel set + global), refreshed every hour; Twitch emotes come marked in the message ---
|
||||||
|
let seventv = new Map(), seventvAt = 0;
|
||||||
|
async function load7tv(twitchId) {
|
||||||
|
if (Date.now() - seventvAt < 60 * 60 * 1000) return;
|
||||||
|
seventvAt = Date.now();
|
||||||
|
const next = new Map();
|
||||||
|
const add = set => { for (const e of set?.emotes || []) next.set(e.name, e.id); };
|
||||||
|
try { const r = await fetch('https://7tv.io/v3/emote-sets/global'); if (r.ok) add(await r.json()); } catch {}
|
||||||
|
try { const r = await fetch(`https://7tv.io/v3/users/twitch/${encodeURIComponent(twitchId)}`); if (r.ok) add((await r.json()).emote_set); } catch {}
|
||||||
|
if (next.size) seventv = next;
|
||||||
|
}
|
||||||
|
|
||||||
|
function hiddenUsers() {
|
||||||
|
return String(db.getSettings().chat_hidden_users || '').toLowerCase().split(/[\s,]+/).filter(Boolean);
|
||||||
|
}
|
||||||
|
|
||||||
|
// one chat message: count it, keep the raw copy
|
||||||
|
function onMessage(e) {
|
||||||
|
init();
|
||||||
|
if (e.broadcaster_user_id) load7tv(e.broadcaster_user_id).catch(() => {});
|
||||||
|
const login = String(e.chatter_user_login || '').toLowerCase();
|
||||||
|
if (!e.chatter_user_id || hiddenUsers().includes(login)) return;
|
||||||
|
const text = String(e.message?.text || '');
|
||||||
|
const at = new Date().toISOString(), day = at.slice(0, 10);
|
||||||
|
|
||||||
|
// emotes: Twitch ones are marked by Twitch; any other word that is a 7TV emote counts too
|
||||||
|
const emotes = [];
|
||||||
|
for (const f of e.message?.fragments || []) {
|
||||||
|
if (f.type === 'emote') emotes.push({ name: f.text, source: 'twitch', id: f.emote?.id || null });
|
||||||
|
else if (f.type === 'text') for (const w of f.text.split(/\s+/)) if (w && seventv.has(w)) emotes.push({ name: w, source: '7tv', id: seventv.get(w) });
|
||||||
|
}
|
||||||
|
const m = /^\s*!(\w[\w-]{0,30})/.exec(text);
|
||||||
|
const command = m ? '!' + m[1].toLowerCase() : null;
|
||||||
|
|
||||||
|
const d = db.raw();
|
||||||
|
d.transaction(() => {
|
||||||
|
d.prepare(`INSERT OR IGNORE INTO chat_raw (id, at, user_id, user_login, user_name, text, emotes, command, first_msg)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`)
|
||||||
|
.run(e.message_id, at, e.chatter_user_id, login, e.chatter_user_name || login, text,
|
||||||
|
JSON.stringify(emotes.map(x => x.name)), command, e.message_type === 'user_intro' ? 1 : 0);
|
||||||
|
d.prepare(`INSERT INTO chat_user (user_id, user_login, user_name, messages, first_seen, last_seen) VALUES (?, ?, ?, 1, ?, ?)
|
||||||
|
ON CONFLICT(user_id) DO UPDATE SET messages = messages + 1, user_login = excluded.user_login,
|
||||||
|
user_name = excluded.user_name, last_seen = excluded.last_seen`)
|
||||||
|
.run(e.chatter_user_id, login, e.chatter_user_name || login, at, at);
|
||||||
|
d.prepare(`INSERT INTO chat_user_day (user_id, day, messages) VALUES (?, ?, 1)
|
||||||
|
ON CONFLICT(user_id, day) DO UPDATE SET messages = messages + 1`).run(e.chatter_user_id, day);
|
||||||
|
const em = d.prepare(`INSERT INTO chat_emote (user_id, emote, source, emote_id, uses, last_used) VALUES (?, ?, ?, ?, 1, ?)
|
||||||
|
ON CONFLICT(user_id, emote) DO UPDATE SET uses = uses + 1, last_used = excluded.last_used`);
|
||||||
|
for (const x of emotes) em.run(e.chatter_user_id, x.name, x.source, x.id, at);
|
||||||
|
if (command) d.prepare(`INSERT INTO chat_command (user_id, command, uses, last_used) VALUES (?, ?, 1, ?)
|
||||||
|
ON CONFLICT(user_id, command) DO UPDATE SET uses = uses + 1, last_used = excluded.last_used`)
|
||||||
|
.run(e.chatter_user_id, command, at);
|
||||||
|
})();
|
||||||
|
}
|
||||||
|
|
||||||
|
// moderation: remove stored message text (counts stay)
|
||||||
|
function onDelete(e) { init(); db.raw().prepare('DELETE FROM chat_raw WHERE id = ?').run(e.message_id); }
|
||||||
|
function onClearUser(e) { init(); db.raw().prepare('DELETE FROM chat_raw WHERE user_id = ?').run(e.target_user_id); }
|
||||||
|
function onClear() { init(); db.raw().prepare(`DELETE FROM chat_raw WHERE at >= ?`).run(new Date(Date.now() - 24 * 3600e3).toISOString()); }
|
||||||
|
|
||||||
|
function prune() {
|
||||||
|
const cut = new Date(Date.now() - RAW_DAYS * 24 * 3600e3).toISOString();
|
||||||
|
const n = db.raw().prepare('DELETE FROM chat_raw WHERE at < ?').run(cut).changes;
|
||||||
|
if (n) console.log(`[chatlog] pruned ${n} raw message(s) older than ${RAW_DAYS} days`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// removal request: forget a viewer completely (raw + counts)
|
||||||
|
function forgetUser(userIdOrLogin) {
|
||||||
|
init();
|
||||||
|
const d = db.raw();
|
||||||
|
const u = d.prepare('SELECT user_id FROM chat_user WHERE user_id = ? OR user_login = ?').get(String(userIdOrLogin), String(userIdOrLogin).toLowerCase());
|
||||||
|
if (!u) return 0;
|
||||||
|
for (const t of ['chat_raw', 'chat_user', 'chat_user_day', 'chat_emote', 'chat_command']) d.prepare(`DELETE FROM ${t} WHERE user_id = ?`).run(u.user_id);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { init, onMessage, onDelete, onClearUser, onClear, prune, forgetUser, RAW_DAYS };
|
||||||
|
|
@ -377,4 +377,5 @@ module.exports = {
|
||||||
getAllVariations, getVariationsFor, getVariation, createVariation, updateVariation, renameTrigger, deleteVariation,
|
getAllVariations, getVariationsFor, getVariation, createVariation, updateVariation, renameTrigger, deleteVariation,
|
||||||
getAllTtsVoices, getTtsVoice, createTtsVoice, updateTtsVoice, deleteTtsVoice,
|
getAllTtsVoices, getTtsVoice, createTtsVoice, updateTtsVoice, deleteTtsVoice,
|
||||||
logActivity, getActivityLog, getActivity,
|
logActivity, getActivityLog, getActivity,
|
||||||
|
raw: () => db, // for modules that keep their own tables (chatlog.js)
|
||||||
};
|
};
|
||||||
|
|
|
||||||
|
|
@ -8,6 +8,7 @@ const { WebSocket } = require('ws');
|
||||||
const twitch = require('./twitch');
|
const twitch = require('./twitch');
|
||||||
const alerts = require('./alerts');
|
const alerts = require('./alerts');
|
||||||
const redeems = require('./redeems');
|
const redeems = require('./redeems');
|
||||||
|
const chatlog = require('./chatlog');
|
||||||
|
|
||||||
const EVENTSUB_URL = 'wss://eventsub.wss.twitch.tv/ws';
|
const EVENTSUB_URL = 'wss://eventsub.wss.twitch.tv/ws';
|
||||||
|
|
||||||
|
|
@ -128,6 +129,11 @@ async function subscribeAll(sessionId) {
|
||||||
{ type: 'channel.custom_power_up_redemption.add', version: '1', condition: { broadcaster_user_id: b } },
|
{ type: 'channel.custom_power_up_redemption.add', version: '1', condition: { broadcaster_user_id: b } },
|
||||||
// subs, resubs, gifts, community gifts, raids, with Prime/multi-month/recipient/message details
|
// 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.chat.notification', version: '1', condition: { broadcaster_user_id: b, user_id: b } },
|
||||||
|
// chat statistics (chatlog.js): every message, plus deletes / timeouts+bans / clears to drop stored text
|
||||||
|
{ type: 'channel.chat.message', version: '1', condition: { broadcaster_user_id: b, user_id: b } },
|
||||||
|
{ type: 'channel.chat.message_delete', version: '1', condition: { broadcaster_user_id: b, user_id: b } },
|
||||||
|
{ type: 'channel.chat.clear_user_messages', version: '1', condition: { broadcaster_user_id: b, user_id: b } },
|
||||||
|
{ type: 'channel.chat.clear', 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 } },
|
{ type: 'channel.channel_points_custom_reward_redemption.add', version: '1', condition: { broadcaster_user_id: b } },
|
||||||
// built-in rewards: highlight message, unlock emote, ...
|
// built-in rewards: highlight message, unlock emote, ...
|
||||||
{ type: 'channel.channel_points_automatic_reward_redemption.add', version: '2', condition: { broadcaster_user_id: b } },
|
{ type: 'channel.channel_points_automatic_reward_redemption.add', version: '2', condition: { broadcaster_user_id: b } },
|
||||||
|
|
@ -209,6 +215,18 @@ function handleNotification(payload) {
|
||||||
if (alert) alerts.send(alert, event);
|
if (alert) alerts.send(alert, event);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
case 'channel.chat.message':
|
||||||
|
try { chatlog.onMessage(event); } catch (e) { console.error('[chatlog]', e.message); }
|
||||||
|
break;
|
||||||
|
case 'channel.chat.message_delete':
|
||||||
|
try { chatlog.onDelete(event); } catch (e) { console.error('[chatlog]', e.message); }
|
||||||
|
break;
|
||||||
|
case 'channel.chat.clear_user_messages':
|
||||||
|
try { chatlog.onClearUser(event); } catch (e) { console.error('[chatlog]', e.message); }
|
||||||
|
break;
|
||||||
|
case 'channel.chat.clear':
|
||||||
|
try { chatlog.onClear(event); } catch (e) { console.error('[chatlog]', e.message); }
|
||||||
|
break;
|
||||||
case 'channel.custom_power_up_redemption.add': {
|
case 'channel.custom_power_up_redemption.add': {
|
||||||
const p = event.custom_power_up || {};
|
const p = event.custom_power_up || {};
|
||||||
if (p.id) redeems.handle('custom_power_up', p.id, p.title || 'Custom Power-up',
|
if (p.id) redeems.handle('custom_power_up', p.id, p.title || 'Custom Power-up',
|
||||||
|
|
|
||||||
|
|
@ -19,6 +19,8 @@ server.listen(PORT, () => {
|
||||||
console.log(`[server] APP_BASE_URL: ${process.env.APP_BASE_URL}`);
|
console.log(`[server] APP_BASE_URL: ${process.env.APP_BASE_URL}`);
|
||||||
console.log(`[server] DB_PATH: ${process.env.DB_PATH}`);
|
console.log(`[server] DB_PATH: ${process.env.DB_PATH}`);
|
||||||
|
|
||||||
|
require('./chatlog').init(); // chat statistics tables + hourly 30-day cleanup of raw messages
|
||||||
|
|
||||||
// Resume EventSub with the stored login, so alerts survive restarts and deploys
|
// Resume EventSub with the stored login, so alerts survive restarts and deploys
|
||||||
// without logging in again. (Set EVENTSUB_DISABLED=1 for local UI work.)
|
// without logging in again. (Set EVENTSUB_DISABLED=1 for local UI work.)
|
||||||
const user = db.getPrimaryUser();
|
const user = db.getPrimaryUser();
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue