import { formatDuration, formatSeconds } from '../../shared/format.ts' import type { AlertKey } from '../../shared/schemas.ts' import { getProfile, postUrl } from '../atproto/identity.ts' import type { UserRoles } from './engine/roles.ts' import { checkConditions } from './engine/roles.ts' import type { UserInfo } from './engine/variables.ts' import { publish } from './platform.ts' import { canSearchYouTube, lookupMedia } from './services.ts' import type { Exec, ChannelRuntime, IncomingMessage } from './runtime.ts' export interface MediaRow { id: number channel_id: string requester_did: string | null requester_handle: string provider: 'youtube' | 'soundcloud' url: string media_id: string title: string author: string duration: number | null thumbnail: string status: 'pending' | 'queued' | 'playing' | 'played' | 'skipped' | 'removed' position: number from_backup: number created_at: string played_at: string | null } export class MediaModule { private rt: ChannelRuntime private skipVotes = new Map>() constructor(rt: ChannelRuntime) { this.rt = rt } private get db() { return this.rt.store.db } current(): MediaRow | undefined { return this.db.get("SELECT * FROM media_queue WHERE channel_id = ? AND status = 'playing' ORDER BY id DESC LIMIT 1", this.rt.channelId) } currentLabel(): string | null { const c = this.current() return c ? `${c.title}${c.author ? ` by ${c.author}` : ''} (${c.url})${c.requester_handle ? `, requested by @${c.requester_handle}` : ''}` : null } queue(status: 'queued' | 'pending' = 'queued'): MediaRow[] { return this.db.all('SELECT * FROM media_queue WHERE channel_id = ? AND status = ? ORDER BY position, id', this.rt.channelId, status) } history(limit = 50): MediaRow[] { return this.db.all("SELECT * FROM media_queue WHERE channel_id = ? AND status IN ('played', 'skipped') ORDER BY played_at DESC LIMIT ?", this.rt.channelId, limit) } private changed() { publish(this.rt.channelId, { type: 'media' }) } /** Add a request. Returns a chat-ready result message. */ async request(input: string, by: { did: string | null; handle: string }, opts: { bypassLimits: boolean }): Promise { const s = this.rt.cfg.get('media') const info = await lookupMedia(input, s.providers) if (!info) { if (!/^https?:/i.test(input) && !canSearchYouTube()) return 'Please request with a YouTube or SoundCloud link.' return `Couldn’t find anything playable for “${input}”.` } if (!opts.bypassLimits) { if (info.duration && info.duration > s.maxDuration) return `That’s too long (${formatSeconds(info.duration)}). The limit is ${formatSeconds(s.maxDuration)}.` const queued = [...this.queue(), ...this.queue('pending')] if (queued.length >= s.maxQueue) return 'The queue is full right now.' if (by.did && queued.filter((r) => r.requester_did === by.did).length >= s.maxPerUser) return `You already have ${s.maxPerUser} requests in the queue.` if (queued.some((r) => r.media_id === info.mediaId)) return 'That’s already in the queue.' } const status = s.queueModeration && !opts.bypassLimits ? 'pending' : 'queued' this.db.run( 'INSERT INTO media_queue (channel_id, requester_did, requester_handle, provider, url, media_id, title, author, duration, thumbnail, status, position, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', this.rt.channelId, by.did, by.handle, info.provider, info.url, info.mediaId, info.title, info.author, info.duration, info.thumbnail, status, Date.now(), new Date().toISOString(), ) this.changed() if (status === 'pending') return `“${info.title}” is waiting for a moderator to approve it.` const pos = this.queue().length + (this.current() ? 0 : -1) return `Added “${info.title}” to the queue${pos > 0 ? ` at position ${pos}` : ''}.` } /** Finish whatever is playing and start the next track (or one from the backup playlist). */ async next(markAs: 'played' | 'skipped' = 'played'): Promise { const cur = this.current() if (cur) this.db.run('UPDATE media_queue SET status = ?, played_at = ? WHERE id = ?', markAs, new Date().toISOString(), cur.id) const up = this.queue()[0] if (up) { this.db.run("UPDATE media_queue SET status = 'playing', played_at = ? WHERE id = ?", new Date().toISOString(), up.id) } else { const backup = this.rt.cfg.get('media').backupPlaylist if (backup.length) { const pick = backup[Math.floor(Math.random() * backup.length)] const info = await lookupMedia(pick, ['youtube', 'soundcloud']).catch(() => null) if (info) { this.db.run( "INSERT INTO media_queue (channel_id, requester_did, requester_handle, provider, url, media_id, title, author, duration, thumbnail, status, position, from_backup, created_at, played_at) VALUES (?, NULL, '', ?, ?, ?, ?, ?, ?, ?, 'playing', 0, 1, ?, ?)", this.rt.channelId, info.provider, info.url, info.mediaId, info.title, info.author, info.duration, info.thumbnail, new Date().toISOString(), new Date().toISOString(), ) } } } this.skipVotes.clear() this.changed() return this.current() } setStatus(id: number, status: 'queued' | 'removed') { this.db.run('UPDATE media_queue SET status = ? WHERE id = ? AND channel_id = ?', status, id, this.rt.channelId) this.changed() } moveToTop(id: number) { const first = this.queue()[0] this.db.run('UPDATE media_queue SET position = ? WHERE id = ? AND channel_id = ?', (first?.position ?? Date.now()) - 1, id, this.rt.channelId) this.changed() } clear() { this.db.run("UPDATE media_queue SET status = 'removed' WHERE channel_id = ? AND status IN ('queued', 'pending')", this.rt.channelId) this.changed() } setVolume(volume: number) { const s = this.rt.cfg.get('media') this.rt.store.setSingleton(this.rt.channelId, 'media', { ...s, volume: Math.max(0, Math.min(100, Math.round(volume))) }) this.changed() } async chatCommand(id: string, msg: IncomingMessage, roles: UserRoles, args: string[], exec: Exec): Promise { const s = this.rt.cfg.get('media') switch (id) { case 'songrequest': { if (!s.allowRequests) return 'Media requests are turned off right now.' if (!args.length) return `Usage: ${this.rt.settings.prefix}sr ` if (checkConditions(s.conditions, roles, this.rt.live)) return 'You can’t request media right now.' if (exec.dryRun) return '(would add the request to the queue)' return this.request(args.join(' '), { did: msg.user.did, handle: msg.user.handle }, { bypassLimits: false }) } case 'wrongsong': { const mine = [...this.queue(), ...this.queue('pending')].filter((r) => r.requester_did === msg.user.did).pop() if (!mine) return 'You don’t have anything in the queue.' if (!exec.dryRun) this.setStatus(mine.id, 'removed') return `Removed “${mine.title}” from the queue.` } case 'songrequestskip': if (!this.current()) return 'Nothing is playing right now.' if (!exec.dryRun) await this.next('skipped') return 'Skipped.' case 'songvoteskip': { const cur = this.current() if (!cur) return 'Nothing is playing right now.' const votes = this.skipVotes.get(cur.id) ?? new Set() votes.add(msg.user.did) this.skipVotes.set(cur.id, votes) const chatters = this.rt.services().chatters().length const needed = Math.max(s.voteSkipMinimum, Math.ceil((chatters * s.voteSkipPercent) / 100)) if (votes.size >= needed) { if (!exec.dryRun) await this.next('skipped') return `Vote passed (${votes.size}/${needed}). Skipped “${cur.title}”.` } return `Vote to skip: ${votes.size}/${needed}.` } case 'songrequestclear': if (!exec.dryRun) this.clear() return 'Cleared the queue.' case 'songvolume': { if (!args.length) return `The volume is ${s.volume}.` const v = Number(args[0]) if (Number.isNaN(v) || v < 0 || v > 100) return `Usage: ${this.rt.settings.prefix}volume <0-100>` if (!exec.dryRun) this.setVolume(v) return `Set the volume to ${Math.round(v)}.` } } return null } } interface ActiveVote { target: { did: string; handle: string } yea: Set nay: Set timer: NodeJS.Timeout } export class VoteKick { private rt: ChannelRuntime private active: ActiveVote | null = null private lastEnded = 0 constructor(rt: ChannelRuntime) { this.rt = rt } private vars(template: string, v: ActiveVote) { const s = this.rt.cfg.get('modules.votekick') return template .replace(/\$\(target\)/g, `@${v.target.handle}`) .replace(/\$\(command\)/g, 'VoteYea') .replace(/\$\(votes\)/g, String(v.yea.size)) .replace(/\$\(required\)/g, String(s.votesRequired)) .replace(/\$\(duration\)/g, formatSeconds(s.timeout)) } async start(msg: IncomingMessage, roles: UserRoles, args: string[], exec: Exec) { const s = this.rt.cfg.get('modules.votekick') if (!s.enabled) return if (this.active) return this.rt.respond(exec, `A vote kick for @${this.active.target.handle} is already running. Type VoteYea or VoteNay.`, 'say', msg) if (Date.now() - this.lastEnded < s.cooldown * 1000) return const who = args[0]?.replace(/^@/, '') if (!who) return this.rt.respond(exec, `Usage: ${this.rt.settings.prefix}votekick `, 'reply', msg) const p = await getProfile(who) if (!p) return this.rt.respond(exec, '[Error: User not found.]', 'reply', msg) if (p.did === this.rt.channelId || this.rt.isModerator(p.did) || p.did === this.rt.platform.botDid()) { return this.rt.respond(exec, 'You can’t vote kick that person.', 'reply', msg) } if (exec.dryRun) { exec.log('module', 'Vote kick', `would start a vote against @${p.handle}`) return } const vote: ActiveVote = { target: { did: p.did, handle: p.handle }, yea: new Set([msg.user.did]), nay: new Set(), timer: setTimeout(() => void this.finish(false), s.duration * 1000), } this.active = vote await this.rt.respond(exec, this.vars(s.startMessage, vote), 'say', msg) await this.check() } onMessage(msg: IncomingMessage) { if (!this.active) return const t = msg.text.trim().toLowerCase() if (t === 'voteyea' || t === 'vote yea' || t === 'yea') { this.active.nay.delete(msg.user.did) this.active.yea.add(msg.user.did) } else if (t === 'votenay' || t === 'vote nay' || t === 'nay') { this.active.yea.delete(msg.user.did) this.active.nay.add(msg.user.did) } else return void this.check() } private async check() { const s = this.rt.cfg.get('modules.votekick') if (this.active && this.active.yea.size >= s.votesRequired) await this.finish(true) } private async finish(passed: boolean) { const v = this.active if (!v) return clearTimeout(v.timer) this.active = null this.lastEnded = Date.now() const s = this.rt.cfg.get('modules.votekick') if (passed) { await this.rt.timeout(v.target, s.timeout, 'Vote kicked by chat', 'votekick').catch(() => {}) this.rt.store.audit(this.rt.channelId, this.rt.actor, 'moderation', `@${v.target.handle} was vote kicked (${v.yea.size} votes)`) } await this.rt.sendText(await this.rt.render(this.vars(passed ? s.passMessage : s.failMessage, v), null)) } } export interface GiveawayEntry { did: string handle: string display_name: string weight: number entered_at: string last_active: string } export class GiveawayModule { private rt: ChannelRuntime constructor(rt: ChannelRuntime) { this.rt = rt } private weightFor(roles: UserRoles): number { const luck = this.rt.cfg.get('giveaway').luck return Math.max(1, ...luck.filter((l) => roles.roleIds.has(l.roleId)).map((l) => l.multiplier)) } private upsert(msg: IncomingMessage, roles: UserRoles) { const now = new Date().toISOString() this.rt.store.db.run( `INSERT INTO giveaway_entries (channel_id, did, handle, display_name, weight, entered_at, last_active) VALUES (?, ?, ?, ?, ?, ?, ?) ON CONFLICT(channel_id, did) DO UPDATE SET last_active = excluded.last_active, weight = excluded.weight`, this.rt.channelId, msg.user.did, msg.user.handle, msg.user.displayName, this.weightFor(roles), now, now, ) publish(this.rt.channelId, { type: 'giveaway' }) } onActivity(msg: IncomingMessage, roles: UserRoles) { const g = this.rt.cfg.get('giveaway') if (!g.running) return if (msg.user.did === this.rt.channelId) return if (g.type === 'active') this.upsert(msg, roles) else if (msg.text.trim().toLowerCase() === g.keyword.trim().toLowerCase()) this.upsert(msg, roles) else this.rt.store.db.run('UPDATE giveaway_entries SET last_active = ? WHERE channel_id = ? AND did = ?', new Date().toISOString(), this.rt.channelId, msg.user.did) } entries(): GiveawayEntry[] { const g = this.rt.cfg.get('giveaway') const rows = this.rt.store.db.all('SELECT * FROM giveaway_entries WHERE channel_id = ? ORDER BY entered_at', this.rt.channelId) if (!g.inactivityTimeout) return rows const cutoff = Date.now() - g.inactivityTimeout * 1000 return rows.filter((r) => Date.parse(r.last_active) >= cutoff) } reset() { this.rt.store.db.run('DELETE FROM giveaway_entries WHERE channel_id = ?', this.rt.channelId) publish(this.rt.channelId, { type: 'giveaway' }) } remove(did: string) { this.rt.store.db.run('DELETE FROM giveaway_entries WHERE channel_id = ? AND did = ?', this.rt.channelId, did) publish(this.rt.channelId, { type: 'giveaway' }) } async draw(): Promise<{ winner: GiveawayEntry; messages: { text: string; created_at: string }[] } | null> { const pool = this.entries() if (!pool.length) return null const total = pool.reduce((n, e) => n + e.weight, 0) let r = Math.random() * total let winner = pool[pool.length - 1] for (const e of pool) { r -= e.weight if (r <= 0) { winner = e break } } const g = this.rt.cfg.get('giveaway') if (g.announce) await this.rt.sendText(`🎉 Congratulations @${winner.handle}, you won the giveaway!`) this.rt.store.audit(this.rt.channelId, this.rt.actor, 'giveaway', `@${winner.handle} won the giveaway (${pool.length} entries)`) const messages = this.rt.store.db.all<{ text: string; created_at: string }>( 'SELECT text, created_at FROM chat_messages WHERE channel_id = ? AND author_did = ? ORDER BY created_at DESC LIMIT 20', this.rt.channelId, winner.did, ) return { winner, messages } } } export class Integrations { private rt: ChannelRuntime constructor(rt: ChannelRuntime) { this.rt = rt } async onAlert(key: AlertKey, vars: { user?: UserInfo; viewers?: number }) { const discord = this.rt.cfg.get('integrations.discord') if (discord.enabled && discord.webhookUrl && (key === 'live' || (key === 'offline' && discord.sendOffline))) { const template = (key === 'live' ? discord.liveMessage : discord.offlineMessage).replace(/\$\(url\)/g, `https://stream.place/${this.rt.channel.handle}`) const text = await this.rt.render(template, null) await fetch(discord.webhookUrl, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ content: `${discord.mention ? `${discord.mention} ` : ''}${text}`.slice(0, 2000), allowed_mentions: { parse: ['roles', 'everyone', 'users'] } }), signal: AbortSignal.timeout(8000), }).catch((err) => this.rt.store.audit(this.rt.channelId, this.rt.actor, 'error', `Discord notification failed: ${err.message}`)) } await this.webhook('alert', { alert: key, user: vars.user?.handle, viewers: vars.viewers }) } async webhook(event: 'chat' | 'command' | 'moderation' | 'alert', data: unknown) { const w = this.rt.cfg.get('integrations.webhook') if (!w.enabled || !w.url || !w.events.includes(event)) return await fetch(w.url, { method: 'POST', headers: { 'content-type': 'application/json', 'user-agent': 'superbot' }, body: JSON.stringify({ event, channel: { did: this.rt.channelId, handle: this.rt.channel.handle }, data, at: new Date().toISOString() }), signal: AbortSignal.timeout(8000), }).catch(() => {}) } } /** Optional chat features plus the dashboard-driven ones (media, giveaways). */ export class Modules { readonly media: MediaModule readonly votekick: VoteKick readonly giveaway: GiveawayModule readonly integrations: Integrations private rt: ChannelRuntime private combo: { token: string; users: Set } | null = null private pyramid: { did: string; handle: string; token: string; widths: number[] } | null = null constructor(rt: ChannelRuntime) { this.rt = rt this.media = new MediaModule(rt) this.votekick = new VoteKick(rt) this.giveaway = new GiveawayModule(rt) this.integrations = new Integrations(rt) } onActivity(msg: IncomingMessage, roles: UserRoles) { this.giveaway.onActivity(msg, roles) } async onLive(_isLive: boolean) { this.combo = null this.pyramid = null } async onMessage(msg: IncomingMessage, _roles: UserRoles, exec: Exec) { if (exec.dryRun) return this.votekick.onMessage(msg) await this.checkCombo(msg) await this.checkPyramid(msg) } /** Same single emoji/word from several different people in a row; announced when it breaks. */ private async checkCombo(msg: IncomingMessage) { const s = this.rt.cfg.get('modules.combo') if (!s.enabled) return const words = msg.text.trim().split(/\s+/) const token = words.length === 1 && [...words[0]].length <= 25 ? words[0] : null if (this.combo && token === this.combo.token) { this.combo.users.add(msg.user.did) return } const ended = this.combo this.combo = token ? { token, users: new Set([msg.user.did]) } : null if (ended && ended.users.size >= s.minCombo && (!s.onlineOnly || this.rt.live.isLive)) { await this.rt.sendText(s.message.replace(/\$\(count\)/g, String(ended.users.size)).replace(/\$\(emote\)/g, ended.token)) } } /** One person building 1, 2, …, n, …, 2, 1 copies of the same token, uninterrupted. */ private async checkPyramid(msg: IncomingMessage) { const s = this.rt.cfg.get('modules.pyramid') if (!s.enabled) return const words = msg.text.trim().split(/\s+/) const token = words[0] const uniform = words.every((w) => w === token) const p = this.pyramid if (!uniform || !p || p.did !== msg.user.did || p.token !== token) { this.pyramid = uniform && words.length === 1 ? { did: msg.user.did, handle: msg.user.handle, token, widths: [1] } : null return } const w = words.length const last = p.widths[p.widths.length - 1] const peak = Math.max(...p.widths) const climbing = last === peak && p.widths.every((x, i) => i === 0 || x === p.widths[i - 1] + 1) if ((climbing && (w === last + 1 || w === last - 1)) || (!climbing && w === last - 1)) { p.widths.push(w) if (w === 1 && peak >= s.minWidth) { this.pyramid = null if (!s.onlineOnly || this.rt.live.isLive) { await this.rt.sendText(s.message.replace(/\$\(user\)/g, `@${p.handle}`).replace(/\$\(width\)/g, String(peak)).replace(/\$\(emote\)/g, token)) } } return } this.pyramid = w === 1 ? { did: msg.user.did, handle: msg.user.handle, token, widths: [1] } : null } async onBskyPost(authorDid: string, uri: string, record: { text?: string; reply?: unknown }) { const s = this.rt.cfg.get('modules.bskyposts') if (!s.enabled) return const account = s.accounts.find((a) => a.did === authorDid) if (!account) return if (record.reply && !s.includeReplies) return if (s.onlineOnly && !this.rt.live.isLive) return const handle = (await getProfile(authorDid).catch(() => null))?.handle ?? account.handle const text = s.message .replace(/\$\(author\)/g, `@${handle}`) .replace(/\$\(link\)/g, postUrl(uri, handle)) .replace(/\$\(text\)/g, (record.text ?? '').slice(0, 200)) await this.rt.sendText(text) } } export const describeUptime = (ms: number) => formatDuration(ms)