| 1 | // The bot behind corpus/bot-demos: six widgets that use the widget's state and requests for real (Bot API 10.4). |
| 2 | // Long polling, no dependencies. The protocol of each widget is in its file's header and notes/bot-demos-spec.md; |
| 3 | // apps/web/src/mock-bot.ts plays the same protocol in the dev app. |
| 4 | // |
| 5 |
| 6 | // inline mode (@bot in any chat): a duel, a poll, who's in, the ticker and the reaction test (the shared ones by id) |
| 7 | // requests: order:poll|refresh|cancel, vote:N, rsvp:in|may|out, ttt:N|new, score:N (widget_query and, from copies |
| 8 | // of shared widgets, shared_widget_query); the bot edits the state with editMessageWidgetData / editSharedWidgetData |
| 9 | // and answers with answerWidgetQuery's data (JSON). |
| 10 | // timers: an order moves one step every 30 s until delivered; a ticker changes every 10 s for a day. |
| 11 | // |
| 12 | // Config: ~/.config/widget-sandbox/widget-bot.env (or --config): TW_BOT_TOKEN, TW_BOT_API (the beta: |
| 13 | // https://api.telegram.org/beta), TW_BOT_TEST_ENV=1. State: bot-demos.state.json next to the config. Never inside a |
| 14 | // git working tree. |
| 15 | // |
| 16 | // corepack pnpm tsx scripts/bot-demos.ts [--config <file>] |
| 17 |
| 18 | import fs from 'node:fs'; |
| 19 | import os from 'node:os'; |
| 20 | import path from 'node:path'; |
| 21 | import { fileURLToPath } from 'node:url'; |
| 22 |
| 23 | const ROOT = path.join(path.dirname(fileURLToPath(import.meta.url)), '..'); |
| 24 | const DEMOS = path.join(ROOT, 'corpus', 'bot-demos'); |
| 25 | const args = process.argv.slice(2); |
| 26 | const opt = (name: string) => (args.includes(name) ? args[args.indexOf(name) + 1] : undefined); |
| 27 | const die = (m: string): never => { console.error(`bot-demos: ${m}`); process.exit(1); }; |
| 28 |
| 29 | // ---- config and the Bot API |
| 30 |
| 31 | const CONFIG = opt('--config') ?? path.join(os.homedir(), '.config', 'widget-sandbox', 'widget-bot.env'); |
| 32 | function loadConfig() { |
| 33 | const vals: Record<string, string> = {}; |
| 34 | if (!fs.existsSync(CONFIG)) die(`no config ${CONFIG}`); |
| 35 | for (let d = path.dirname(path.resolve(CONFIG)); path.dirname(d) !== d; d = path.dirname(d)) if (fs.existsSync(path.join(d, '.git'))) die(`the config ${CONFIG} is inside a git working tree`); |
| 36 | for (const line of fs.readFileSync(CONFIG, 'utf8').split('\n')) { |
| 37 | const m = /^\s*(?:export\s+)?([A-Z0-9_]+)\s*=\s*(.*?)\s*$/.exec(line); |
| 38 | if (m && !line.trim().startsWith('#')) vals[m[1]] = m[2].replace(/^(['"])(.*)\1$/, '$2'); |
| 39 | } |
| 40 | const get = (k: string) => process.env[k] || vals[k] || ''; |
| 41 | const token = get('TW_BOT_TOKEN') || die(`no TW_BOT_TOKEN in ${CONFIG}`); |
| 42 | const base = (get('TW_BOT_API') || 'https://api.telegram.org').replace(/\/+$/, ''); |
| 43 | return { token, url: get('TW_BOT_TEST_ENV') === '1' ? `${base}/bot${token}/test` : `${base}/bot${token}` }; |
| 44 | } |
| 45 | const cfg = loadConfig(); |
| 46 |
| 47 | async function api(method: string, params: Record<string, unknown> = {}): Promise<any> { |
| 48 | for (;;) { |
| 49 | let body: any; |
| 50 | try { |
| 51 | const res = await fetch(`${cfg.url}/${method}`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(params) }); |
| 52 | body = await res.json(); |
| 53 | } catch (e) { throw new Error(`${method}: ${String((e as Error).message).split(cfg.token).join('<token>')}`); } |
| 54 | if (body.ok) return body.result; |
| 55 | const wait = body.parameters?.retry_after; |
| 56 | if (wait) { await new Promise((r) => setTimeout(r, wait * 1000 + 200)); continue; } |
| 57 | throw new Error(`${method}: ${body.description}`); |
| 58 | } |
| 59 | } |
| 60 | const html = (file: string) => fs.readFileSync(path.join(DEMOS, file), 'utf8'); |
| 61 | const J = (s: string | undefined | null, d: any) => { try { return s ? JSON.parse(s) : d; } catch { return d; } }; |
| 62 | const nameOf = (u: any) => String(u?.first_name ?? 'Someone').slice(0, 16); |
| 63 | const hhmm = (d: Date) => d.toTimeString().slice(0, 5); |
| 64 |
| 65 | // ---- state (persisted) |
| 66 |
| 67 | interface Order { st: number; eta: string; next: number } |
| 68 | /** `r`, a shared object's revision, goes out with every edit and answer: a client's poll may bring an older copy back. */ |
| 69 | interface Poll { q: string; o: string[]; v: number[]; voters: Record<string, number>; r?: number } |
| 70 | interface Rsvp { c: { in: [number, string][]; may: [number, string][]; out: [number, string][] }; p: { t: string; w: string; p: string; max: number; n: number } } |
| 71 | interface Duel { b: string; x: [number, string] | null; o: [number, string] | null; t: 'x' | 'o'; w: string | null; l: number[] | null; s: [number, number] } |
| 72 | interface Ticker { s: string; n: string; c: string; p: number; o: number; h: number[]; until: number; r?: number } |
| 73 | interface State { |
| 74 | orders: Record<string, Order & { pub: any }>; |
| 75 | polls: Record<string, Poll>; |
| 76 | rsvps: Record<string, Rsvp>; |
| 77 | duels: Record<string, Duel>; |
| 78 | tickers: Record<string, Ticker>; |
| 79 | reaction: { id: string | null; top: [string, number][]; plays: number; bests: Record<string, [string, number]>; chats: Record<string, number>; r?: number }; |
| 80 | } |
| 81 | const STATE_FILE = path.join(path.dirname(CONFIG), 'bot-demos.state.json'); |
| 82 | const state: State = Object.assign( |
| 83 | { orders: {}, polls: {}, rsvps: {}, duels: {}, tickers: {}, reaction: { id: null, top: [], plays: 0, bests: {}, chats: {} } }, |
| 84 | J(fs.existsSync(STATE_FILE) ? fs.readFileSync(STATE_FILE, 'utf8') : null, {}), |
| 85 | ); |
| 86 | let saveTimer: NodeJS.Timeout | null = null; |
| 87 | const save = () => { saveTimer ??= setTimeout(() => { saveTimer = null; fs.writeFileSync(STATE_FILE, JSON.stringify(state)); }, 500); }; |
| 88 |
| 89 | /** Where a widget_query's message is: chat:message or i:<inline id>. */ |
| 90 | const keyOf = (q: any) => (q.inline_message_id ? `i:${q.inline_message_id}` : `${q.chat.id}:${q.message_id}`); |
| 91 | const where = (key: string) => (key.startsWith('i:') ? { inline_message_id: key.slice(2) } : { chat_id: Number(key.split(':')[0]), message_id: Number(key.split(':')[1]) }); |
| 92 | /** An edit that changes nothing is not an error here ("message is not modified"). */ |
| 93 | const sameIsFine = (e: unknown) => { if (!/not modified/i.test((e as Error).message)) throw e; }; |
| 94 | const editMessage = (key: string, fields: { chat_data?: string; public_data?: string }) => api('editMessageWidgetData', { ...where(key), ...fields }).catch(sameIsFine); |
| 95 | const editShared = (widget_id: string, public_data: string) => api('editSharedWidgetData', { widget_id, public_data, cache_time: 5 }).catch(sameIsFine); |
| 96 |
| 97 | // ---- the six demos: their first state |
| 98 |
| 99 | let me: any; |
| 100 | const SHOPS = [['Pizzeria Uno', '🍕', [['Margherita', 2, 1250], ['Burrata', 1, 900], ['Lemonade', 2, 350]]], ['Sushi Kai', '🍣', [['Salmon nigiri', 4, 380], ['Dragon roll', 1, 1450], ['Miso soup', 2, 420]]], ['Burger Lab', '🍔', [['Smash burger', 2, 1190], ['Fries', 2, 450], ['Shake', 1, 590]]]] as const; |
| 101 | function newOrder() { |
| 102 | const [shop, e, items] = SHOPS[Math.floor(Math.random() * SHOPS.length)]; |
| 103 | const pub = { shop, e, id: `A-${1000 + Math.floor(Math.random() * 9000)}`, st: 0, eta: hhmm(new Date(Date.now() + 25 * 60_000)), u: hhmm(new Date()), bot: me.username }; |
| 104 | const chat = { items, cur: '€', addr: '221B Baker St, flat 3', pay: '•• 4242' }; |
| 105 | return { pub, chat }; |
| 106 | } |
| 107 | const DEFAULT_POLL = { q: 'Where do we go on Friday?', o: ['Pizza', 'Sushi', 'Tacos', 'Burgers'] }; |
| 108 | const newRsvp = (): Rsvp => ({ c: { in: [], may: [], out: [] }, p: { t: 'Friday football', w: 'Fri · 19:00', p: 'Central Park, field 3', max: 10, n: 0 } }); |
| 109 | const newDuel = (): Duel => ({ b: '---------', x: null, o: null, t: 'x', w: null, l: null, s: [0, 0] }); |
| 110 | const duelPublic = (g: Duel) => JSON.stringify({ b: g.b, x: g.x?.[1] ?? null, o: g.o?.[1] ?? null, w: g.w, s: g.s, bot: me.username }); |
| 111 | const tickerPublic = (t: Ticker) => JSON.stringify({ s: t.s, n: t.n, c: t.c, p: t.p, o: t.o, h: t.h, t: new Date().toTimeString().slice(0, 8), r: t.r ?? 0 }); |
| 112 | /** The order's status for its message; `u` is when it last changed (a forward shows the status as of then). */ |
| 113 | const orderPublic = (o: Order & { pub: any }) => JSON.stringify({ ...o.pub, st: o.st, eta: o.eta, u: hhmm(new Date()) }); |
| 114 | const pollPublic = (p: Poll) => JSON.stringify({ q: p.q, o: p.o, v: p.v, r: p.r ?? 0 }); |
| 115 | function newTicker(): Ticker { |
| 116 | const p = 5.3 + Math.random() * 0.3, h = Array.from({ length: 24 }, (_, i) => Math.round((p + Math.sin(i / 3) * 0.08 + (Math.random() - 0.5) * 0.04) * 10000) / 10000); |
| 117 | return { s: 'TON', n: 'Toncoin', c: '$', p: h[23], o: h[0], h, until: Date.now() + 24 * 3600_000 }; |
| 118 | } |
| 119 | const reactionPublic = () => JSON.stringify({ top: state.reaction.top, plays: state.reaction.plays, r: state.reaction.r ?? 0 }); |
| 120 |
| 121 | // ---- commands |
| 122 |
| 123 | async function onMessage(m: any) { |
| 124 | const [cmd, ...rest] = String(m.text ?? '').split(' '); |
| 125 | const c = cmd.split('@')[0]; |
| 126 | const chat_id = m.chat.id; |
| 127 | const reply = (fields: Record<string, unknown>) => api('sendWidget', { chat_id, ...fields }); |
| 128 | if (c === '/start' || c === '/help') { |
| 129 | await api('sendMessage', { chat_id, parse_mode: 'HTML', text: [ |
| 130 | '<b>Widget demos</b> — the widget\'s state and requests, for real.', |
| 131 | '/order — an order tracker: personal details stay in this chat, a forward shows only the status', |
| 132 | '/poll [question | option | option] — a shared poll: forwards vote too, everyone sees live counts', |
| 133 | '/rsvp — who\'s in: a sign-up list for a group', |
| 134 | '/duel — tic-tac-toe for two (best via inline: type @' + me.username + ' in a chat with a friend)', |
| 135 | '/ticker — a live quote: one shared state, every copy follows', |
| 136 | '/reaction — a reaction test with one leaderboard for everyone', |
| 137 | ].join('\n') }); |
| 138 | return; |
| 139 | } |
| 140 | if (c === '/order') { |
| 141 | const o = newOrder(); |
| 142 | const sent = await reply({ html: html('01-order.html'), allow_queries: true, public_data: JSON.stringify(o.pub), chat_data: JSON.stringify(o.chat) }); |
| 143 | state.orders[`${chat_id}:${sent.message_id}`] = { st: 0, eta: o.pub.eta, next: Date.now() + 30_000, pub: o.pub }; |
| 144 | } else if (c === '/poll') { |
| 145 | const parts = rest.join(' ').split('|').map((s) => s.trim()).filter(Boolean); |
| 146 | const q = parts.length >= 3 ? { q: parts[0].slice(0, 120), o: parts.slice(1, 7).map((s) => s.slice(0, 40)) } : DEFAULT_POLL; |
| 147 | const sent = await reply({ html: html('02-poll.html'), allow_queries: true, is_shared: true, public_data: JSON.stringify({ ...q, v: q.o.map(() => 0) }) }); |
| 148 | state.polls[sent.widget.id] = { ...q, v: q.o.map(() => 0), voters: {} }; |
| 149 | } else if (c === '/rsvp') { |
| 150 | const r = newRsvp(); |
| 151 | const sent = await reply({ html: html('03-rsvp.html'), allow_queries: true, public_data: JSON.stringify(r.p), chat_data: JSON.stringify(r.c) }); |
| 152 | state.rsvps[`${chat_id}:${sent.message_id}`] = r; |
| 153 | } else if (c === '/duel') { |
| 154 | const g = newDuel(); |
| 155 | const sent = await reply({ html: html('04-tic-tac-toe.html'), allow_queries: true, chat_data: JSON.stringify(g), public_data: duelPublic(g) }); |
| 156 | state.duels[`${chat_id}:${sent.message_id}`] = g; |
| 157 | } else if (c === '/ticker') { |
| 158 | const id = Object.keys(state.tickers).find((k) => state.tickers[k].until > Date.now()); |
| 159 | if (id) await api('sendSharedWidget', { chat_id, widget_id: id }); |
| 160 | else { |
| 161 | const t = newTicker(); |
| 162 | const sent = await reply({ html: html('05-ticker.html'), is_shared: true, public_data: tickerPublic(t) }); |
| 163 | state.tickers[sent.widget.id] = t; |
| 164 | } |
| 165 | } else if (c === '/reaction') { |
| 166 | const best = state.reaction.chats[String(chat_id)]; |
| 167 | const chat_data = best ? JSON.stringify({ best }) : undefined; |
| 168 | if (state.reaction.id) await api('sendSharedWidget', { chat_id, widget_id: state.reaction.id, ...(chat_data ? { chat_data } : {}) }); |
| 169 | else { |
| 170 | const sent = await reply({ html: html('06-reaction.html'), allow_queries: true, is_shared: true, public_data: reactionPublic(), ...(chat_data ? { chat_data } : {}) }); |
| 171 | state.reaction.id = sent.widget.id; |
| 172 | } |
| 173 | } else return; |
| 174 | console.log(`${c} in ${m.chat.type} ${chat_id}`); |
| 175 | save(); |
| 176 | } |
| 177 |
| 178 | // ---- inline mode |
| 179 |
| 180 | async function onInline(q: any) { |
| 181 | const article = (id: string, title: string, description: string, content: Record<string, unknown>) => ({ type: 'article', id, title, description, input_message_content: content }); |
| 182 | const g = newDuel(), r = newRsvp(); |
| 183 | const results = [ |
| 184 | article('duel', 'Tic-tac-toe duel', 'Challenge someone in this chat', { html: html('04-tic-tac-toe.html'), allow_queries: true, chat_data: JSON.stringify(g), public_data: duelPublic(g) }), |
| 185 | article('poll', DEFAULT_POLL.q, 'A shared poll: forwards vote too', { html: html('02-poll.html'), allow_queries: true, is_shared: true, public_data: JSON.stringify({ ...DEFAULT_POLL, v: DEFAULT_POLL.o.map(() => 0) }) }), |
| 186 | article('rsvp', 'Who\'s in?', 'A sign-up list for this chat', { html: html('03-rsvp.html'), allow_queries: true, public_data: JSON.stringify(r.p), chat_data: JSON.stringify(r.c) }), |
| 187 | ...(state.reaction.id ? [article('reaction', 'Reaction test', `One leaderboard for everyone · ${state.reaction.plays} plays`, { widget_id: state.reaction.id })] : []), |
| 188 | ...Object.keys(state.tickers).filter((k) => state.tickers[k].until > Date.now()).slice(0, 1).map((id) => article('ticker', 'TON live', 'A live quote, every copy follows', { widget_id: id })), |
| 189 | ]; |
| 190 | await api('answerInlineQuery', { inline_query_id: q.id, results, cache_time: 0, is_personal: true }); |
| 191 | } |
| 192 |
| 193 | /** A message sent via the bot first shows up as a query: give it its state then (the bot did not know its id). */ |
| 194 | function stateFor<T>(map: Record<string, T>, key: string, make: () => T): T { |
| 195 | return (map[key] ??= make()); |
| 196 | } |
| 197 |
| 198 | // ---- requests |
| 199 |
| 200 | async function onQuery(q: any, fromCopy: boolean): Promise<unknown> { |
| 201 | const data: string = q.data; |
| 202 | const uid = q.from.id, who = nameOf(q.from); |
| 203 | const [kind, arg] = data.split(':'); |
| 204 |
| 205 | if (kind === 'vote') { |
| 206 | const id = q.widget_id; |
| 207 | if (!id) return { err: 'Not a shared poll' }; |
| 208 | const p = stateFor<Poll>(state.polls, id, () => ({ ...DEFAULT_POLL, v: DEFAULT_POLL.o.map(() => 0), voters: {} })); |
| 209 | const n = Number(arg); |
| 210 | if (!(n >= 0 && n < p.o.length)) return { err: 'Unknown option' }; |
| 211 | const before = p.voters[uid]; |
| 212 | if (before !== undefined) p.v[before]--; |
| 213 | if (before === n) delete p.voters[uid]; else { p.voters[uid] = n; p.v[n]++; } |
| 214 | p.r = (p.r ?? 0) + 1; |
| 215 | await editShared(id, pollPublic(p)); |
| 216 | return { my: p.voters[uid] ?? -1, v: p.v, r: p.r }; |
| 217 | } |
| 218 |
| 219 | if (kind === 'score') { |
| 220 | const ms = Number(arg); |
| 221 | if (!(Number.isInteger(ms) && ms >= 100 && ms <= 2000)) return { err: 'Not a human time' }; |
| 222 | const R = state.reaction; |
| 223 | if (q.widget_id) R.id ??= q.widget_id; |
| 224 | R.plays++; |
| 225 | const prev = R.bests[uid]; |
| 226 | R.bests[uid] = [who, Math.min(prev?.[1] ?? ms, ms)]; |
| 227 | R.top = Object.values(R.bests).sort((a, b) => a[1] - b[1]).slice(0, 8); |
| 228 | R.r = (R.r ?? 0) + 1; |
| 229 | if (R.id) await editShared(R.id, reactionPublic()); |
| 230 | const k = q.chat && String(q.chat.id); |
| 231 | if (!fromCopy && k && !(R.chats[k] <= ms)) { |
| 232 | R.chats[k] = ms; |
| 233 | await editMessage(keyOf(q), { chat_data: JSON.stringify({ best: ms }) }); |
| 234 | } |
| 235 | // The board comes with the answer: a copy may not see the shared edit for a while. |
| 236 | return { rank: R.top.findIndex((r) => r === R.bests[uid]) + 1, best: R.bests[uid][1], top: R.top, plays: R.plays, r: R.r }; |
| 237 | } |
| 238 |
| 239 | if (fromCopy) return { err: 'Not available in a copy' }; |
| 240 | const key = keyOf(q); |
| 241 |
| 242 | if (kind === 'order') { |
| 243 | const o = state.orders[key]; |
| 244 | if (!o) return { err: 'Order not found' }; |
| 245 | if (arg === 'cancel') { |
| 246 | if (o.st < 0) return { err: 'Already cancelled' }; |
| 247 | if (o.st > 1) return { err: 'Too late to cancel' }; |
| 248 | await editMessage(key, { public_data: orderPublic({ ...o, st: -1 }) }); |
| 249 | o.st = -1; |
| 250 | } |
| 251 | return { st: o.st, eta: o.eta }; |
| 252 | } |
| 253 |
| 254 | if (kind === 'rsvp') { |
| 255 | const r: Rsvp = structuredClone(stateFor(state.rsvps, key, newRsvp)); |
| 256 | if (!['in', 'may', 'out'].includes(arg)) return { err: 'Unknown answer' }; |
| 257 | const lists = r.c as Record<string, [number, string][]>; |
| 258 | const was = Object.keys(lists).find((k) => lists[k].some((e) => e[0] === uid)); |
| 259 | const meNow = was === arg ? null : arg; |
| 260 | if (meNow === 'in' && was !== 'in' && r.c.in.length >= r.p.max) return { err: 'Full', me: was ?? null }; |
| 261 | for (const k of Object.keys(lists)) lists[k] = lists[k].filter((e) => e[0] !== uid); |
| 262 | if (meNow) lists[meNow].push([uid, who]); |
| 263 | r.p.n = r.c.in.length; |
| 264 | await editMessage(key, { chat_data: JSON.stringify(r.c), public_data: JSON.stringify(r.p) }); |
| 265 | state.rsvps[key] = r; |
| 266 | return { me: meNow }; |
| 267 | } |
| 268 |
| 269 | if (kind === 'ttt') { |
| 270 | // A move goes into the state only once the message shows it: a failed edit must not take a turn away. |
| 271 | const g: Duel = structuredClone(stateFor(state.duels, key, newDuel)); |
| 272 | if (arg === 'new') { |
| 273 | if (!g.w) return { err: 'Game on' }; |
| 274 | Object.assign(g, { b: '---------', t: g.w === 'x' ? 'o' : 'x', w: null, l: null }); |
| 275 | } else { |
| 276 | const i = Number(arg); |
| 277 | if (!(i >= 0 && i <= 8)) return { err: 'Unknown cell' }; |
| 278 | if (g.w) return { err: 'Game over' }; |
| 279 | if (!g.x) g.x = [uid, who]; |
| 280 | const mark = g.x[0] === uid ? 'x' : g.o?.[0] === uid ? 'o' : g.o ? null : 'o'; |
| 281 | if (!mark) return { err: 'Full' }; |
| 282 | if (g.t !== mark) return { err: 'Not your turn' }; |
| 283 | if (mark === 'o' && !g.o) g.o = [uid, who]; |
| 284 | if (g.b[i] !== '-') return { err: 'Taken' }; |
| 285 | g.b = g.b.slice(0, i) + mark + g.b.slice(i + 1); |
| 286 | const LINES = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6]]; |
| 287 | const line = LINES.find(([a, b, c]) => g.b[a] !== '-' && g.b[a] === g.b[b] && g.b[a] === g.b[c]); |
| 288 | if (line) { g.w = mark; g.l = line; g.s[mark === 'x' ? 0 : 1]++; } else if (!g.b.includes('-')) g.w = 'd'; |
| 289 | g.t = mark === 'x' ? 'o' : 'x'; |
| 290 | } |
| 291 | await editMessage(key, { chat_data: JSON.stringify(g), public_data: duelPublic(g) }); |
| 292 | state.duels[key] = g; |
| 293 | return { ok: 1 }; |
| 294 | } |
| 295 |
| 296 | return { err: 'Unknown request' }; |
| 297 | } |
| 298 |
| 299 | // ---- timers |
| 300 |
| 301 | async function tick() { |
| 302 | const now = Date.now(); |
| 303 | for (const [key, o] of Object.entries(state.orders)) { |
| 304 | if (o.st < 0 || o.st >= 3 || o.next > now) continue; |
| 305 | o.st++; |
| 306 | o.next = now + 30_000; |
| 307 | if (o.st === 3) o.eta = hhmm(new Date()); |
| 308 | try { await editMessage(key, { public_data: orderPublic(o) }); console.log(`order ${key} → ${o.st}`); } |
| 309 | catch (e) { console.error((e as Error).message); delete state.orders[key]; } |
| 310 | save(); |
| 311 | } |
| 312 | for (const [id, t] of Object.entries(state.tickers)) { |
| 313 | if (t.until < now) continue; |
| 314 | t.p = Math.max(0.5, Math.round((t.p * (1 + (Math.random() - 0.48) * 0.006)) * 10000) / 10000); |
| 315 | t.h = [...t.h.slice(1), t.p]; |
| 316 | t.r = (t.r ?? 0) + 1; |
| 317 | try { await editShared(id, tickerPublic(t)); } |
| 318 | catch (e) { console.error((e as Error).message); t.until = 0; } |
| 319 | save(); |
| 320 | } |
| 321 | } |
| 322 |
| 323 | // ---- the loop |
| 324 |
| 325 | async function main() { |
| 326 | me = await api('getMe'); |
| 327 | console.log(`bot-demos: @${me.username}, demos from ${path.relative(ROOT, DEMOS)}, state in ${STATE_FILE}; Ctrl-C to stop`); |
| 328 | setInterval(() => { tick().catch((e) => console.error(e.message)); }, 10_000); |
| 329 | let offset = 0; |
| 330 | for (;;) { |
| 331 | let updates: any[] = []; |
| 332 | try { updates = await api('getUpdates', { offset, timeout: 30, allowed_updates: ['message', 'inline_query', 'widget_query', 'shared_widget_query'] }); } |
| 333 | catch (e) { console.error((e as Error).message); await new Promise((r) => setTimeout(r, 3000)); continue; } |
| 334 | for (const u of updates) { |
| 335 | offset = u.update_id + 1; |
| 336 | try { |
| 337 | if (u.message) await onMessage(u.message); |
| 338 | else if (u.inline_query) await onInline(u.inline_query); |
| 339 | else if (u.widget_query || u.shared_widget_query) { |
| 340 | const q = u.widget_query ?? u.shared_widget_query; |
| 341 | const at = q.inline_message_id ? 'inline' : q.chat ? `${q.chat.id}:${q.message_id}` : `widget ${q.widget_id}`; |
| 342 | let answer: unknown; |
| 343 | // Every query gets an answer, also when an edit fails; otherwise the widget waits and says the bot didn't answer. |
| 344 | try { answer = await onQuery(q, !u.widget_query); } |
| 345 | catch (e) { console.error(`${q.data} at ${at}: ${(e as Error).message}`); answer = { err: 'The bot failed. Try again' }; } |
| 346 | save(); |
| 347 | console.log(`${u.widget_query ? 'widget_query' : 'shared_widget_query'} ${q.data} from ${nameOf(q.from)} at ${at} → ${JSON.stringify(answer).slice(0, 160)}`); |
| 348 | await api('answerWidgetQuery', { widget_query_id: q.id, data: JSON.stringify(answer) }); |
| 349 | } |
| 350 | } catch (e) { console.error((e as Error).message); } |
| 351 | } |
| 352 | } |
| 353 | } |
| 354 |
| 355 | main().catch((e) => die((e as Error).message)); |
| 356 |