import { formatSeconds } from '../../shared/format.ts' import type { ActivityRef, AlertKey, Doc, ModAction, Punishment, ResponseType } from '../../shared/schemas.ts' import type { MessageRef, ReplyTarget } from '../atproto/bot.ts' import { getFollow, getProfile, latestPost, listRecords, type Profile } from '../atproto/identity.ts' import type { Actor, ChannelRow, Store } from '../db/store.ts' import { env } from '../env.ts' import { activityFromRecord, searchGames, type ChatMessageView, type LivestreamView } from '../streamplace.ts' import { ACTIVITY_LABELS } from '../../shared/format.ts' import { buildConfig, type ChannelConfig } from './engine/config.ts' import { escalatedTimeout, evaluateModeration, type ModVerdict, type RecentMessage } from './engine/moderation.ts' import { checkConditions, resolveRoles, type ChatUser, type UserRoles } from './engine/roles.ts' import { chunkMessage, splitArgs } from './engine/text.ts' import { renderWith, type LiveInfo, type UserInfo, type VarContext, type VarServices } from './engine/variables.ts' import { runDefaultCommand } from './commands.ts' import { Modules } from './modules.ts' import { publish, type ChatEntry, type Platform } from './platform.ts' import { fetchPublicText, getMalwareHosts, lastfmNowPlaying, tealfmNowPlaying, weather } from './services.ts' export interface IncomingMessage { uri: string cid: string text: string createdAt: string replyRoot: MessageRef | null replyParent: MessageRef | null facetUris: string[] user: ChatUser color: string | null isBot: boolean /** Not a real chat message (sent through the API), so there's nothing to reply to, hide or pin. */ synthetic?: boolean } export interface TraceStep { kind: 'info' | 'moderation' | 'command' | 'keyword' | 'module' | 'send' | 'action' | 'skip' label: string detail?: string } /** One pass of the pipeline. In dry-run mode (the config tester) nothing is written or sent. */ export class Exec { readonly dryRun: boolean readonly steps: TraceStep[] = [] /** Config tester only: pretend the sender does (or doesn't) follow the channel. */ forceFollower: boolean | undefined constructor(dryRun: boolean, forceFollower?: boolean) { this.dryRun = dryRun this.forceFollower = forceFollower } log(kind: TraceStep['kind'], label: string, detail?: string) { this.steps.push({ kind, label, detail }) } } export function toIncoming(view: ChatMessageView): IncomingMessage { const badges = (view.badges ?? []).map((b) => b.badgeType.split('#').pop() ?? '') const selfBot = view.chatProfile?.selfLabels?.includes('bot') ?? false if (selfBot && !badges.includes('bot')) badges.push('bot') const c = view.chatProfile?.color const facetUris = (view.record.facets ?? []).flatMap((f) => f.features.filter((x) => x.uri).map((x) => x.uri!)) return { uri: view.uri, cid: view.cid, text: view.record.text ?? '', createdAt: view.record.createdAt ?? view.indexedAt, replyRoot: view.record.reply?.root ?? null, replyParent: view.record.reply?.parent ?? null, facetUris, user: { did: view.author.did, handle: view.author.handle, displayName: view.author.displayName || view.author.handle, badges }, color: c ? `rgb(${c.red}, ${c.green}, ${c.blue})` : null, isBot: badges.includes('bot'), } } interface TimerState { lastSent: number lines: number index: number } const HISTORY = 400 export class ChannelRuntime { readonly channelId: string readonly store: Store readonly platform: Platform readonly modules: Modules channel: ChannelRow cfg: ChannelConfig live: LiveInfo = { isLive: false, title: '', activity: null, activitySince: null, startedAt: null, endedAt: null, viewers: 0, gamesPlayed: [] } streamUri: string | null = null liveKnown = false socketConnected = false readonly recent: (RecentMessage & { uri: string; handle: string; replyRoot: string | null; hidden: boolean })[] = [] readonly chatterSeen = new Map() readonly permits = new Map() private cooldowns = new Map() private timerState = new Map() private moderators = new Set() private moderatorsLoadedAt = 0 private sendChain: Promise = Promise.resolve() private lastSendAt = 0 readonly startedAt = Date.now() constructor(channel: ChannelRow, store: Store, platform: Platform) { this.channel = channel this.channelId = channel.id this.store = store this.platform = platform this.cfg = buildConfig(store, channel.id) this.modules = new Modules(this) this.restoreStreamHistory() } reload() { this.cfg = buildConfig(this.store, this.channelId) this.channel = this.store.getChannel(this.channelId) ?? this.channel } get settings() { return this.cfg.get('settings') } get actor(): Actor { return { did: null, handle: 'superbot' } } channelInfo(): UserInfo { return { did: this.channel.id, handle: this.channel.handle, displayName: this.channel.display_name || this.channel.handle, avatar: this.channel.avatar } } // --- live state ----------------------------------------------------------- private restoreStreamHistory() { const last = this.store.db.get<{ uri: string; title: string; activities: string; started_at: string; ended_at: string | null }>( 'SELECT * FROM streams WHERE channel_id = ? ORDER BY id DESC LIMIT 1', this.channelId, ) if (!last) return this.live.gamesPlayed = JSON.parse(last.activities) this.live.title = last.title if (last.ended_at) this.live.endedAt = Date.parse(last.ended_at) } /** Called by the manager's live poll with the current livestream, or null when offline. */ async updateLive(view: LivestreamView | null) { const first = !this.liveKnown this.liveKnown = true const wasLive = this.live.isLive if (view) { const activity = activityFromRecord(view.record.activity) const prevTitle = this.live.title const prevActivity = this.live.activity this.live.isLive = true this.live.title = view.record.title ?? '' this.live.viewers = view.viewerCount?.count ?? this.live.viewers this.streamUri = view.uri if (!wasLive) { this.live.startedAt = Date.parse(view.record.createdAt) || Date.now() this.live.activity = activity this.live.activitySince = Date.now() this.live.gamesPlayed = activity ? [activity.name] : [] this.store.db.run( 'INSERT INTO streams (channel_id, uri, title, activities, started_at) VALUES (?, ?, ?, ?, ?) ON CONFLICT(channel_id, uri) DO UPDATE SET ended_at = NULL', this.channelId, view.uri, this.live.title, JSON.stringify(this.live.gamesPlayed), new Date(this.live.startedAt).toISOString(), ) const row = this.store.db.get<{ activities: string }>('SELECT activities FROM streams WHERE channel_id = ? AND uri = ?', this.channelId, view.uri) if (row) this.live.gamesPlayed = JSON.parse(row.activities) if (!first) { this.store.audit(this.channelId, this.actor, 'stream', `Went live: ${this.live.title}`) await this.alert('live', {}) await this.modules.onLive(true) } } else { if (prevTitle !== this.live.title && !first) { this.store.db.run('UPDATE streams SET title = ? WHERE channel_id = ? AND uri = ?', this.live.title, this.channelId, view.uri) await this.alert('title', {}) } if ((prevActivity?.id ?? null) !== (activity?.id ?? null)) { this.live.activity = activity this.live.activitySince = Date.now() if (activity && !this.live.gamesPlayed.includes(activity.name)) { this.live.gamesPlayed.push(activity.name) this.store.db.run('UPDATE streams SET activities = ? WHERE channel_id = ? AND uri = ?', JSON.stringify(this.live.gamesPlayed), this.channelId, view.uri) } if (!first && activity) await this.alert('activity', {}) } } } else if (wasLive) { this.live.isLive = false this.live.endedAt = Date.now() this.live.viewers = 0 this.store.db.run("UPDATE streams SET ended_at = ? WHERE channel_id = ? AND ended_at IS NULL", new Date().toISOString(), this.channelId) this.store.audit(this.channelId, this.actor, 'stream', 'Stream ended') await this.alert('offline', {}, true) await this.modules.onLive(false) } publish(this.channelId, { type: 'live', live: this.liveSnapshot() }) } /** Title/activity changes pushed over the websocket between polls. */ async onLivestreamFrame(view: LivestreamView) { if (!this.live.isLive || view.record.endedAt) return await this.updateLive(view) } setViewers(n: number) { this.live.viewers = n } liveSnapshot() { return { ...this.live, streamUri: this.streamUri, connected: this.socketConnected } } // --- chat pipeline ---------------------------------------------------------- /** Messages replayed on connect: remembered for history, never acted on. */ rememberHistory(msg: IncomingMessage) { this.pushRecent(msg) } private pushRecent(msg: IncomingMessage) { this.recent.push({ did: msg.user.did, text: msg.text, at: Date.parse(msg.createdAt) || Date.now(), uri: msg.uri, handle: msg.user.handle, replyRoot: msg.replyRoot?.uri ?? null, hidden: false }) if (this.recent.length > HISTORY) this.recent.splice(0, this.recent.length - HISTORY) } private persistMessage(msg: IncomingMessage) { this.store.db.run( 'INSERT OR IGNORE INTO chat_messages (uri, channel_id, author_did, author_handle, author_name, text, reply_root, badges, color, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', msg.uri, this.channelId, msg.user.did, msg.user.handle, msg.user.displayName, msg.text, msg.replyRoot?.uri ?? null, JSON.stringify(msg.user.badges), msg.color, msg.createdAt, ) const entry: ChatEntry = { uri: msg.uri, did: msg.user.did, handle: msg.user.handle, displayName: msg.user.displayName, text: msg.text, badges: msg.user.badges, color: msg.color, createdAt: msg.createdAt, isBot: msg.isBot, hidden: false, } publish(this.channelId, { type: 'chat', message: entry }) void this.modules.integrations.webhook('chat', entry) } /** Record the chatter; returns true the first time they've ever chatted here. */ private trackChatter(msg: IncomingMessage): boolean { const nowIso = new Date().toISOString() const existing = this.store.db.get<{ did: string }>('SELECT did FROM chatters WHERE channel_id = ? AND did = ?', this.channelId, msg.user.did) this.store.db.run( `INSERT INTO chatters (channel_id, did, handle, display_name, first_seen, last_seen, messages) VALUES (?, ?, ?, ?, ?, ?, 1) ON CONFLICT(channel_id, did) DO UPDATE SET handle = excluded.handle, display_name = excluded.display_name, last_seen = excluded.last_seen, messages = messages + 1`, this.channelId, msg.user.did, msg.user.handle, msg.user.displayName, nowIso, nowIso, ) this.chatterSeen.set(msg.user.did, { info: { did: msg.user.did, handle: msg.user.handle, displayName: msg.user.displayName }, at: Date.now() }) return !existing } async rolesFor(user: ChatUser, exec?: Exec): Promise { await this.refreshModerators() const forced = exec?.forceFollower return resolveRoles(user, this.cfg.roles, { channelDid: this.channelId, moderators: this.moderators, isFollower: forced !== undefined ? async () => forced : async (did) => !!(await getFollow(did, this.channelId)), }) } private async refreshModerators() { if (Date.now() - this.moderatorsLoadedAt < 5 * 60_000) return this.moderatorsLoadedAt = Date.now() try { const { records } = await listRecords<{ moderator: string; permissions: string[]; expirationTime?: string }>(this.channelId, 'place.stream.moderation.permission', 100) this.moderators = new Set(records.filter((r) => !r.value.expirationTime || Date.parse(r.value.expirationTime) > Date.now()).map((r) => r.value.moderator)) } catch {} } isModerator(did: string) { return this.moderators.has(did) } /** The full pipeline for a live chat message. */ async onMessage(msg: IncomingMessage, exec = new Exec(false)): Promise { const botDid = this.platform.botDid() if (!exec.dryRun) { this.persistMessage(msg) if (msg.user.did === botDid) { this.pushRecent(msg) return exec } } if (msg.isBot && this.settings.ignoreOtherBots) { exec.log('skip', 'Ignored a message from another bot') if (!exec.dryRun) this.pushRecent(msg) return exec } const roles = await this.rolesFor(msg.user, exec) exec.log('info', 'Roles', this.describeRoles(roles)) let firstTime = false if (!exec.dryRun) firstTime = this.trackChatter(msg) // Moderation runs before anything else and stops the pipeline when it acts. const verdict = this.moderate(msg, roles, exec) if (!exec.dryRun) this.pushRecent(msg) if (verdict) { await this.punish(verdict, msg, exec) return exec } if (!exec.dryRun) { for (const t of this.timerState.values()) t.lines++ this.modules.onActivity(msg, roles) } if (firstTime && this.settings.firstChatter.enabled) { await this.respond(exec, this.settings.firstChatter.message, 'say', msg, { counterKey: null }) } const handled = (await this.handleCommand(msg, roles, exec)) || (await this.handleKeywords(msg, roles, exec)) if (!handled) exec.log('info', 'No command or keyword matched') await this.modules.onMessage(msg, roles, exec) return exec } private describeRoles(roles: UserRoles): string { const names = this.cfg.roles.filter((r) => roles.roleIds.has(r.id)).map((r) => r.data.name) return names.join(', ') || 'Everyone' } private moderate(msg: IncomingMessage, roles: UserRoles, exec: Exec): ModVerdict | null { const s = this.settings if (msg.user.did === this.channelId) { exec.log('info', 'Moderation skipped', 'The broadcaster is never moderated') return null } if (s.exemptModerators && roles.platform.has('moderator')) { exec.log('info', 'Moderation skipped', 'Moderators are exempt (Channel settings)') return null } if (roles.permissions.has('chat.bypass_filters')) { exec.log('info', 'Moderation skipped', 'This role can bypass filters') return null } const permit = this.permits.get(msg.user.did) if (permit && permit > Date.now()) { exec.log('info', 'Moderation skipped', 'User has an active !permit') return null } const now = Date.now() const earlier = this.recent.filter((m) => m.uri !== msg.uri && now - m.at < 10 * 60_000) const verdict = evaluateModeration(this.cfg, { text: msg.text, did: msg.user.did, handle: msg.user.handle, displayName: msg.user.displayName, replyRoot: msg.replyRoot?.uri ?? null, facetUris: msg.facetUris, userRecent: earlier.filter((m) => m.did === msg.user.did), channelRecent: earlier, threadReplies: (root) => this.recent.filter((m) => m.replyRoot === root).length, prefix: s.prefix, malwareHosts: getMalwareHosts(), live: this.live, roles, now, }) if (verdict) exec.log('moderation', `${verdict.source === 'blocked_term' ? 'Blocked term' : 'Spam filter'}: ${verdict.name}`, verdict.detail) else exec.log('info', 'Passed all blocked terms and spam filters') return verdict } private countStrikes(did: string, source: string, kind: 'offence' | 'warning', windowSecs: number): number { return ( this.store.db.get<{ n: number }>('SELECT count(*) AS n FROM strikes WHERE channel_id = ? AND did = ? AND source = ? AND kind = ? AND at > ?', this.channelId, did, source, kind, Date.now() - windowSecs * 1000)?.n ?? 0 ) } private addStrike(did: string, source: string, kind: 'offence' | 'warning') { this.store.db.run('INSERT INTO strikes (channel_id, did, source, kind, at) VALUES (?, ?, ?, ?, ?)', this.channelId, did, source, kind, Date.now()) } private async punish(v: ModVerdict, msg: IncomingMessage, exec: Exec) { const p = v.punishment let action: ModAction = p.action const sourceKey = `${v.source}:${v.id}` if (p.warnings.enabled && action !== 'none' && action !== 'warn') { const warned = this.countStrikes(msg.user.did, sourceKey, 'warning', p.warnings.window) if (warned < p.warnings.count) { action = 'warn' if (!exec.dryRun) this.addStrike(msg.user.did, sourceKey, 'warning') } } const prior = this.countStrikes(msg.user.did, sourceKey, 'offence', p.repeatOffenders.window) const reason = p.reason || `${v.source === 'blocked_term' ? 'Blocked term' : v.name} (${v.detail})` const vars = { counterKey: null } if (action !== 'none') await this.act(exec, 'Hide the message', () => this.hideMessage(msg.uri)) let summary: string switch (action) { case 'none': summary = 'logged' break case 'delete': summary = 'deleted message' break case 'warn': summary = 'warned' await this.respond(exec, p.warnings.enabled ? p.warnings.message : `@$(sendername), ${reason} [warning]`, 'say', msg, vars) break case 'timeout': { const secs = escalatedTimeout(p, prior) summary = `timed out for ${formatSeconds(secs)}${prior && p.repeatOffenders.enabled ? ` (offence #${prior + 1})` : ''}` await this.act(exec, `Time out @${msg.user.handle} for ${formatSeconds(secs)}`, () => this.timeout(msg.user, secs, reason, sourceKey)) break } case 'ban': summary = 'banned' await this.act(exec, `Ban @${msg.user.handle}`, () => this.ban(msg.user, reason, sourceKey)) break } if (!exec.dryRun) this.addStrike(msg.user.did, sourceKey, 'offence') if (p.notify && (action === 'delete' || action === 'timeout' || action === 'ban')) { const tag = action === 'delete' ? 'deleted' : action === 'timeout' ? 'timeout' : 'ban' await this.respond(exec, `@$(sendername), ${reason} [${tag}]`, 'say', msg, vars) } if (p.announcement.enabled && p.announcement.message) await this.respond(exec, p.announcement.message, 'say', msg, vars) if (!exec.dryRun) { this.store.audit(this.channelId, this.actor, 'moderation', `@${msg.user.handle} ${summary} by ${v.source === 'blocked_term' ? 'blocked term' : 'spam filter'} “${v.name}”`, { message: msg.text.slice(0, 300), detail: v.detail, did: msg.user.did, }) void this.modules.integrations.webhook('moderation', { user: msg.user.handle, did: msg.user.did, action, rule: v.name, detail: v.detail }) } } /** Run a side effect, or just describe it in dry-run mode. Failures are logged, not thrown. */ async act(exec: Exec, label: string, fn: () => Promise): Promise { exec.log('action', label) if (exec.dryRun) return true try { await fn() return true } catch (err) { const message = err instanceof Error ? err.message : String(err) console.warn(`[${this.channel.handle}] ${label} failed:`, message) this.store.audit(this.channelId, this.actor, 'error', `${label} failed: ${message}`) return false } } async hideMessage(uri: string) { await this.platform.hide(this.channelId, uri) this.store.db.run('UPDATE chat_messages SET hidden = 1 WHERE uri = ?', uri) const r = this.recent.find((m) => m.uri === uri) if (r) r.hidden = true publish(this.channelId, { type: 'hidden', uri }) } /** Time someone out: block now, unblock when it expires. Extends an active timeout instead of stacking. */ async timeout(user: { did: string; handle: string }, secs: number, reason: string, source = 'manual') { if (user.did === this.channelId) throw new Error('You can’t time out the broadcaster.') const active = this.store.db.get<{ id: number; kind: string; expires_at: number | null }>( 'SELECT id, kind, expires_at FROM punishments WHERE channel_id = ? AND did = ? AND lifted_at IS NULL ORDER BY id DESC LIMIT 1', this.channelId, user.did, ) const expires = Date.now() + secs * 1000 if (active) { if (active.kind === 'ban') return if ((active.expires_at ?? 0) < expires) this.store.db.run('UPDATE punishments SET expires_at = ?, reason = ? WHERE id = ?', expires, reason, active.id) return } const blockUri = await this.platform.block(this.channelId, user.did) this.store.db.run( 'INSERT INTO punishments (channel_id, did, handle, kind, block_uri, reason, source, expires_at, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)', this.channelId, user.did, user.handle, 'timeout', blockUri, reason, source, expires, Date.now(), ) } async ban(user: { did: string; handle: string }, reason: string, source = 'manual') { if (user.did === this.channelId) throw new Error('You can’t ban the broadcaster.') const active = this.store.db.get<{ id: number; kind: string }>('SELECT id, kind FROM punishments WHERE channel_id = ? AND did = ? AND lifted_at IS NULL ORDER BY id DESC LIMIT 1', this.channelId, user.did) if (active) { this.store.db.run("UPDATE punishments SET kind = 'ban', expires_at = NULL, reason = ? WHERE id = ?", reason, active.id) return } const blockUri = await this.platform.block(this.channelId, user.did) this.store.db.run( 'INSERT INTO punishments (channel_id, did, handle, kind, block_uri, reason, source, expires_at, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, NULL, ?)', this.channelId, user.did, user.handle, 'ban', blockUri, reason, source, Date.now(), ) } /** Lift every active ban or timeout on someone, including blocks made outside the bot. */ async unban(did: string): Promise { const rows = this.store.db.all<{ id: number; block_uri: string | null }>('SELECT id, block_uri FROM punishments WHERE channel_id = ? AND did = ? AND lifted_at IS NULL', this.channelId, did) const uris = new Set(rows.map((r) => r.block_uri).filter((u): u is string => !!u)) for (const uri of await this.platform.findBlocks(this.channelId, did).catch(() => [])) uris.add(uri) for (const uri of uris) await this.platform.unblock(this.channelId, uri).catch(() => {}) this.store.db.run('UPDATE punishments SET lifted_at = ? WHERE channel_id = ? AND did = ? AND lifted_at IS NULL', Date.now(), this.channelId, did) return uris.size } // --- commands & keywords ------------------------------------------------------ cooldownLeft(key: string): number { return Math.max(0, (this.cooldowns.get(key) ?? 0) - Date.now()) } /** True if allowed to run now (and starts the cooldowns), false if on cooldown. */ takeCooldown(exec: Exec, key: string, user: ChatUser, roles: UserRoles, global: number, perUser: number): boolean { if (exec.dryRun) return true const bypass = roles.permissions.has('chat.bypass_cooldowns') || (this.settings.modsBypassCooldowns && (roles.platform.has('moderator') || roles.platform.has('broadcaster'))) if (!bypass) { if (this.cooldownLeft(`${key}`) > 0 || this.cooldownLeft(`${key}:${user.did}`) > 0) return false } if (global) this.cooldowns.set(key, Date.now() + global * 1000) if (perUser) this.cooldowns.set(`${key}:${user.did}`, Date.now() + perUser * 1000) if (this.cooldowns.size > 5000) for (const [k, t] of this.cooldowns) if (t < Date.now()) this.cooldowns.delete(k) return true } private expired(expiry: { mode: string; at: string | null }) { return expiry.mode !== 'none' && !!expiry.at && Date.parse(expiry.at) <= Date.now() } parseTrigger(text: string): { name: string; args: string[] } | null { const prefix = this.settings.prefix const t = text.trim() if (!t.startsWith(prefix)) return null const [first, ...args] = splitArgs(t.slice(prefix.length)) if (!first) return null return { name: first.toLowerCase(), args } } private async handleCommand(msg: IncomingMessage, roles: UserRoles, exec: Exec): Promise { const trigger = this.parseTrigger(msg.text) if (trigger) { const custom = this.cfg.commandsByTrigger.get(trigger.name) if (custom && custom.data.enabled && !this.expired(custom.data.expiry)) { return this.runCustomCommand(custom, msg, roles, trigger.args, exec) } const def = this.cfg.defaultsByTrigger.get(trigger.name) if (def && def.override.enabled) { const why = checkConditions(def.override.conditions, roles, this.live) if (why) { exec.log('skip', `Default command !${def.name}`, why) return true } if (def.def.permission && !roles.permissions.has(def.def.permission)) { exec.log('skip', `Default command !${def.name}`, 'missing permission') return true } if (!this.takeCooldown(exec, `default:${def.def.id}`, msg.user, roles, def.override.globalCooldown, def.override.userCooldown)) { exec.log('skip', `Default command !${def.name}`, 'on cooldown') return true } exec.log('command', `Default command !${def.name}`) await runDefaultCommand(this, def, msg, roles, trigger.args, exec) return true } } for (const { doc, matchers } of this.cfg.commandKeywords) { if (!doc.data.enabled || this.expired(doc.data.expiry)) continue const normalized = this.cfg.normalize(msg.text) if (matchers.some((m) => m(normalized))) return this.runCustomCommand(doc, msg, roles, splitArgs(msg.text), exec) } return false } private async runCustomCommand(cmd: Doc<'command'>, msg: IncomingMessage, roles: UserRoles, args: string[], exec: Exec): Promise { const c = cmd.data const why = checkConditions(c.conditions, roles, this.live) if (why) { exec.log('skip', `Command !${c.name}`, why) return true } if (!this.takeCooldown(exec, `cmd:${cmd.id}`, msg.user, roles, c.globalCooldown, c.userCooldown)) { exec.log('skip', `Command !${c.name}`, 'on cooldown') return true } exec.log('command', `Command !${c.name}`) if (!exec.dryRun) void this.modules.integrations.webhook('command', { command: c.name, user: msg.user.handle, args }) await this.respond(exec, c.response, c.responseType, msg, { args, counterKey: `cmd:${cmd.id}` }) return true } private async handleKeywords(msg: IncomingMessage, roles: UserRoles, exec: Exec): Promise { const name = this.cfg.normalize([msg.user.handle, msg.user.displayName].join(' ')) const text = this.cfg.normalize(msg.text) for (const { doc, groups } of this.cfg.keywords) { const k = doc.data if (!k.enabled || this.expired(k.expiry)) continue const texts = k.targeting === 'message' ? [text] : k.targeting === 'username' ? [name] : [text, name] const hit = groups.some((g) => texts.some((t) => g.every((m) => m(t)))) if (!hit) continue const why = checkConditions(k.conditions, roles, this.live) if (why) { exec.log('skip', `Keyword “${k.name}”`, why) continue } if (!this.takeCooldown(exec, `kw:${doc.id}`, msg.user, roles, k.globalCooldown, k.userCooldown)) { exec.log('skip', `Keyword “${k.name}”`, 'on cooldown') return true } exec.log('keyword', `Keyword “${k.name}”`) await this.respond(exec, k.response, k.responseType, msg, { args: splitArgs(msg.text), counterKey: `kw:${doc.id}` }) return true } return false } // --- rendering & sending --------------------------------------------------------- services(): VarServices { const rt = this return { channel: this.channelInfo(), live: this.live, publicUrl: env.publicUrl, timezone: this.settings.timezone, botStartedAt: this.startedAt, profile: async (actor) => toUserInfo(await getProfile(actor)), follow: (did) => getFollow(did, this.channelId), counterAdd: (name, delta) => this.store.counterAdd(this.channelId, name, delta), counterGet: (name) => this.store.counterGet(this.channelId, name), counterSet: (name, value) => this.store.counterSet(this.channelId, name, value), quote: (n) => { const quotes = this.store.listDocs(this.channelId, 'quote') if (!quotes.length) return 'none' const q = n === null ? quotes[Math.floor(Math.random() * quotes.length)] : quotes.find((x) => x.data.number === n) return q ? { number: q.data.number, text: q.data.text } : null }, commandResponse: (name) => this.cfg.commandsByTrigger.get(name)?.data.response, eightBall: () => { const answers = this.cfg.get('modules.eightball').answers return answers[Math.floor(Math.random() * answers.length)] ?? 'Ask again later.' }, chatters: () => [...this.chatterSeen.values()].filter((c) => Date.now() - c.at < 10 * 60_000).map((c) => c.info), watchtime: (did) => { if (!this.cfg.get('loyalty').enabled) return null const row = this.store.db.get<{ time_online: number; time_offline: number }>('SELECT time_online, time_offline FROM chatters WHERE channel_id = ? AND did = ?', this.channelId, did) return { online: row?.time_online ?? 0, offline: row?.time_offline ?? 0 } }, currentSong: () => this.modules.media.currentLabel(), setTitle: (title) => rt.setStream({ title }), setActivity: async (query) => (await rt.setActivityByName(query)).name, fetchText: (url) => fetchPublicText(url), lastfm: (user) => lastfmNowPlaying(user), tealfm: (actor) => tealfmNowPlaying(actor), musicSettings: () => { const lastfm = this.cfg.get('integrations.lastfm') const tealfm = this.cfg.get('integrations.tealfm') return { lastfm: { enabled: lastfm.enabled, account: lastfm.username }, tealfm: { enabled: tealfm.enabled, account: tealfm.handle.trim() || this.channel.handle }, } }, weather: (loc) => weather(loc), latestPost: async (actor) => (await latestPost(actor))?.url ?? null, } } varContext(msg: IncomingMessage | null, extra: Partial = {}): VarContext { return { services: this.services(), sender: msg ? { did: msg.user.did, handle: msg.user.handle, displayName: msg.user.displayName } : null, message: msg?.text ?? '', messageUri: msg?.uri ?? null, args: [], counterKey: null, inTimer: false, dryRun: false, ...extra, } } render(template: string, msg: IncomingMessage | null, extra: Partial = {}): Promise { return renderWith(template, this.varContext(msg, extra)) } /** Render a response and deliver it. Responses starting with /timeout, /ban, /unban, /delete or /pin perform that action. */ async respond(exec: Exec, template: string, type: ResponseType, msg: IncomingMessage | null, extra: Partial = {}) { if (!template.trim()) return const text = (await this.render(template, msg, { ...extra, dryRun: exec.dryRun })).trim() if (!text) return if (text.startsWith('/') && (await this.runSlashAction(text, msg, exec))) return let out = text if (type === 'mention' && msg) out = `@${msg.user.handle} ${text}` const reply: ReplyTarget | undefined = type === 'reply' && msg && !msg.synthetic ? { parent: { uri: msg.uri, cid: msg.cid }, root: msg.replyRoot ?? { uri: msg.uri, cid: msg.cid } } : undefined await this.say(exec, out, reply, type === 'pin') } private async runSlashAction(text: string, msg: IncomingMessage | null, exec: Exec): Promise { const [cmd, target, ...rest] = text.split(/\s+/) const resolveTarget = async () => { const p = await getProfile((target ?? '').replace(/^@/, '')) if (!p) throw new Error(`Couldn’t find user “${target}”.`) return { did: p.did, handle: p.handle } } switch (cmd.toLowerCase()) { case '/timeout': { const secs = Math.max(1, Math.min(Number(rest[0]) || 600, 14 * 86400)) const reason = rest.slice(1).join(' ') await this.act(exec, `Time out ${target} for ${formatSeconds(secs)}`, async () => { const u = await resolveTarget() if (msg && u.did === msg.user.did) await this.hideMessage(msg.uri).catch(() => {}) await this.timeout(u, secs, reason, 'response') this.store.audit(this.channelId, this.actor, 'moderation', `@${u.handle} timed out for ${formatSeconds(secs)} by a response`, { reason }) }) return true } case '/ban': { const reason = rest.join(' ') await this.act(exec, `Ban ${target}`, async () => { const u = await resolveTarget() if (msg && u.did === msg.user.did) await this.hideMessage(msg.uri).catch(() => {}) await this.ban(u, reason, 'response') this.store.audit(this.channelId, this.actor, 'moderation', `@${u.handle} banned by a response`, { reason }) }) return true } case '/unban': case '/untimeout': await this.act(exec, `Unban ${target}`, async () => { const u = await resolveTarget() await this.unban(u.did) }) return true case '/delete': if (msg && !msg.synthetic) await this.act(exec, 'Hide the message', () => this.hideMessage(msg.uri)) return true case '/pin': if (msg && !msg.synthetic) await this.act(exec, 'Pin the message', () => this.platform.pin(this.channelId, msg.uri)) return true default: return false } } /** Queue a chat message from the bot, respecting the channel's send gap. */ async say(exec: Exec, text: string, reply?: ReplyTarget, pin = false): Promise { exec.log('send', reply ? 'Reply' : pin ? 'Send and pin' : 'Send', text) if (exec.dryRun) return if (this.channel.bot_muted) return if (!this.platform.canSend()) return const chunks = chunkMessage(text, 300).slice(0, 3) const job = this.sendChain.then(async () => { for (const chunk of chunks) { const wait = this.lastSendAt + this.settings.messageGapMs - Date.now() if (wait > 0) await new Promise((r) => setTimeout(r, wait)) this.lastSendAt = Date.now() try { const ref = await this.platform.send(this.channelId, chunk, reply) if (pin) await this.platform.pin(this.channelId, ref.uri).catch(() => {}) } catch (err) { console.warn(`[${this.channel.handle}] send failed:`, err instanceof Error ? err.message : err) } } }) this.sendChain = job.catch(() => {}) await job } /** Send a plain message (dashboard, alerts, timers). */ sendText(text: string) { return this.say(new Exec(false), text) } // --- alerts --------------------------------------------------------------------- async alert(key: AlertKey, vars: { user?: UserInfo; viewers?: number }, force = false) { const a = this.cfg.alerts[key] await this.modules.integrations.onAlert(key, vars) if (!a.enabled) return if (a.onlineOnly && !this.live.isLive && !force) return let template = a.message if (vars.viewers !== undefined) template = template.replace(/\$\(viewers\)/g, String(vars.viewers)) const ctx: Partial = { inTimer: false } const fakeMsg = vars.user ? ({ uri: '', cid: '', text: '', createdAt: '', replyRoot: null, replyParent: null, facetUris: [], user: { ...vars.user, badges: [] }, color: null, isBot: false } as IncomingMessage) : null const text = await this.render(template, fakeMsg, ctx) await this.sendText(text) } async onFollow(followerDid: string) { const dedupeKey = `followed:${this.channelId}:${followerDid}` if (this.store.kvGet(dedupeKey)) return this.store.kvSet(dedupeKey, 1, 24 * 3600_000) const p = await getProfile(followerDid).catch(() => null) if (!p) return this.store.audit(this.channelId, { did: p.did, handle: p.handle }, 'follow', `@${p.handle} followed the channel`) await this.alert('follow', { user: toUserInfo(p)! }) } async onTeleport(source: { did: string; handle: string; displayName?: string }, viewers: number) { this.store.audit(this.channelId, { did: source.did, handle: source.handle }, 'teleport', `@${source.handle} teleported in with ${viewers} viewers`) await this.alert('teleport', { user: { did: source.did, handle: source.handle, displayName: source.displayName || source.handle }, viewers }) } async onTeleportOut(targetDid: string) { const p = await getProfile(targetDid).catch(() => null) if (!p) return await this.alert('teleportOut', { user: toUserInfo(p)! }, true) } // --- stream controls ------------------------------------------------------------ async setStream(patch: { title?: string; activity?: ActivityRef | null }) { await this.platform.updateStream(this.channelId, patch) if (patch.title !== undefined) this.live.title = patch.title if (patch.activity !== undefined) { this.live.activity = patch.activity this.live.activitySince = Date.now() } publish(this.channelId, { type: 'live', live: this.liveSnapshot() }) } /** Match free text to a Streamplace activity label or a catalog game, then set it. */ async setActivityByName(query: string): Promise { const q = query.trim().toLowerCase() const label = Object.entries(ACTIVITY_LABELS).find(([id, name]) => id === q.replace(/\s+/g, '_') || name.toLowerCase() === q) let activity: ActivityRef | null = label ? { kind: 'label', id: label[0], name: label[1] } : null if (!activity) { const games = await searchGames(query) const exact = games.find((g) => g.name.toLowerCase() === q) ?? games[0] if (!exact) throw new Error(`No game found for “${query}”.`) activity = { kind: 'game', id: exact.uri, name: exact.name } } await this.setStream({ activity }) return activity } // --- timers ----------------------------------------------------------------------- async tickTimers() { const now = Date.now() for (const timer of this.cfg.timers) { const t = timer.data let state = this.timerState.get(timer.id) if (!state) { state = { lastSent: now, lines: 0, index: 0 } this.timerState.set(timer.id, state) continue } if (!t.enabled) continue const interval = this.live.isLive ? (t.onlineEnabled ? t.onlineInterval : null) : t.offlineEnabled ? t.offlineInterval : null if (interval === null) continue if (now - state.lastSent < interval * 60_000) continue if (state.lines < t.minLines) continue if (t.activities.length && !t.activities.some((a) => a.id === this.live.activity?.id)) continue if (t.titleKeywords.length && !t.titleKeywords.some((k) => this.live.title.toLowerCase().includes(k.toLowerCase()))) continue const items = [ ...t.commandIds.map((id) => this.cfg.commands.find((c) => c.id === id)?.data.response).filter((r): r is string => !!r), ...t.messages.filter((m) => m.trim()), ] if (!items.length) continue const template = items[state.index % items.length] state.index++ state.lastSent = now state.lines = 0 const text = await this.render(template, null, { inTimer: true }) await this.sendText(text) } } /** Add 10 minutes of watchtime to everyone who chatted in the last 10 minutes. */ loyaltyTick() { if (!this.cfg.get('loyalty').enabled) return const col = this.live.isLive ? 'time_online' : 'time_offline' const since = new Date(Date.now() - 10 * 60_000).toISOString() this.store.db.run(`UPDATE chatters SET ${col} = ${col} + 600 WHERE channel_id = ? AND last_seen >= ?`, this.channelId, since) } /** * Run a command as the broadcaster without it appearing in chat, e.g. from a Stream Deck button. * Only commands run: no moderation, keywords or modules, and nothing is recorded as chat. */ async runAsBroadcaster(text: string): Promise<{ handled: boolean; steps: TraceStep[] }> { const exec = new Exec(false) const user: ChatUser = { did: this.channelId, handle: this.channel.handle, displayName: this.channel.display_name || this.channel.handle, badges: ['streamer'] } const msg: IncomingMessage = { uri: `at://${this.channelId}/superbot.api/${Date.now()}`, cid: '', text, createdAt: new Date().toISOString(), replyRoot: null, replyParent: null, facetUris: [], user, color: null, isBot: false, synthetic: true, } const roles = await this.rolesFor(user, exec) const handled = await this.handleCommand(msg, roles, exec) if (!handled) exec.log('info', 'No command matched') return { handled, steps: exec.steps } } /** The config tester: run a pretend message through the pipeline without side effects. */ async simulate(input: { text: string; handle: string; displayName?: string; roles: string[] }): Promise { const exec = new Exec(true, input.roles.includes('follower') || input.roles.includes('broadcaster')) const profile = await getProfile(input.handle).catch(() => null) const did = profile?.did ?? `did:example:${input.handle}` const badges: string[] = [] for (const r of input.roles) { if (r === 'broadcaster') badges.push('streamer') if (r === 'moderator') badges.push('mod') if (r === 'vip') badges.push('vip') } const user: ChatUser = { did: input.roles.includes('broadcaster') ? this.channelId : did, handle: profile?.handle ?? input.handle, displayName: input.displayName || profile?.displayName || input.handle, badges } const msg: IncomingMessage = { uri: 'at://simulated/place.stream.chat.message/test', cid: 'simulated', text: input.text, createdAt: new Date().toISOString(), replyRoot: null, replyParent: null, facetUris: [], user, color: null, isBot: false, } await this.onMessage(msg, exec) return exec.steps } } export function toUserInfo(p: Profile | null): UserInfo | null { if (!p) return null return { did: p.did, handle: p.handle, displayName: p.displayName, avatar: p.avatar, description: p.description, createdAt: p.createdAt, followersCount: p.followersCount } } export type { Punishment }