// Channel point rewards, built-in channel point rewards and bits Power-ups. // Each trigger (kind + key) has variations; one enabled variation is picked at random, // weighted by rarity (like Twitch alert variations), and played as a polaroid or sound-only alert. const db = require('./db'); const alerts = require('./alerts'); const dispatch = require('./dispatch'); const tts = require('./tts'); // relative weight per rarity (Twitch does not publish its numbers; tune here). // chance of a variation = its weight / sum of the weights of the trigger's ENABLED variations const RARITY = { common: { label: 'Common', weight: 50 }, uncommon: { label: 'Uncommon', weight: 25 }, rare: { label: 'Rare', weight: 12 }, ultra_rare: { label: 'Ultra Rare', weight: 3 }, }; // built-in (automatic) channel point rewards, channel.channel_points_automatic_reward_redemption.add v2 const AUTO_REWARDS = { send_highlighted_message: 'Highlight my message', single_message_bypass_sub_mode: 'Send a message in sub-only mode', random_sub_emote_unlock: 'Unlock a random sub emote', chosen_sub_emote_unlock: 'Choose an emote to unlock', chosen_modified_sub_emote_unlock: 'Modify a single emote', }; // bits Power-ups, channel.bits.use with type = power_up const POWER_UPS = { message_effect: 'Power-up: Message Effect', celebration: 'Power-up: On-Screen Celebration', gigantify_an_emote: 'Power-up: Gigantify an Emote', }; // Custom Power-ups (bits, made by the streamer on Twitch): kind 'custom_power_up', key = power-up id // how a trigger is drawn on the overlay (everything else: cassette tape) const STYLE = { 'power_up:gigantify_an_emote': 'emote', // the viewer's emote, giant 'power_up:celebration': 'emote_rain', // copies of the emote bouncing around the screen 'auto_reward:send_highlighted_message': 'message', // big taped paper note with the message 'power_up:message_effect': 'message', // same as highlight }; const LINE = { emote: 'gigantified an emote!', emote_rain: 'is celebrating!', message: 'highlighted:', tts: 'says:' }; const emoteUrl = id => id ? `https://static-cdn.jtvnw.net/emoticons/v2/${encodeURIComponent(id)}/default/dark/3.0` : null; function pick(variations) { const pool = variations.filter(v => v.enabled); const total = pool.reduce((s, v) => s + (RARITY[v.rarity]?.weight || 1), 0); let r = Math.random() * total; for (const v of pool) { r -= RARITY[v.rarity]?.weight || 1; if (r < 0) return v; } return pool[pool.length - 1] || null; } function toAlert(v, { user, input, emote, bits }) { const spoken = !!(v.tts_voice_id && input); // TTS variations: envelope letter (fx.js envelope()) // video variations play full-screen on the ?parts=video overlay (public/alerts/video.js) const style = v.video ? 'video' : spoken ? 'tts' : (STYLE[`${v.kind}:${v.key}`] || 'cassette'); const line = spoken ? LINE.tts : LINE[style]; return { type: 'redeem', kind: v.kind, key: v.key, style, vid: v.id, // vid: re-speak on replay if the mp3 was pruned user, reward: v.title, variation: v.name, rarity: v.rarity, input: input || null, // special styles have their own wording unless the caption was customised caption: style !== 'cassette' && v.caption === 'redeemed it! ♡' ? line : v.caption, sound: spoken ? null : (v.sound || null), volume: v.volume, // TTS on: the voice replaces the sound polaroid: !!v.polaroid, art: v.art || null, emote: emoteUrl(emote), video: v.video || null, bits: bits ?? null, }; } // TTS: clean the viewer's text, speak it with the variation's saved voice, attach { tts, tts_ms }. // Never throws: on any problem the alert still goes out, just without speech. async function addSpeech(v, alert) { try { const voice = db.getTtsVoice(v.tts_voice_id); if (!voice || !alert.input) return; const s = db.getSettings(); const { text, blocked } = tts.prepareViewerText(alert.input, { maxChars: s.tts_max_chars, blocklist: s.tts_blocklist }); if (blocked) { console.log(`[tts] blocked message from ${alert.user}`); alert.input = '(message removed)'; return; } alert.input = text; // the note shows what is read if (!text) return; const say = s.tts_say_name && alert.user ? `${alert.user} says: ${text}` : text; const out = await tts.synth(voice.config, say); alert.tts = out.url; alert.tts_ms = out.durationMs; alert.tts_env = await tts.loudness(out.file); // word timing on the overlay alert.tts_prefix = say === text ? 0 : 2; // words spoken before the message (" says:") } catch (e) { console.warn(`[tts] ${alert.user}: ${e.message}`); } } // Twitch icons of channel point rewards (custom images only) and Custom Power-ups. // alert.icon -> top-left sticker on the cassette (cassette.js) and the video box (video.js). // Cached; reloaded every 10 min, or (at most every 30 s) when an unknown trigger comes in. const icons = new Map(); let iconsAt = 0, iconsLoading = null; const bestImg = i => (i && (i.url_4x || i.url_2x || i.url_1x)) || null; async function loadIcons() { const twitch = require('./twitch'); const u = twitch.getUser(); if (!u) return; const next = new Map(); try { const r = await twitch.helix(`/channel_points/custom_rewards?broadcaster_id=${u.twitch_id}`); if (r.ok) for (const x of (await r.json()).data || []) { const img = bestImg(x.image); if (img) next.set(`reward|${x.id}`, img); } } catch (e) { console.warn('[redeems] reward icons:', e.message); } try { const r = await twitch.helix(`/bits/custom_power_ups?broadcaster_id=${u.twitch_id}`); if (r.ok) for (const x of (await r.json()).data || []) { const img = bestImg(x.image) || bestImg(x.icon) || bestImg(x.default_image) || x.image_url || null; if (img) next.set(`custom_power_up|${x.id}`, img); } } catch (e) { console.warn('[redeems] power-up icons:', e.message); } if (next.size || !icons.size) { icons.clear(); for (const [k, v] of next) icons.set(k, v); } iconsAt = Date.now(); } async function iconFor(kind, key) { if (kind !== 'reward' && kind !== 'custom_power_up') return null; const age = Date.now() - iconsAt; if (age > 10 * 60000 || (!icons.has(`${kind}|${key}`) && age > 30000)) { iconsLoading = iconsLoading || loadIcons().finally(() => { iconsLoading = null; }); await Promise.race([iconsLoading, new Promise(r => setTimeout(r, 2000))]); // never hold an alert long } return icons.get(`${kind}|${key}`) || null; } // legacy action event type for the actions system / activity log const LEGACY = { reward: 'channel_points', auto_reward: 'auto_reward', power_up: 'power_up', custom_power_up: 'custom_power_up' }; // A redemption arrived from Twitch. function handle(kind, key, title, { user, input, emote, bits }, raw) { if (title) db.renameTrigger(kind, key, title); const v = pick(db.getVariationsFor(kind, key)); if (!v) { // nothing configured (or all off): still log it and run legacy actions dispatch.dispatchEvent(LEGACY[kind], key, user, raw); return null; } const alert = toAlert(v, { user, input, emote, bits }); const ready = iconFor(kind, key).then(icon => { alert.icon = icon; }); if (v.tts_voice_id && input && !v.video) ready.then(() => addSpeech(v, alert)).then(() => alerts.send(alert, raw)); // speech first, then the alert else ready.then(() => alerts.send(alert, raw)); return alert; } // Dashboard Replay of an old activity row that has no stored alert: a fresh pick for the trigger, // with the viewer's original name and text. Resolves to the alert, or null if nothing is configured. async function rebuild(kind, key, { user, input, emote, bits }) { const v = pick(db.getVariationsFor(kind, key)); if (!v) return null; const alert = toAlert(v, { user, input, emote, bits }); alert.icon = await iconFor(kind, key); if (v.tts_voice_id && input && !v.video) await addSpeech(v, alert); return alert; } // Replay of a stored TTS alert whose mp3 was pruned: speak it again with the same variation's voice. async function respeak(alert) { const v = alert.vid && db.getVariation(alert.vid); for (const k of ['tts', 'tts_ms', 'tts_env', 'tts_prefix']) delete alert[k]; if (v && v.tts_voice_id && alert.input) await addSpeech(v, alert); return alert; } // Dashboard test: one specific variation, or a random pick for the whole trigger. function test({ id, kind, key }) { const v = id ? db.getVariation(id) : pick(db.getVariationsFor(kind, key)); if (!v) return false; const input = v.tts_voice_id ? 'Hydrate check! Also, nice shot, I was totally not camping that container.' : ['send_highlighted_message', 'message_effect'].includes(v.key) ? 'this is what a highlighted message looks like on stream!' : v.kind === 'reward' ? 'test input' : null; const alert = toAlert({ ...v, enabled: 1 }, { user: 'ChickenWhisperer', input, emote: v.kind === 'power_up' ? '25' : null, bits: v.kind === 'custom_power_up' ? 50 : null }); // 25 = Kappa const ready = iconFor(v.kind, v.key).then(icon => { alert.icon = icon; }); if (v.tts_voice_id && !v.video) ready.then(() => addSpeech(v, alert)).then(() => alerts.sendTestAlert(alert)); else ready.then(() => alerts.sendTestAlert(alert)); return true; } module.exports = { RARITY, AUTO_REWARDS, POWER_UPS, STYLE, LEGACY, pick, handle, test, rebuild, respeak };