| 6 | // state (editMessageWidgetData, by the message's chat and message_id or its inline_message_id) and the shared |
| 7 | // widget's (editSharedWidgetData by widget_id, with cache_time), repeats them when the action says so, then |
| 8 | // answerWidgetQuery with the result as its data. Templates: {n} counts the requests with that data per message |
| 9 | // (per widget_id for a copy, which has no message), {from} is who pressed (first_name), {time} the bot's |
| 10 | // HH:MM:SS. A query with data the table does not know gets an empty answer. It also answers the inline query |
| 11 | // `conf-preview` with the widgets whose message spec says inline (the preview cases). |
| 12 | // --post <widget id> [--variant <kind>]: sends that widget as its message specs say: sendWidget with the html, |
| 13 | // the flags and the state (chat_data, public_data), into the tester's private chat or the test group (chat: |
| 14 | // group). It says when the tester must forward it. |
| 15 | // --self-test: the dispatch on made-up updates against a fake API, no network. |
| 16 | // |
| 17 | // The names are Bot API 10.4's (checked against the beta on 2026-10-28): sendWidget (allow_queries, is_shared), |
| 18 | // answerWidgetQuery (data), editMessageWidgetData, editSharedWidgetData, the updates widget_query (id, from, chat, |
| 19 | // message_id or inline_message_id, chat_instance, chat_type, data, widget_id) and shared_widget_query (id, from, |
| 20 | // data, widget_id: a copy of a shared widget), an inline result as an article with InputWidgetMessageContent. The |
| 21 | // message specs keep the layer-233 flags of docs/tgw-format.md; the Bot API has no fwd_allow_queries: a shared |
| 22 | // widget sent with allow_queries is one whose forwards may ask, so fwd_allow_queries is sent as is_shared + |
| 23 | // allow_queries and shared_widget as is_shared. |
| 24 | // |
| 25 | // Config: the same file as publish-channel.ts, ~/.config/widget-sandbox/test-bot.env (or --config): TW_BOT_TOKEN, |
| 26 | // TW_BOT_USER (the tester's private chat), TW_BOT_GROUP (the test group, for chat: group), optional TW_BOT_API |
| 27 | // (the beta: https://api.telegram.org/beta) and TW_BOT_TEST_ENV=1. Never inside a git working tree. |
| 28 | // |
| 29 | // corepack pnpm tsx scripts/conformance/test-bot.ts --self-test |
| 30 | // corepack pnpm tsx scripts/conformance/test-bot.ts --post visual/sdk/20-forward-requests --variant live-copy |
| 31 | // corepack pnpm tsx scripts/conformance/test-bot.ts |
| 32 |
| 33 | import fs from 'node:fs'; |
| 34 | import os from 'node:os'; |
| 35 | import path from 'node:path'; |
| 36 | import { fileURLToPath } from 'node:url'; |
| 37 | import type { BotAction, MessageSpec } from './lib'; |
| 38 |
| 39 | const ROOT = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', '..'); |
| 40 | const CONF = path.join(ROOT, 'packages', 'conformance'); |
| 41 | const args = process.argv.slice(2); |
| 42 | const opt = (name: string) => (args.includes(name) ? args[args.indexOf(name) + 1] : undefined); |
| 43 | const die = (m: string): never => { console.error(`test-bot: ${m}`); process.exit(1); }; |
| 44 |
| 45 | interface Post { widget: string; width: number; height: number; message?: MessageSpec; variant?: string } |
| 46 | interface Channel { posts: Post[]; bot: Record<string, { case: string; action: BotAction }> } |
| 47 | const channel = (): Channel => JSON.parse(fs.readFileSync(path.join(CONF, 'channel.json'), 'utf8')); |
| 48 |
| 49 | // ---- the Bot API |
| 50 |
| 51 | type Api = (method: string, params: Record<string, unknown>) => Promise<any>; |
| 52 |
| 53 | function loadConfig() { |
| 54 | const file = opt('--config') ?? path.join(os.homedir(), '.config', 'widget-sandbox', 'test-bot.env'); |
| 55 | const vals: Record<string, string> = {}; |
| 56 | if (fs.existsSync(file)) { |
| 57 | for (let d = path.dirname(path.resolve(file)); path.dirname(d) !== d; d = path.dirname(d)) if (fs.existsSync(path.join(d, '.git'))) die(`the config ${file} is inside a git working tree`); |
| 58 | for (const line of fs.readFileSync(file, 'utf8').split('\n')) { |
| 59 | const m = /^\s*(?:export\s+)?([A-Z0-9_]+)\s*=\s*(.*?)\s*$/.exec(line); |
| 60 | if (m && !line.trim().startsWith('#')) vals[m[1]] = m[2].replace(/^(['"])(.*)\1$/, '$2'); |
| 61 | } |
| 62 | } |
| 63 | const get = (k: string) => process.env[k] || vals[k] || ''; |
| 64 | const token = get('TW_BOT_TOKEN') || die(`no TW_BOT_TOKEN (${file})`); |
| 65 | const base = (get('TW_BOT_API') || 'https://api.telegram.org').replace(/\/+$/, ''); |
| 66 | const group = get('TW_BOT_GROUP'); |
| 67 | return { |
| 68 | user: get('TW_BOT_USER'), |
| 69 | group: group && !group.startsWith('-100') ? `-100${group}` : group, |
| 70 | base: get('TW_BOT_TEST_ENV') === '1' ? `${base}/bot${token}/test` : `${base}/bot${token}`, |
| 71 | }; |
| 72 | } |
| 73 |
| 74 | function botApi(base: string): Api { |
| 75 | return async (method, params) => { |
| 76 | const res = await fetch(`${base}/${method}`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(params) }); |
| 77 | const body = (await res.json()) as { ok: boolean; result?: unknown; description?: string; parameters?: { retry_after?: number } }; |
| 78 | if (body.ok) return body.result; |
| 79 | if (body.parameters?.retry_after) { await new Promise((r) => setTimeout(r, body.parameters!.retry_after! * 1000)); return botApi(base)(method, params); } |
| 80 | throw new Error(`${method}: ${body.description}`); |
| 81 | }; |
| 82 | } |
| 83 |
| 84 | // ---- answering widget queries |
| 85 |
| 86 | const counters = new Map<string, number>(); |
| 87 | const fill = (s: string, n: number, from: string) => |
| 88 | s.replace(/\{n\}/g, String(n)).replace(/\{from\}/g, from).replace(/\{time\}/g, new Date().toTimeString().slice(0, 8)); |
| 89 |
| 90 | /** |
| 91 | * One widget_query or shared_widget_query (Bot API): what the table says for its data, then the answer. A |
| 92 | * widget_query comes from a message (chat and message_id, or inline_message_id; widget_id when it is a shared |
| 93 | * widget's); a shared_widget_query from a copy of a shared widget, which has only widget_id. |
| 94 | */ |
| 95 | export async function handleQuery(api: Api, q: any, table: Channel['bot'], schedule = setTimeout as (f: () => void, ms: number) => unknown) { |
| 96 | const action = table[q.data]?.action; |
| 97 | if (!action) return api('answerWidgetQuery', { widget_query_id: q.id }); |
| 98 | // A copy has no message: its counter (and its edits) go by the shared widget. |
| 99 | const where = q.chat && q.message_id ? `${q.chat.id}:${q.message_id}` : q.inline_message_id ?? `widget:${q.widget_id}`; |
| 100 | const key = `${where}|${q.data}`; |
| 101 | const from = q.from?.first_name ?? String(q.from?.id ?? ''); |
| 102 | const edit = async () => { |
| 103 | const n = (counters.get(key) ?? 0) + 1; |
| 104 | counters.set(key, n); |
| 105 | if (action.edit) { |
| 106 | const fields = Object.fromEntries(Object.entries(action.edit).map(([k, v]) => [k, fill(v as string, n, from)])); |
| 107 | if (q.chat && q.message_id) await api('editMessageWidgetData', { chat_id: q.chat.id, message_id: q.message_id, ...fields }); |
| 108 | else if (q.inline_message_id) await api('editMessageWidgetData', { inline_message_id: q.inline_message_id, ...fields }); |
| 109 | // A copy: only the shared state, by the widget's id (a copy has no chat state). |
| 110 | else if (q.widget_id && fields.public_data !== undefined) await api('editSharedWidgetData', { widget_id: q.widget_id, public_data: fields.public_data }); |
| 111 | } |
| 112 | if (action.editShared && q.widget_id) { |
| 113 | await api('editSharedWidgetData', { widget_id: q.widget_id, public_data: fill(action.editShared.public_data, n, from), ...(action.editShared.cache_time !== undefined ? { cache_time: action.editShared.cache_time } : {}) }); |
| 114 | } |
| 115 | return n; |
| 116 | }; |
| 117 | const n = action.edit || action.editShared ? await edit() : (counters.set(key, (counters.get(key) ?? 0) + 1), counters.get(key)!); |
| 118 | if (action.repeat) for (let i = 1; i < action.repeat.times; i++) schedule(() => { edit().catch((e) => console.error(`repeat ${q.data}: ${e.message}`)); }, i * action.repeat.every * 1000); |
| 119 | return api('answerWidgetQuery', { widget_query_id: q.id, ...(action.result !== undefined ? { data: fill(action.result, n, from) } : {}) }); |
| 120 | } |
| 121 |
| 122 | // ---- sending |
| 123 |
| 124 | /** sendWidget's fields (and InputWidgetMessageContent's) for a message spec: its layer-233 flags in Bot API terms. */ |
| 125 | const sendFields = (m: MessageSpec | undefined, p: Post) => ({ |
| 126 | html: fs.readFileSync(path.join(CONF, p.widget), 'utf8'), |
| 127 | ...(p.width > 0 ? { width: p.width } : {}), |
| 128 | ...(p.height > 0 ? { height: p.height } : {}), |
| 129 | ...(m?.allow_queries || m?.fwd_allow_queries ? { allow_queries: true } : {}), |
| 130 | ...(m?.shared_widget || m?.fwd_allow_queries ? { is_shared: true } : {}), |
| 131 | ...(m?.chat_data !== undefined ? { chat_data: m.chat_data } : {}), |
| 132 | ...(m?.public_data !== undefined ? { public_data: m.public_data } : {}), |
| 133 | }); |
| 134 |
| 135 | /** The inline query conf-preview: the preview cases as articles that send a widget. */ |
| 136 | async function answerInline(api: Api, q: any, posts: Post[]) { |
| 137 | const results = posts.filter((p) => p.message?.inline).map((p, i) => ({ type: 'article', id: String(i + 1), title: p.widget, input_message_content: sendFields(p.message, p) })); |
| 138 | return api('answerInlineQuery', { inline_query_id: q.id, results, cache_time: 0, is_personal: true }); |
| 139 | } |
| 140 |
| 141 | async function post(api: Api, cfg: ReturnType<typeof loadConfig>, id: string, variant?: string) { |
| 142 | const posts = channel().posts.filter((p) => p.widget === `${id}.html` && (!variant || p.variant === variant)); |
| 143 | if (!posts.length) die(`no post ${id}${variant ? ` (${variant})` : ''} in channel.json`); |
| 144 | for (const p of posts) { |
| 145 | const m = p.message; |
| 146 | if (m?.inline) { console.log(`${id}: an inline result: type the bot's username and conf-preview in any chat (the bot must be running)`); continue; } |
| 147 | const chat = m?.chat === 'group' ? cfg.group || die('TW_BOT_GROUP is not set') : cfg.user || die('TW_BOT_USER is not set'); |
| 148 | const sent = await api('sendWidget', { chat_id: chat, ...sendFields(m, p) }); |
| 149 | console.log(`${id}${p.variant ? ` (${p.variant})` : ''}: message ${sent?.message_id} in ${chat}${m?.forward ? ': now forward it, the test looks at the forward' : ''}`); |
| 150 | } |
| 151 | } |
| 152 |
| 153 | async function run(api: Api) { |
| 154 | const { bot, posts } = channel(); |
| 155 | console.log(`test-bot: ${Object.keys(bot).length} request data in the table; answering until Ctrl-C`); |
| 156 | let offset = 0; |
| 157 | for (;;) { |
| 158 | let updates: any[] = []; |
| 159 | try { updates = await api('getUpdates', { offset, timeout: 30, allowed_updates: ['widget_query', 'shared_widget_query', 'inline_query'] }); } catch (e) { console.error((e as Error).message); await new Promise((r) => setTimeout(r, 3000)); continue; } |
| 160 | for (const u of updates) { |
| 161 | offset = u.update_id + 1; |
| 162 | try { |
| 163 | const q = u.widget_query ?? u.shared_widget_query; |
| 164 | if (q) { console.log(`${u.widget_query ? 'widget_query' : 'shared_widget_query'} ${JSON.stringify(q.data)} from ${q.from?.first_name}`); await handleQuery(api, q, bot); } |
| 165 | else if (u.inline_query && u.inline_query.query.trim() === 'conf-preview') await answerInline(api, u.inline_query, posts); |
| 166 | } catch (e) { console.error((e as Error).message); } |
| 167 | } |
| 168 | } |
| 169 | } |
| 170 |
| 171 | // ---- self-test: the dispatch on made-up updates, no network |
| 172 |
| 173 | async function selfTest() { |
| 174 | const { bot } = channel(); |
| 175 | const calls: [string, any][] = []; |
| 176 | const api: Api = async (method, params) => { calls.push([method, params]); return true; }; |
| 177 | const scheduled: number[] = []; |
| 178 | const from = { id: 7, first_name: 'Ann' }; |
| 179 | const expect = (want: [string, any][], what: string) => { |
| 180 | const got = JSON.stringify(calls.splice(0)); |
| 181 | if (got !== JSON.stringify(want)) die(`${what}: got ${got}, want ${JSON.stringify(want)}`); |
| 182 | console.log(`ok ${what}`); |
| 183 | }; |
| 184 | const msg = { chat: { id: 1001, type: 'private' }, message_id: 42, chat_instance: '-1' }; |
| 185 | await handleQuery(api, { id: 'q1', from, ...msg, data: 'conf:16:edit' }, bot); |
| 186 | await handleQuery(api, { id: 'q2', from, ...msg, data: 'conf:16:edit' }, bot); |
| 187 | expect([ |
| 188 | ['editMessageWidgetData', { chat_id: 1001, message_id: 42, chat_data: '1', public_data: '1' }], ['answerWidgetQuery', { widget_query_id: 'q1', data: 'edited 1' }], |
| 189 | ['editMessageWidgetData', { chat_id: 1001, message_id: 42, chat_data: '2', public_data: '2' }], ['answerWidgetQuery', { widget_query_id: 'q2', data: 'edited 2' }], |
| 190 | ], 'a state edit by the message, counted per message (16-state-edit)'); |
| 191 | await handleQuery(api, { id: 'q3', from, widget_id: '77', data: 'conf:20:ask' }, bot); |
| 192 | expect([['answerWidgetQuery', { widget_query_id: 'q3', data: 'answered for Ann' }]], 'a copy (shared_widget_query): only from, data and widget_id (20-forward-requests)'); |
| 193 | await handleQuery(api, { id: 'q4', from, ...msg, widget_id: '88', data: 'conf:24:start' }, bot, (_f, ms) => scheduled.push(ms)); |
| 194 | expect([['editSharedWidgetData', { widget_id: '88', public_data: '1', cache_time: 5 }], ['answerWidgetQuery', { widget_query_id: 'q4', data: 'ticking' }]], 'a shared edit by widget_id, then the answer (24-watch-public-data)'); |
| 195 | if (scheduled.length !== 11 || scheduled[0] !== 10_000) die(`the ticker: got ${scheduled.length} repeats, first at ${scheduled[0]} ms`); |
| 196 | console.log('ok the ticker repeats 11 more times, every 10 s'); |
| 197 | await handleQuery(api, { id: 'q5', from, chat: { id: -100123, type: 'supergroup' }, message_id: 5, chat_instance: '-2', data: 'conf:25:plus' }, bot); |
| 198 | expect([['editMessageWidgetData', { chat_id: -100123, message_id: 5, chat_data: '{"n":1,"by":"Ann"}' }], ['answerWidgetQuery', { widget_query_id: 'q5', data: 'ok' }]], 'a group\'s chat state (25-group-chat-state)'); |
| 199 | await handleQuery(api, { id: 'q7', from, inline_message_id: 'AQ', chat_instance: '-3', chat_type: 'private', data: 'conf:16:edit' }, bot); |
| 200 | expect([['editMessageWidgetData', { inline_message_id: 'AQ', chat_data: '1', public_data: '1' }], ['answerWidgetQuery', { widget_query_id: 'q7', data: 'edited 1' }]], 'a via-bot message: edits by inline_message_id'); |
| 201 | await handleQuery(api, { id: 'q6', from, ...msg, data: 'conf:nope' }, bot); |
| 202 | expect([['answerWidgetQuery', { widget_query_id: 'q6' }]], 'unknown data: an empty answer'); |
| 203 | console.log(`test-bot self-test: ${Object.keys(bot).length} request data in the table, all fine`); |
| 204 | } |
| 205 |
| 206 | async function main() { |
| 207 | if (args.includes('--self-test')) return selfTest(); |
| 208 | const cfg = loadConfig(); |
| 209 | const api = botApi(cfg.base); |
| 210 | const id = opt('--post'); |
| 211 | if (id) return post(api, cfg, id.replace(/\.html$/, ''), opt('--variant')); |
| 212 | return run(api); |
| 213 | } |
| 214 |
| 215 | main().catch((e) => die((e as Error).message)); |
| 216 |