import { formatDuration } from '../../../shared/format.ts' import type { ActivityRef } from '../../../shared/schemas.ts' import { evaluateMath, formatNumber } from './math.ts' import { renderTemplate, type Resolver } from './template.ts' export interface UserInfo { did: string handle: string displayName: string avatar?: string description?: string createdAt?: string | null followersCount?: number } export interface LiveInfo { isLive: boolean title: string activity: ActivityRef | null activitySince: number | null startedAt: number | null endedAt: number | null viewers: number gamesPlayed: string[] } /** Everything variables can reach outside the message itself. Injected so tests and the config tester can fake it. */ export interface VarServices { channel: UserInfo live: LiveInfo publicUrl: string timezone: string botStartedAt: number profile(actor: string): Promise follow(followerDid: string): Promise<{ createdAt: string | null } | null> counterAdd(name: string, delta: number): number counterGet(name: string): number counterSet(name: string, value: number): number quote(n: number | null): { number: number; text: string } | null | 'none' commandResponse(name: string): string | undefined eightBall(): string chatters(): UserInfo[] watchtime(did: string): { online: number; offline: number } | null currentSong(): string | null setTitle(title: string): Promise setActivity(query: string): Promise fetchText(url: string): Promise lastfm(user: string): Promise<{ artist: string; track: string } | null> tealfm(actor: string): Promise<{ artist: string; track: string } | null> /** Integrations settings: whether each is on, and the account used when $(lastfm)/$(tealfm) get none. */ musicSettings(): Record<'lastfm' | 'tealfm', { enabled: boolean; account: string }> weather(location: string): Promise latestPost(actor: string): Promise } export interface VarContext { services: VarServices sender: UserInfo | null /** The whole chat message (for $(echo)). */ message: string messageUri: string | null /** Words after the command name. */ args: string[] /** Counter used by a bare $(count). */ counterKey: string | null inTimer: boolean /** Set while rendering for the config tester: nothing is written. */ dryRun: boolean /** Guards $(references) from recursing. */ depth?: number } const err = (msg: string) => `[Error: ${msg}]` const strip = (s: string) => s.trim().replace(/^@/, '') function argRange(ctx: VarContext, start: number | null, end: number | null, fallback: string): string { const s = start ?? 1 if (s < 1) return err('Invalid tag') if (ctx.args.length < s) return fallback || err(`Index ${s} is not in arguments.`) if (end !== null && end < s) return err('Invalid tag') return ctx.args.slice(s - 1, end ?? undefined).join(' ') } function parseDateArgs(raw: string): number | null { // "2026-12-25", "2026-12-25 18:00", "2026-12-25 18:00 -5" const parts = raw.trim().split(/\s+/) if (!parts[0]) return null const [date, time = '00:00', offset] = parts let iso = `${date}T${time.length === 5 ? `${time}:00` : time}` if (offset !== undefined) { const n = Number(offset) if (Number.isNaN(n)) return null const sign = n < 0 ? '-' : '+' const abs = Math.abs(n) iso += `${sign}${String(Math.floor(abs)).padStart(2, '0')}:${String(Math.round((abs % 1) * 60)).padStart(2, '0')}` } else iso += 'Z' const t = Date.parse(iso) return Number.isNaN(t) ? null : t } function formatTime(zone: string, format: string | undefined, at = new Date()): string { const opts: Intl.DateTimeFormatOptions = { timeZone: zone } if (!format) Object.assign(opts, { hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: true, timeZoneName: 'short' }) else if (/date/i.test(format)) Object.assign(opts, { dateStyle: 'long' }) else if (/24/.test(format)) Object.assign(opts, { hour: '2-digit', minute: '2-digit', hour12: false }) else Object.assign(opts, { hour: 'numeric', minute: '2-digit', hour12: true }) return new Intl.DateTimeFormat('en-US', opts).format(at) } function dateOnly(iso: string | null | undefined, zone: string): string { if (!iso) return 'an unknown date' return new Intl.DateTimeFormat('en-GB', { dateStyle: 'long', timeZone: zone }).format(new Date(iso)) } /** Build the resolver for one render. */ export function makeResolver(ctx: VarContext): Resolver { const s = ctx.services async function user(arg: string): Promise { const name = strip(arg.split(/\s+/)[0] ?? '') if (!name) { if (ctx.sender) return ctx.sender return 'invalid' } const p = await s.profile(name) if (!p) return ctx.sender && !ctx.inTimer ? ctx.sender : 'invalid' return p } function userMember(u: UserInfo, member: string): Promise | string { switch (member) { case '': case 'display_name': case 'name': return u.displayName || u.handle case 'handle': case 'login': return u.handle case 'did': case 'id': case 'provider_id': return u.did case 'provider': return 'bluesky' case 'avatar': return u.avatar ?? '' case 'bio': return u.description || '' case 'followers': return String(u.followersCount ?? 0) case 'accountage': return u.createdAt ? formatDuration(Date.now() - Date.parse(u.createdAt)) : err('Unknown account age.') case 'accountsince': return dateOnly(u.createdAt, s.timezone) case 'time_online': case 'time_offline': { const w = s.watchtime(u.did) if (!w) return err('Loyalty tracking is off.') return formatDuration((member === 'time_online' ? w.online : w.offline) * 1000, 2) } default: return err(`Unknown member “${member}”.`) } } function channelMember(member: string): string { const ch = s.channel const live = s.live switch (member) { case '': case 'handle': case 'login': return ch.handle case 'display_name': case 'name': return ch.displayName || ch.handle case 'did': case 'id': case 'provider_id': return ch.did case 'slug': return ch.handle case 'provider': return 'streamplace' case 'followers': return String(ch.followersCount ?? 0) case 'viewers': return live.isLive ? String(live.viewers) : err('Stream is offline.') case 'uptime': return live.isLive && live.startedAt ? formatDuration(Date.now() - live.startedAt) : err('Stream is offline.') case 'url': return `https://stream.place/${ch.handle}` case 'commands_url': return `${s.publicUrl}/${ch.handle}/commands` case 'media_url': return `${s.publicUrl}/${ch.handle}/media` case 'accountage': return ch.createdAt ? formatDuration(Date.now() - Date.parse(ch.createdAt)) : err('Unknown account age.') case 'accountsince': return dateOnly(ch.createdAt, s.timezone) case 'bio': return ch.description || '' default: return err(`Unknown member “${member}”.`) } } /** * $(lastfm …) and $(tealfm …): "[account] [format]". The first word is the account only when it * looks like one (a handle or DID for teal.fm, a username for Last.fm); otherwise it starts the format. */ async function nowPlaying(service: 'lastfm' | 'tealfm', arg: string): Promise { const words = arg.split(/\s+/).filter(Boolean) const looksLikeAccount = service === 'tealfm' ? /^@?(did:[a-z]+:\S+|([a-z0-9-]+\.)+[a-z][a-z0-9-]*)$/i : /^[a-z0-9_-]{2,}$/i const settings = s.musicSettings()[service] if (!settings.enabled) return err(service === 'lastfm' ? 'Last.fm is turned off. Turn it on in Integrations.' : 'teal.fm is turned off. Turn it on in Integrations.') const name = words[0] && looksLikeAccount.test(words[0]) ? words.shift()!.replace(/^@/, '') : settings.account if (!name) return err(service === 'lastfm' ? 'You must provide a last.fm username.' : 'You must provide a teal.fm handle.') const np = await s[service](name).catch(() => undefined) if (np === undefined) return err(service === 'lastfm' ? 'last.fm API returned an error.' : 'Couldn’t read that teal.fm status.') if (!np) return `${name} isn’t playing anything right now.` const format = words.join(' ') || '{artist} - {songname}' return format.replace(/\{artist\}/g, np.artist).replace(/\{songname\}/g, np.track) } const handlers: Record Promise | string> = { echo: () => ctx.message, query: () => ctx.args.join(' '), querystring: () => new URLSearchParams({ q: ctx.args.join(' ') }).toString().slice(2), msgid: () => ctx.messageUri ?? '', index: (arg) => { const [n, ...fb] = arg.split(/\s+/) return argRange(ctx, Number(n), Number(n), fb.join(' ')) }, fromindex: (arg) => { const [n, ...fb] = arg.split(/\s+/) return argRange(ctx, Number(n), null, fb.join(' ')) }, sender: async (arg, member) => { if (ctx.inTimer) return err('Cannot be executed inside of a timer') if (!ctx.sender) return '' return userMember(ctx.sender, member) }, sendername: () => (ctx.sender ? ctx.sender.handle : ''), user: async (arg, member) => { const u = await user(arg) if (u === 'invalid') return ctx.inTimer ? '' : err('Invalid username.') return userMember(u, member) }, touser: () => (ctx.args[0] ? strip(ctx.args[0]) : (ctx.sender?.handle ?? '')), target: () => (ctx.args[0] ? strip(ctx.args[0]) : ''), channel: (_arg, member) => channelMember(member), title: () => s.live.title || '', game: (_arg, member) => { if (member === 'playtime') { if (!s.live.activity || !s.live.activitySince) return err('No game found.') return formatDuration(Date.now() - s.live.activitySince) } return s.live.activity?.name ?? '' }, gamesplayed: () => (s.live.gamesPlayed.length ? s.live.gamesPlayed.join(', ') : err('User has no recorded games yet.')), uptime: () => (s.live.isLive && s.live.startedAt ? formatDuration(Date.now() - s.live.startedAt) : err('Stream is offline.')), downtime: () => { if (s.live.isLive) return err('Stream is live.') if (!s.live.endedAt) return err('User has no recorded downtime yet.') return formatDuration(Date.now() - s.live.endedAt) }, viewers: () => (s.live.isLive ? String(s.live.viewers) : err('Stream is offline.')), chatters: (_arg, member) => { const list = s.chatters() if (member.startsWith('random')) { if (!list.length) return err('Unable to find a chatter.') const pick = list[Math.floor(Math.random() * list.length)] return userMember(pick, member.slice('random'.length).replace(/^\./, '')) } return String(list.length) }, settitle: async (arg) => { if (!arg) return err('No title provided.') if (!ctx.dryRun) await s.setTitle(arg) return `Changed title to "${arg}"` }, setgame: async (arg) => { if (!arg) return err('No game provided.') const name = ctx.dryRun ? arg : await s.setActivity(arg) return `Changed game to "${name}"` }, followage: async (arg) => { const [who] = arg.split(/\s+/) const u = await user(who ?? '') if (u === 'invalid') return err('One or more users not found.') if (u.did === s.channel.did) return err('You cannot follow yourself.') const f = await s.follow(u.did) if (!f) return err(`${u.displayName || u.handle} is not following ${s.channel.displayName || s.channel.handle}.`) if (!f.createdAt) return `${u.displayName || u.handle} is following ${s.channel.displayName || s.channel.handle}.` return `${u.displayName || u.handle} has been following ${s.channel.displayName || s.channel.handle} for ${formatDuration(Date.now() - Date.parse(f.createdAt))}.` }, followsince: async (arg) => { const u = await user(arg) if (u === 'invalid') return err('User not found.') const f = await s.follow(u.did) if (!f) return err(`${u.displayName || u.handle} is not following ${s.channel.displayName || s.channel.handle}.`) return `${u.displayName || u.handle} has been following ${s.channel.displayName || s.channel.handle} since ${dateOnly(f.createdAt, s.timezone)}.` }, accountage: async (arg) => { const u = await user(arg) if (u === 'invalid') return err('User not found.') return u.createdAt ? formatDuration(Date.now() - Date.parse(u.createdAt)) : err('Unknown account age.') }, count: (arg, member) => { const [name, amount] = arg.split(/\s+/) const validName = (n: string | undefined) => !!n && /^[a-z0-9_-]+$/i.test(n) const nameErr = err('Count name invalid. Must contain only alphanumeric, dashes, or underscores.') const key = (n: string) => `count:${n.toLowerCase()}` switch (member) { case '': if (!ctx.counterKey) return err('$(count) only works in commands and keywords.') return String(ctx.dryRun ? s.counterGet(ctx.counterKey) + 1 : s.counterAdd(ctx.counterKey, 1)) case 'get': if (!name) return handlers.count('', '') if (!validName(name)) return nameErr return String(s.counterGet(key(name))) case 'increment': case 'update': { if (!validName(name)) return nameErr const delta = amount === undefined ? 1 : Number(amount) if (Number.isNaN(delta)) return err('Amount must be a number.') return String(ctx.dryRun ? s.counterGet(key(name)) + delta : s.counterAdd(key(name), delta)) } case 'set': { if (!name || amount === undefined) return err('Usage: $(count.set ).') if (!validName(name)) return nameErr const n = Number(amount) if (Number.isNaN(n)) return err('Count must be a number.') return String(ctx.dryRun ? Math.max(0, n) : s.counterSet(key(name), n)) } default: return err(`Unknown member “${member}”.`) } }, randint: (arg) => { const parts = arg.split(/\s+/).filter(Boolean) if (parts.length !== 2) return err('Usage: $(randint 1 30).') const [a, b] = parts.map(Number) if (Number.isNaN(a) || Number.isNaN(b)) return err('Usage: $(randint 1 30).') const lo = Math.ceil(Math.min(a, b)) const hi = Math.floor(Math.max(a, b)) return String(lo + Math.floor(Math.random() * (hi - lo + 1))) }, random: (arg) => { // $(random 1-100) or $(random a|b|c) const range = /^(-?\d+)\s*-\s*(-?\d+)$/.exec(arg) if (range) return handlers.randint(`${range[1]} ${range[2]}`, '') const opts = arg.split('|').map((x) => x.trim()).filter(Boolean) if (opts.length) return opts[Math.floor(Math.random() * opts.length)] return String(Math.floor(Math.random() * 100) + 1) }, rngphrase: (arg) => { const opts = arg.split(',').map((x) => x.trim()).filter(Boolean) if (!opts.length) return err('Must provide arguments.') return opts[Math.floor(Math.random() * opts.length)] }, eightball: () => s.eightBall(), time: (arg) => { const [zone, ...fmt] = arg.split(/\s+/).filter(Boolean) const tz = zone || s.timezone if (!tz) return err('No timezone provided.') try { return formatTime(tz, fmt.join(' ') || undefined) } catch { return err('Invalid timezone.') } }, date: (arg) => { const tz = arg.trim() || s.timezone try { return new Intl.DateTimeFormat('en-GB', { dateStyle: 'long', timeZone: tz }).format(new Date()) } catch { return err('Invalid timezone.') } }, countdown: (arg) => { if (!arg) return err('No timestamp provided.') const t = parseDateArgs(arg) if (t === null) return err('Failed to parse timestamp.') return formatDuration(Math.abs(t - Date.now())) }, botuptime: () => formatDuration(Date.now() - s.botStartedAt), math: (arg) => { if (!arg) return err('No math provided.') try { return formatNumber(evaluateMath(arg)) } catch (e) { return err(e instanceof Error ? e.message : 'Invalid math expression.') } }, repeat: (arg) => { const m = /^(\d+)\s+([\s\S]+)$/.exec(arg) if (!m) return err('Usage: $(repeat 6 Phrase).') const n = Math.min(Number(m[1]), 50) return Array.from({ length: n }, () => m[2]).join(' ') }, urlencode: (arg) => new URLSearchParams({ q: arg }).toString().slice(2), urldecode: (arg) => { try { return decodeURIComponent(arg.replace(/\+/g, ' ')) } catch { return arg } }, pathencode: (arg) => encodeURIComponent(arg), pathdecode: (arg) => { try { return decodeURIComponent(arg) } catch { return arg } }, upper: (arg) => arg.toUpperCase(), lower: (arg) => arg.toLowerCase(), customapi: async (arg) => { if (!arg) return err('No URL provided.') if (ctx.dryRun) return `[customapi: ${arg}]` try { return await s.fetchText(arg) } catch { return err('Failed to connect to remote server.') } }, lastfm: (arg) => nowPlaying('lastfm', arg), tealfm: (arg) => nowPlaying('tealfm', arg), weather: async (arg) => { if (!arg) return err('No Weather location provided.') return s.weather(arg) }, quote: (arg) => { const n = arg && arg !== 'random' ? Number(arg) : null if (n !== null && Number.isNaN(n)) return err('Quote not found.') const q = s.quote(n) if (q === 'none') return err('This channel does not have any quotes.') if (!q) return err('Quote not found.') return `#${q.number}: ${q.text}` }, references: async (arg) => { if (!arg) return err('Input argument required.') if ((ctx.depth ?? 0) > 0) return err('Nested $(references) are not allowed.') const response = s.commandResponse(strip(arg).replace(/^!/, '').toLowerCase()) if (response === undefined) return err('Command not found.') return renderTemplate(response, makeResolver({ ...ctx, depth: (ctx.depth ?? 0) + 1 })) }, song: () => s.currentSong() ?? 'Nothing is playing right now.', bsky: async (arg, member) => { if (member !== 'latest') return err(`Unknown member “${member}”.`) const actor = strip(arg) || s.channel.did return (await s.latestPost(actor)) ?? err('No posts found.') }, } handlers.urlfetch = handlers.customapi handlers.currenttime = handlers.time handlers.countup = handlers.countdown handlers.followdate = handlers.followsince handlers.accountsince = async (arg) => { const u = await user(arg) return u === 'invalid' ? err('User not found.') : dateOnly(u.createdAt, s.timezone) } return async (name, argText) => { // Argument shorthands: $(1), $(2:), $(:3), $(1:3), each with an optional fallback. const range = /^(\d*)(:?)(\d*)$/.exec(name) if (range && (range[1] || range[3])) { const start = range[1] ? Number(range[1]) : 1 const end = range[2] ? (range[3] ? Number(range[3]) : null) : start return argRange(ctx, start, end, argText) } const lower = name.toLowerCase() if (handlers[lower]) return handlers[lower](argText, '') const dot = lower.indexOf('.') if (dot > 0) { const base = lower.slice(0, dot) if (handlers[base]) return handlers[base](argText, lower.slice(dot + 1)) } return undefined } } export function renderWith(template: string, ctx: VarContext): Promise { return renderTemplate(template, makeResolver(ctx)) }