| 6 | // 2. the widget: sendWidget (Bot API 10.4, on the beta Bot API until it is |
| 7 | // released) with the HTML, its size anchors and its caption. A bot may |
| 8 | // send a widget only into its private chat with a user, and forwarding is |
| 9 | // allowed into any chat, |
| 10 | // so by default the widget goes to the tester's private chat and is |
| 11 | // forwarded into the topic from there (never copyMessage: a copy is a new |
| 12 | // send, which the server refuses in a group). A test bot that may post |
| 13 | // widgets into any chat (TW_BOT_DIRECT=1) sends it straight into the topic; |
| 14 | // 3. the reference picture(s): sendPhoto, or sendMediaGroup for light + dark; |
| 15 | // a picture Telegram would reject or shrink goes as a document instead. |
| 16 | // The automatic set has no picture: its widgets report their own result. |
| 17 | // |
| 18 | // The size anchors go as sendWidget's width and height (0 = auto on that axis, |
| 19 | // left out). The regular Bot API does not know widgets: an HTML document the test |
| 20 | // bot turned into a widget lost show_caption_above_media (2026-10-30). |
| 21 | // |
| 22 | // Config (never inside a git working tree; environment variables win): |
| 23 | // ~/.config/widget-sandbox/test-bot.env, or --config <file>: |
| 24 | // TW_BOT_TOKEN=… the bot token |
| 25 | // TW_BOT_USER=… the tester's user id: the private chat the widgets go to first |
| 26 | // TW_BOT_DIRECT=1 optional: the bot sends widgets straight into the group (TW_BOT_USER optional then) |
| 27 | // TW_BOT_GROUP=… the forum supergroup (the bot is an admin with Manage topics and Delete messages) |
| 28 | // TW_BOT_ID=… optional: the bot's id, checked against the token |
| 29 | // TW_BOT_API=… optional, default https://api.telegram.org/beta (sendWidget is Bot API 10.4) |
| 30 | // TW_BOT_TEST_ENV=1 optional: the Bot API's test environment (/bot<token>/test/<method>) |
| 31 | // State: ~/.config/widget-sandbox/conformance-channel.state.json (--state <file>), |
| 32 | // per group: the topics and, per post, the hashes and the message ids. A re-run |
| 33 | // skips unchanged posts, edits a changed description or picture in place, and |
| 34 | // for a changed or new widget deletes that post and every later one of its |
| 35 | // topic and posts them again, so a topic stays in posting order. |
| 36 | // |
| 37 | // corepack pnpm tsx scripts/conformance/publish-channel.ts --dry-run |
| 38 | // corepack pnpm tsx scripts/conformance/publish-channel.ts --only visual/01-boxes |
| 39 | // corepack pnpm tsx scripts/conformance/publish-channel.ts [--topic visual,auto] [--limit N] |
| 40 | // corepack pnpm tsx scripts/conformance/publish-channel.ts --reset [--topic …] [--only …] [--delete-topics] |
| 41 | // |
| 42 | // --dry-run prints the plan and sends nothing; with a config it also checks the |
| 43 | // bot, the group and the tester's chat with read-only calls (getMe, getChat, |
| 44 | // getChatMember). --only takes comma-separated key patterns (a substring, or a |
| 45 | // glob with *); it works on the matching posts alone, so a changed one is |
| 46 | // reposted at the end of its topic and the next full run restores the order. |
| 47 | // --limit N stops after N posts sent. --verbose prints what the server |
| 48 | // returned for each widget message. When old messages of a topic cannot be |
| 49 | // deleted (the server lets a bot delete its messages only for a while), the |
| 50 | // run posts nothing again in that topic; --rebuild deletes the selected topics |
| 51 | // with everything in them and posts them again. --reset deletes the messages this script |
| 52 | // recorded (group and private chat) and forgets them; --delete-topics also |
| 53 | // deletes the topics, with everything in them (testers' replies included). |
| 54 |
| 55 | import crypto from 'node:crypto'; |
| 56 | import fs from 'node:fs'; |
| 57 | import os from 'node:os'; |
| 58 | import path from 'node:path'; |
| 59 | import zlib from 'node:zlib'; |
| 60 | import { fileURLToPath } from 'node:url'; |
| 61 |
| 62 | const ROOT = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', '..'); |
| 63 | const CONF = path.join(ROOT, 'packages', 'conformance'); |
| 64 | const CONFIG_DIR = path.join(os.homedir(), '.config', 'widget-sandbox'); |
| 65 |
| 66 | /** |
| 67 | * The topics, in the order they are filled. `channel`: the posts of |
| 68 | * channel.json under this widget-path prefix (the longest prefix wins). |
| 69 | * `corpus`: every widget of a corpus directory that fits a mini-widget, in file |
| 70 | * order, with no picture. `default: false` topics go out only when --topic names them (its name in lower case, |
| 71 | * spaces as hyphens: `--topic safe-area`). `withoutCaption`: its widgets go out without a caption, so a client draws |
| 72 | * its time over them (docs/sdk-v1.md §2.17); a file whose header says `caption: none, below, above` goes out once per |
| 73 | * placement: without a caption, with one below the widget (0: the time in the caption's line), with one above it. |
| 74 | * icon colours: the six Telegram allows for a forum topic. |
| 75 | */ |
| 76 | interface TopicSpec { name: string; channel?: string; corpus?: string; default: boolean; color: number; withoutCaption?: boolean } |
| 77 | const TOPICS: TopicSpec[] = [ |
| 78 | { name: 'Visual', channel: 'visual/', default: true, color: 0x6fb9f0 }, |
| 79 | { name: 'Client SDK', channel: 'visual/sdk/', default: true, color: 0xffd67e }, |
| 80 | { name: 'Auto', channel: 'auto/', default: true, color: 0x8eee98 }, |
| 81 | // Widgets with little or no CSS, drawn by the renderer's UA layer (v0.1.1, corpus/defaults/README.md). |
| 82 | { name: 'Defaults', corpus: 'corpus/defaults', default: true, color: 0xcb86db }, |
| 83 | // What the horizontal-only rule removed and what it keeps (corpus/gestures/README.md); --topic gestures. |
| 84 | { name: 'Gestures', corpus: 'corpus/gestures', default: false, color: 0x6fb9f0 }, |
| 85 | // One widget per resize anchor: the default, growing up, growing down (corpus/resize/README.md); --topic resize. |
| 86 | { name: 'Resize', corpus: 'corpus/resize', default: false, color: 0x8eee98 }, |
| 87 | // The client's time over the corner of a widget without a caption (corpus/safe-area/README.md); --topic safe-area. |
| 88 | { name: 'Safe area', corpus: 'corpus/safe-area', default: false, color: 0xffd67e, withoutCaption: true }, |
| 89 | { name: 'Showcase', corpus: 'corpus/showcase', default: false, color: 0xcb86db }, |
| 90 | { name: 'Common', corpus: 'corpus/common', default: false, color: 0xff93b2 }, |
| 91 | { name: 'Generated', corpus: 'corpus/generated/with-profile', default: false, color: 0xfb6f5f }, |
| 92 | ]; |
| 93 |
| 94 | /** The mini-widget gate of packages/conformance (build.ts): raw and zlib at level 9, as the server counts it. */ |
| 95 | const MAX_RAW = 32 * 1024; |
| 96 | const MAX_ZLIB = 3800; |
| 97 | /** sendPhoto: at most 10 MB, width + height at most 10000, ratio at most 20; the server keeps at most 2560 px on the long side. */ |
| 98 | const PHOTO = { bytes: 10 * 1024 * 1024, sum: 10000, ratio: 20, side: 2560 }; |
| 99 | const TEXT_MAX = 4096; |
| 100 | /** Pacing: about 20 messages a minute into a group, 1 a second into a private chat. */ |
| 101 | const PACE_MS = { group: 3200, user: 1100 }; |
| 102 |
| 103 | // ---- arguments |
| 104 |
| 105 | const argv = process.argv.slice(2); |
| 106 | const flag = (name: string) => argv.includes(name); |
| 107 | const opt = (name: string) => { |
| 108 | const i = argv.indexOf(name); |
| 109 | if (i < 0) return undefined; |
| 110 | const v = argv[i + 1]; |
| 111 | if (v === undefined || v.startsWith('--')) die(`${name} needs a value`); |
| 112 | return v; |
| 113 | }; |
| 114 | const known = new Set(['--dry-run', '--reset', '--delete-topics', '--rebuild', '--only', '--topic', '--limit', '--config', '--state', '--verbose']); |
| 115 | for (const a of argv) if (a.startsWith('--') && !known.has(a)) die(`unknown option ${a}`); |
| 116 | const DRY = flag('--dry-run'); |
| 117 | const RESET = flag('--reset'); |
| 118 | const DELETE_TOPICS = flag('--delete-topics'); |
| 119 | const VERBOSE = flag('--verbose'); |
| 120 | const REBUILD = flag('--rebuild'); |
| 121 | const ONLY = opt('--only')?.split(',').map((s) => s.trim()).filter(Boolean); |
| 122 | const LIMIT = opt('--limit') !== undefined ? Number(opt('--limit')) : Infinity; |
| 123 | if (!(LIMIT >= 0)) die('--limit takes a number'); |
| 124 | if (DELETE_TOPICS && !RESET) die('--delete-topics goes with --reset'); |
| 125 | if (REBUILD && (RESET || ONLY)) die('--rebuild works on whole topics: not with --reset or --only'); |
| 126 | /** A topic as --topic names it: `Safe area` is `safe-area`. */ |
| 127 | const topicArg = (name: string) => name.toLowerCase().replace(/\s+/g, '-'); |
| 128 | const topicNames = opt('--topic')?.split(',').map((s) => topicArg(s.trim())); |
| 129 | for (const n of topicNames ?? []) if (!TOPICS.some((t) => topicArg(t.name) === n)) die(`no topic "${n}" (${TOPICS.map((t) => topicArg(t.name)).join(', ')})`); |
| 130 | const SELECTED = TOPICS.filter((t) => (topicNames ? topicNames.includes(topicArg(t.name)) : t.default)); |
| 131 |
| 132 | function die(msg: string): never { |
| 133 | console.error(`publish-channel: ${msg}`); |
| 134 | process.exit(1); |
| 135 | } |
| 136 |
| 137 | const selects = (key: string) => |
| 138 | !ONLY || |
| 139 | ONLY.some((p) => (p.includes('*') ? new RegExp(`^${p.split('*').map(escapeRe).join('.*')}$`).test(key) : key.includes(p))); |
| 140 | const escapeRe = (s: string) => s.replace(/[.+?^${}()|[\]\\]/g, '\\$&'); |
| 141 |
| 142 | // ---- config and state |
| 143 |
| 144 | interface Config { token: string; user: string; group: string; base: string; direct: boolean } |
| 145 |
| 146 | function insideGitTree(file: string) { |
| 147 | for (let d = path.dirname(path.resolve(file)); ; d = path.dirname(d)) { |
| 148 | if (fs.existsSync(path.join(d, '.git'))) return true; |
| 149 | if (path.dirname(d) === d) return false; |
| 150 | } |
| 151 | } |
| 152 |
| 153 | function loadConfig(): Config | undefined { |
| 154 | const file = opt('--config') ?? path.join(CONFIG_DIR, 'test-bot.env'); |
| 155 | const vals: Record<string, string> = {}; |
| 156 | if (fs.existsSync(file)) { |
| 157 | if (insideGitTree(file)) die(`the config ${file} is inside a git working tree; keep it outside the repository`); |
| 158 | for (const line of fs.readFileSync(file, 'utf8').split('\n')) { |
| 159 | const m = /^\s*(?:export\s+)?([A-Z0-9_]+)\s*=\s*(.*?)\s*$/.exec(line); |
| 160 | if (m && !line.trim().startsWith('#')) vals[m[1]] = m[2].replace(/^(['"])(.*)\1$/, '$2'); |
| 161 | } |
| 162 | } else if (opt('--config')) die(`no config file ${file}`); |
| 163 | const get = (k: string) => process.env[k] || vals[k] || ''; |
| 164 | const token = get('TW_BOT_TOKEN'); |
| 165 | const user = get('TW_BOT_USER'); |
| 166 | const group = get('TW_BOT_GROUP'); |
| 167 | if (!token && !user && !group) return undefined; |
| 168 | // A dry run plans without the token (against the group's recorded state when the ids are there). |
| 169 | const direct = get('TW_BOT_DIRECT') === '1'; |
| 170 | const missing = [['TW_BOT_TOKEN', token], ['TW_BOT_USER', user], ['TW_BOT_GROUP', group]] |
| 171 | .filter(([k, v]) => !v && !(DRY && k === 'TW_BOT_TOKEN') && !(direct && k === 'TW_BOT_USER')).map(([k]) => k); |
| 172 | if (missing.length) die(`config is missing ${missing.join(', ')}`); |
| 173 | if (user && !/^\d+$/.test(user)) die('TW_BOT_USER must be a user id, the private chat with the tester'); |
| 174 | // A supergroup id as the apps show it (1234567890) or as the Bot API takes it (-1001234567890). |
| 175 | if (!/^(-100)?\d+$/.test(group)) die('TW_BOT_GROUP must be a supergroup id'); |
| 176 | const chat = group.startsWith('-100') ? group : `-100${group}`; |
| 177 | const bot = get('TW_BOT_ID'); |
| 178 | if (bot && token && !token.startsWith(`${bot}:`)) die('TW_BOT_TOKEN is not the token of TW_BOT_ID'); |
| 179 | const base = (get('TW_BOT_API') || 'https://api.telegram.org/beta').replace(/\/+$/, ''); |
| 180 | return { token, user, group: chat, direct, base: get('TW_BOT_TEST_ENV') === '1' ? `${base}/bot${token}/test` : `${base}/bot${token}` }; |
| 181 | } |
| 182 |
| 183 | interface PostRecord { |
| 184 | key: string; |
| 185 | hash: Hashes; |
| 186 | /** Every message this post put out was sent and recorded. */ |
| 187 | complete: boolean; |
| 188 | description?: number; |
| 189 | /** The original widget message in the private chat. */ |
| 190 | private?: number; |
| 191 | /** The forwarded copy in the topic. */ |
| 192 | widget?: number; |
| 193 | photos: number[]; |
| 194 | /** The pictures went as documents (too large for a photo). */ |
| 195 | photosAsDocuments?: boolean; |
| 196 | } |
| 197 | interface TopicRecord { threadId: number; posts: PostRecord[] } |
| 198 | interface GroupState { |
| 199 | topics: Record<string, TopicRecord>; |
| 200 | /** Messages the server refused to delete; --reset tries them again. */ |
| 201 | orphans?: { group: number[]; user: number[] }; |
| 202 | } |
| 203 | interface State { version: 1; groups: Record<string, GroupState> } |
| 204 |
| 205 | const STATE_FILE = opt('--state') ?? path.join(CONFIG_DIR, 'conformance-channel.state.json'); |
| 206 | if (insideGitTree(STATE_FILE)) die(`the state file ${STATE_FILE} is inside a git working tree; keep it outside the repository`); |
| 207 |
| 208 | function loadState(): State { |
| 209 | if (!fs.existsSync(STATE_FILE)) return { version: 1, groups: {} }; |
| 210 | return JSON.parse(fs.readFileSync(STATE_FILE, 'utf8')) as State; |
| 211 | } |
| 212 | function saveState(state: State) { |
| 213 | fs.mkdirSync(path.dirname(STATE_FILE), { recursive: true }); |
| 214 | const tmp = `${STATE_FILE}.tmp`; |
| 215 | fs.writeFileSync(tmp, JSON.stringify(state, null, 1) + '\n', { mode: 0o600 }); |
| 216 | fs.renameSync(tmp, STATE_FILE); |
| 217 | } |
| 218 |
| 219 | // ---- the posts |
| 220 |
| 221 | interface Photo { file: string; w: number; h: number; bytes: number; asDocument: string | false; label: string } |
| 222 | interface Hashes { widget: string; description: string; photos: string } |
| 223 | interface Post { |
| 224 | key: string; |
| 225 | topic: string; |
| 226 | file: string; |
| 227 | width: number; |
| 228 | height: number; |
| 229 | html: Buffer; |
| 230 | zlib: number; |
| 231 | /** The description message, HTML parse mode. */ |
| 232 | text: string; |
| 233 | photos: Photo[]; |
| 234 | hash: Hashes; |
| 235 | /** Sent without a caption: the client draws its time over the widget (channel.json `withoutCaption`). */ |
| 236 | withoutCaption?: boolean; |
| 237 | /** |
| 238 | * Sent with the caption above the widget (`show_caption_above_media`, layer 233's `invert_media`; channel.json |
| 239 | * `captionAbove`): the client draws its time over the widget as without a caption (docs/sdk-v1.md §2.17). |
| 240 | */ |
| 241 | captionAbove?: boolean; |
| 242 | } |
| 243 |
| 244 | const sha = (...parts: (string | Buffer)[]) => { |
| 245 | const h = crypto.createHash('sha256'); |
| 246 | for (const p of parts) h.update(p).update('\0'); |
| 247 | return h.digest('hex').slice(0, 16); |
| 248 | }; |
| 249 | const escapeHtml = (s: string) => s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>'); |
| 250 | const zlibSize = (b: Buffer) => zlib.deflateSync(b, { level: 9 }).length; |
| 251 | /** |
| 252 | * The widget's message caption: its key, which the forwarded copy keeps; none for a case of the client's time over the |
| 253 | * widget (docs/sdk-v1.md §2.17), which a caption below would move into its own line; above the widget for |
| 254 | * `captionAbove` (the Bot API's show_caption_above_media, layer 233's invert_media). |
| 255 | */ |
| 256 | const docCaption = (p: Post): { caption?: string; show_caption_above_media?: boolean } => |
| 257 | p.withoutCaption ? {} : { caption: p.key.replace('@', ' · '), ...(p.captionAbove ? { show_caption_above_media: true } : {}) }; |
| 258 | const baseKey = (key: string) => key.replace(/@.*/, ''); |
| 259 | /** |
| 260 | * The size anchors as the test bot once read them from the document's file name, before sendWidget: kept in the |
| 261 | * widget's hash so the posts already sent stay current. |
| 262 | */ |
| 263 | const docName = (p: Post) => path.basename(p.file, '.html') + (p.width || p.height ? `-${p.width}x${p.height}` : '') + '.html'; |
| 264 |
| 265 | function description(title: string, anchors: string, body: string) { |
| 266 | const head = `<b>${escapeHtml(title)}</b>${anchors ? ` · ${escapeHtml(anchors)}` : ''}\n`; |
| 267 | const room = TEXT_MAX - head.length - 16; |
| 268 | let text = body; |
| 269 | while (escapeHtml(text).length > room) text = text.slice(0, Math.floor(text.length * 0.9)).trimEnd() + '…'; |
| 270 | return head + escapeHtml(text); |
| 271 | } |
| 272 |
| 273 | function pngSize(file: string) { |
| 274 | const b = fs.readFileSync(file); |
| 275 | if (b.length < 24 || b.toString('latin1', 12, 16) !== 'IHDR') die(`${file} is not a PNG`); |
| 276 | return { w: b.readUInt32BE(16), h: b.readUInt32BE(20), bytes: b.length }; |
| 277 | } |
| 278 |
| 279 | function photo(file: string, key: string): Photo { |
| 280 | const { w, h, bytes } = pngSize(file); |
| 281 | const why = |
| 282 | bytes > PHOTO.bytes ? 'over 10 MB' : |
| 283 | w + h > PHOTO.sum ? 'width + height over 10000' : |
| 284 | Math.max(w, h) / Math.min(w, h) > PHOTO.ratio ? 'aspect ratio over 20' : |
| 285 | Math.max(w, h) > PHOTO.side ? `longer than ${PHOTO.side} px (the photo would be shrunk)` : false; |
| 286 | const label = `${key.replace(/@.*/, '')} · reference${file.endsWith('.dark.png') ? ', dark' : /\.(light)\.png$/.test(file) ? ', light' : ''}`; |
| 287 | return { file, w, h, bytes, asDocument: why, label }; |
| 288 | } |
| 289 |
| 290 | function channelPosts(): Post[] { |
| 291 | const channel = JSON.parse(fs.readFileSync(path.join(CONF, 'channel.json'), 'utf8')) as { |
| 292 | posts: { widget: string; width: number; height: number; caption: string; photos: string[]; variant?: string; message?: Record<string, unknown>; withoutCaption?: boolean; captionAbove?: boolean }[]; |
| 293 | }; |
| 294 | const prefixes = TOPICS.filter((t) => t.channel).sort((a, b) => b.channel!.length - a.channel!.length); |
| 295 | const out: Post[] = []; |
| 296 | const special: string[] = []; |
| 297 | for (const p of channel.posts) { |
| 298 | // A post that needs more than a plain widget in the private chat (the flags, the state, the group, the inline |
| 299 | // results: layer 233) is scripts/conformance/test-bot.ts --post's. |
| 300 | const m = p.message ?? {}; |
| 301 | if (Object.keys(m).some((k) => !['kind', 'view', 'forward'].includes(k)) || (m.kind && m.kind !== 'private' && m.kind !== 'copy')) { |
| 302 | special.push(`${p.widget.replace(/\.html$/, '')}${p.variant ? ` --variant ${p.variant}` : ''}`); |
| 303 | continue; |
| 304 | } |
| 305 | const topic = prefixes.find((t) => p.widget.startsWith(t.channel!)); |
| 306 | if (!topic) die(`channel.json: no topic for ${p.widget}`); |
| 307 | const id = p.widget.replace(/\.html$/, ''); |
| 308 | const file = path.join(CONF, p.widget); |
| 309 | const html = fs.readFileSync(file); |
| 310 | const body = p.caption.startsWith(`${id} · `) ? p.caption.slice(id.length + 3) : p.caption; |
| 311 | out.push({ |
| 312 | key: (p.width || p.height ? `${id}@${p.width}x${p.height}` : id) + (p.variant ? `@${p.variant}` : ''), topic: topic.name, file, width: p.width, height: p.height, html, zlib: zlibSize(html), |
| 313 | text: body, photos: p.photos.map((f) => photo(path.join(CONF, f), id)), hash: { widget: '', description: '', photos: '' }, |
| 314 | ...(p.withoutCaption ? { withoutCaption: true } : {}), |
| 315 | ...(p.captionAbove ? { captionAbove: true } : {}), |
| 316 | }); |
| 317 | } |
| 318 | if (special.length) console.log(`${special.length} posts need layer-233 fields (flags, state, a group, inline results) and are left to the test bot: corepack pnpm tsx scripts/conformance/test-bot.ts --post <id> [--variant <kind>]\n ${special.join('\n ')}`); |
| 319 | return out; |
| 320 | } |
| 321 |
| 322 | function walk(dir: string): string[] { |
| 323 | return fs.readdirSync(dir, { withFileTypes: true }) |
| 324 | .sort((a, b) => a.name.localeCompare(b.name)) |
| 325 | .flatMap((e) => (e.isDirectory() ? walk(path.join(dir, e.name)) : [path.join(dir, e.name)])); |
| 326 | } |
| 327 |
| 328 | /** A corpus topic: every widget that fits a mini-widget; the rest are listed as left out. */ |
| 329 | function corpusPosts(t: TopicSpec, skipped: string[]): Post[] { |
| 330 | const dir = path.join(ROOT, t.corpus!); |
| 331 | const out: Post[] = []; |
| 332 | for (const file of walk(dir).filter((f) => f.endsWith('.html'))) { |
| 333 | const key = path.relative(path.join(ROOT, 'corpus'), file).split(path.sep).join('/').replace(/\.html$/, '').replace('generated/with-profile/', 'generated/'); |
| 334 | const html = fs.readFileSync(file); |
| 335 | const packed = zlibSize(html); |
| 336 | if (html.length > MAX_RAW || packed > MAX_ZLIB) { |
| 337 | skipped.push(`${key} (${(html.length / 1024).toFixed(1)} KB, ${packed} B zlib)`); |
| 338 | continue; |
| 339 | } |
| 340 | const src = html.toString('utf8'); |
| 341 | const idea = /^\s*idea:\s*(.+)$/m.exec(src)?.[1] ?? /<title>([^<]*)<\/title>/i.exec(src)?.[1] ?? ''; |
| 342 | const post = { key, topic: t.name, file, width: 0, height: 0, html, zlib: packed, text: idea.trim(), photos: [], hash: { widget: '', description: '', photos: '' } }; |
| 343 | if (!t.withoutCaption) { out.push(post); continue; } |
| 344 | // `caption: none, below, above`: one post per placement (the triple of corpus/safe-area); else without a caption. |
| 345 | const placements = /^\s*caption:\s*(.+)$/m.exec(src)?.[1].split(',').map((s) => s.trim()) ?? ['none']; |
| 346 | for (const at of placements) { |
| 347 | if (at === 'none') out.push({ ...post, withoutCaption: true, text: `${post.text} Posted without a caption.` }); |
| 348 | else if (at === 'below') out.push({ ...post, key: `${key}@caption-below`, text: `${post.text} Posted with a caption below the widget.` }); |
| 349 | else if (at === 'above') out.push({ ...post, key: `${key}@caption-above`, captionAbove: true, text: `${post.text} Posted with a caption above the widget (invert_media).` }); |
| 350 | else die(`${key}: unknown caption placement "${at}" (none, below, above)`); |
| 351 | } |
| 352 | } |
| 353 | return out; |
| 354 | } |
| 355 |
| 356 | function finish(p: Post): Post { |
| 357 | const anchors = p.width || p.height ? `width ${p.width}, height ${p.height}` : ''; |
| 358 | p.text = description(baseKey(p.key), anchors, p.text); |
| 359 | p.hash = { |
| 360 | // `sendWidget` with the caption above: a caption-above post sent as a document came out with its caption below. |
| 361 | widget: sha(p.html, docName(p), docCaption(p).caption ?? '', ...(p.captionAbove ? ['caption above', 'sendWidget'] : []), DIRECT ? 'direct' : 'forward'), |
| 362 | description: sha(p.text), |
| 363 | photos: sha(...p.photos.flatMap((f) => [fs.readFileSync(f.file), f.label, f.asDocument ? 'document' : 'photo'])), |
| 364 | }; |
| 365 | return p; |
| 366 | } |
| 367 |
| 368 | // ---- the Bot API |
| 369 |
| 370 | class ApiError extends Error { |
| 371 | constructor(readonly method: string, readonly code: number, readonly description: string) { |
| 372 | super(`${method}: ${code} ${description}`); |
| 373 | } |
| 374 | } |
| 375 |
| 376 | let cfg: Config; |
| 377 | const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); |
| 378 | const scrub = (s: string) => (cfg?.token ? s.split(cfg.token).join('<token>') : s); |
| 379 | type Upload = { file: string; name: string; type: string }; |
| 380 |
| 381 | async function api<T>(method: string, params: Record<string, unknown>, files: Record<string, Upload> = {}): Promise<T> { |
| 382 | for (let attempt = 1; ; attempt++) { |
| 383 | let body: FormData | string; |
| 384 | const headers: Record<string, string> = {}; |
| 385 | if (Object.keys(files).length) { |
| 386 | const form = new FormData(); |
| 387 | for (const [k, v] of Object.entries(params)) if (v !== undefined) form.append(k, typeof v === 'string' ? v : JSON.stringify(v)); |
| 388 | for (const [k, f] of Object.entries(files)) form.append(k, new Blob([fs.readFileSync(f.file)], { type: f.type }), f.name); |
| 389 | body = form; |
| 390 | } else { |
| 391 | body = JSON.stringify(params); |
| 392 | headers['content-type'] = 'application/json'; |
| 393 | } |
| 394 | let res: { ok: boolean; result?: T; error_code?: number; description?: string; parameters?: { retry_after?: number } }; |
| 395 | try { |
| 396 | const r = await fetch(`${cfg.base}/${method}`, { method: 'POST', body, headers }); |
| 397 | res = await r.json(); |
| 398 | } catch (e) { |
| 399 | const msg = scrub(String((e as Error)?.cause ?? e)); |
| 400 | if (attempt >= 4) throw new Error(`${method}: ${msg}`); |
| 401 | console.warn(` ${method}: ${msg}; retrying`); |
| 402 | await sleep(2000 * attempt); |
| 403 | continue; |
| 404 | } |
| 405 | if (res.ok) return res.result as T; |
| 406 | const code = res.error_code ?? 0; |
| 407 | if (code === 429 && attempt < 8) { |
| 408 | const wait = (res.parameters?.retry_after ?? 5) + 1; |
| 409 | console.warn(` ${method}: flood wait ${wait} s`); |
| 410 | await sleep(wait * 1000); |
| 411 | continue; |
| 412 | } |
| 413 | if (code >= 500 && attempt < 4) { |
| 414 | await sleep(2000 * attempt); |
| 415 | continue; |
| 416 | } |
| 417 | throw new ApiError(method, code, scrub(res.description ?? 'unknown error')); |
| 418 | } |
| 419 | } |
| 420 |
| 421 | /** Widgets go straight into the group (TW_BOT_DIRECT=1), not through the private chat. */ |
| 422 | let DIRECT = false; |
| 423 | const nextSend: Record<'group' | 'user', number> = { group: 0, user: 0 }; |
| 424 | /** Waits for the chat's next slot and books `n` messages. */ |
| 425 | async function pace(chat: 'group' | 'user', n = 1) { |
| 426 | const wait = nextSend[chat] - Date.now(); |
| 427 | if (wait > 0) await sleep(wait); |
| 428 | nextSend[chat] = Math.max(Date.now(), nextSend[chat]) + PACE_MS[chat] * n; |
| 429 | } |
| 430 |
| 431 | interface Message { message_id: number } |
| 432 | /** --verbose: what the server made of a widget message, without the chat and sender objects and the widget's HTML. */ |
| 433 | const brief = (m: Message) => |
| 434 | JSON.stringify(m, (k, v) => (['chat', 'from', 'sender_chat', 'forward_from', 'forward_origin', 'reply_to_message', 'html'].includes(k) ? undefined : v)); |
| 435 |
| 436 | async function sendDescription(thread: number, p: Post) { |
| 437 | await pace('group'); |
| 438 | const m = await api<Message>('sendMessage', { |
| 439 | chat_id: cfg.group, message_thread_id: thread, text: p.text, parse_mode: 'HTML', |
| 440 | link_preview_options: { is_disabled: true }, disable_notification: true, |
| 441 | }); |
| 442 | return m.message_id; |
| 443 | } |
| 444 |
| 445 | /** The widget: into the tester's private chat, the only place a bot may send one, or straight into the topic. */ |
| 446 | async function sendWidget(p: Post, thread?: number) { |
| 447 | await pace(thread === undefined ? 'user' : 'group'); |
| 448 | const m = await api<Message>('sendWidget', { |
| 449 | ...(thread === undefined ? { chat_id: cfg.user } : { chat_id: cfg.group, message_thread_id: thread }), |
| 450 | html: p.html.toString('utf8'), |
| 451 | ...(p.width > 0 ? { width: p.width } : {}), |
| 452 | ...(p.height > 0 ? { height: p.height } : {}), |
| 453 | ...docCaption(p), |
| 454 | disable_notification: true, |
| 455 | }); |
| 456 | if (VERBOSE) console.log(` sendWidget → ${brief(m)}`); |
| 457 | return m.message_id; |
| 458 | } |
| 459 |
| 460 | /** The original, forwarded into the topic (forwarding a widget is allowed into any chat). */ |
| 461 | async function forwardWidget(thread: number, original: number) { |
| 462 | await pace('group'); |
| 463 | const m = await api<Message>('forwardMessage', { |
| 464 | chat_id: cfg.group, message_thread_id: thread, from_chat_id: cfg.user, message_id: original, disable_notification: true, |
| 465 | }); |
| 466 | if (VERBOSE) console.log(` forwardMessage → ${brief(m)}`); |
| 467 | return m.message_id; |
| 468 | } |
| 469 |
| 470 | const photoUpload = (f: Photo): Upload => ({ file: f.file, name: path.basename(f.file), type: 'image/png' }); |
| 471 | const asDocuments = (p: Post) => p.photos.some((f) => f.asDocument); |
| 472 |
| 473 | async function sendPhotos(thread: number, p: Post): Promise<number[]> { |
| 474 | if (!p.photos.length) return []; |
| 475 | const doc = asDocuments(p); |
| 476 | await pace('group', p.photos.length); |
| 477 | if (p.photos.length === 1) { |
| 478 | const f = p.photos[0]; |
| 479 | const m = await api<Message>( |
| 480 | doc ? 'sendDocument' : 'sendPhoto', |
| 481 | { chat_id: cfg.group, message_thread_id: String(thread), caption: f.label, disable_notification: 'true' }, |
| 482 | { [doc ? 'document' : 'photo']: photoUpload(f) }, |
| 483 | ); |
| 484 | return [m.message_id]; |
| 485 | } |
| 486 | const media = p.photos.map((f, i) => ({ type: doc ? 'document' : 'photo', media: `attach://p${i}`, caption: f.label })); |
| 487 | const ms = await api<Message[]>( |
| 488 | 'sendMediaGroup', |
| 489 | { chat_id: cfg.group, message_thread_id: String(thread), media, disable_notification: 'true' }, |
| 490 | Object.fromEntries(p.photos.map((f, i) => [`p${i}`, photoUpload(f)])), |
| 491 | ); |
| 492 | return ms.map((m) => m.message_id); |
| 493 | } |
| 494 |
| 495 | async function editPhotos(rec: PostRecord, p: Post) { |
| 496 | const doc = asDocuments(p); |
| 497 | for (const [i, f] of p.photos.entries()) { |
| 498 | await pace('group'); |
| 499 | await api('editMessageMedia', { |
| 500 | chat_id: cfg.group, message_id: String(rec.photos[i]), |
| 501 | media: { type: doc ? 'document' : 'photo', media: 'attach://p', caption: f.label }, |
| 502 | }, { p: photoUpload(f) }); |
| 503 | } |
| 504 | } |
| 505 |
| 506 | /** Deletes the bot's own messages; returns the ones the server refused to delete. */ |
| 507 | async function deleteMessages(chat: 'group' | 'user', ids: number[]): Promise<number[]> { |
| 508 | const chatId = chat === 'group' ? cfg.group : cfg.user; |
| 509 | const failed: number[] = []; |
| 510 | for (let i = 0; i < ids.length; i += 100) { |
| 511 | const chunk = ids.slice(i, i + 100); |
| 512 | try { |
| 513 | await pace(chat); |
| 514 | await api('deleteMessages', { chat_id: chatId, message_ids: chunk }); |
| 515 | } catch { |
| 516 | // One refused message fails the whole call: try them one by one. |
| 517 | for (const id of chunk) { |
| 518 | try { |
| 519 | await pace(chat); |
| 520 | await api('deleteMessage', { chat_id: chatId, message_id: id }); |
| 521 | } catch (e) { |
| 522 | if (e instanceof ApiError && /not found/i.test(e.description)) continue; // already gone |
| 523 | failed.push(id); |
| 524 | console.warn(` could not delete message ${id} in the ${chat === 'group' ? 'group' : 'private chat'}: ${(e as Error).message}`); |
| 525 | } |
| 526 | } |
| 527 | } |
| 528 | } |
| 529 | return failed; |
| 530 | } |
| 531 |
| 532 | /** Messages a --reset could not delete: kept in the group's `orphans`, which every --reset tries again. */ |
| 533 | function keepOrphans(gs: GroupState, chat: 'group' | 'user', tried: number[], failed: number[]) { |
| 534 | const orphans = (gs.orphans ??= { group: [], user: [] }); |
| 535 | orphans[chat] = [...new Set([...orphans[chat].filter((id) => !tried.includes(id)), ...failed])]; |
| 536 | } |
| 537 |
| 538 | const groupIds = (r: PostRecord) => [r.description, r.widget, ...r.photos].filter((x): x is number => x !== undefined); |
| 539 |
| 540 | // ---- the plan |
| 541 |
| 542 | type Step = |
| 543 | | { kind: 'skip'; post: Post } |
| 544 | | { kind: 'edit'; post: Post; rec: PostRecord; text: boolean; photos: boolean } |
| 545 | | { kind: 'send'; post: Post; repost: boolean } |
| 546 | | { kind: 'delete'; rec: PostRecord }; |
| 547 |
| 548 | /** |
| 549 | * One topic: the posts in place up to the first one that differs (a different |
| 550 | * or changed widget, a different picture count or kind, an incomplete post) |
| 551 | * are skipped or edited; from there every recorded post is deleted and the |
| 552 | * wanted ones are sent again, in order. With --only both lists hold only the |
| 553 | * matching posts, and the others stay where they are. |
| 554 | */ |
| 555 | function planTopic(want: Post[], recs: PostRecord[]): Step[] { |
| 556 | const fits = (r: PostRecord | undefined, p: Post) => |
| 557 | r && r.complete && r.key === p.key && r.hash.widget === p.hash.widget && r.photos.length === p.photos.length && |
| 558 | !!r.photosAsDocuments === asDocuments(p); |
| 559 | let i = 0; |
| 560 | while (i < want.length && fits(recs[i], want[i])) i++; |
| 561 | const steps: Step[] = []; |
| 562 | for (let j = 0; j < i; j++) { |
| 563 | const text = recs[j].hash.description !== want[j].hash.description; |
| 564 | const photos = recs[j].hash.photos !== want[j].hash.photos; |
| 565 | steps.push(text || photos ? { kind: 'edit', post: want[j], rec: recs[j], text, photos } : { kind: 'skip', post: want[j] }); |
| 566 | } |
| 567 | const tail = recs.slice(i); |
| 568 | for (const r of tail) steps.push({ kind: 'delete', rec: r }); |
| 569 | for (const p of want.slice(i)) steps.push({ kind: 'send', post: p, repost: tail.some((r) => r.key === p.key) }); |
| 570 | return steps; |
| 571 | } |
| 572 |
| 573 | // ---- main |
| 574 |
| 575 | async function check() { |
| 576 | const me = await api<{ id: number; username: string }>('getMe', {}); |
| 577 | console.log(`bot: @${me.username}`); |
| 578 | const chat = await api<{ type: string; title?: string; is_forum?: boolean }>('getChat', { chat_id: cfg.group }); |
| 579 | const problems: string[] = []; |
| 580 | console.log(`group: "${chat.title}", ${chat.type}${chat.is_forum ? ', topics on' : ''}`); |
| 581 | if (chat.type !== 'supergroup' || !chat.is_forum) problems.push('the group must be a supergroup with topics turned on'); |
| 582 | const member = await api<{ status: string; can_manage_topics?: boolean; can_delete_messages?: boolean }>('getChatMember', { chat_id: cfg.group, user_id: me.id }); |
| 583 | console.log(`bot in the group: ${member.status}${member.status === 'administrator' ? `, manage topics ${member.can_manage_topics ? 'yes' : 'no'}, delete messages ${member.can_delete_messages ? 'yes' : 'no'}` : ''}`); |
| 584 | if (member.status !== 'administrator' && member.status !== 'creator') problems.push('the bot must be an admin of the group'); |
| 585 | else if (!member.can_manage_topics) problems.push('the bot needs the Manage topics right'); |
| 586 | else if (!member.can_delete_messages) problems.push('the bot has no Delete messages right: --reset may fail for old messages'); |
| 587 | if (cfg.direct) console.log('widgets: straight into the group'); |
| 588 | else { |
| 589 | try { |
| 590 | const user = await api<{ type: string }>('getChat', { chat_id: cfg.user }); |
| 591 | console.log(`widgets: through the tester's private chat, ${user.type === 'private' ? 'reachable' : user.type}`); |
| 592 | } catch (e) { |
| 593 | problems.push(`the tester's private chat is not reachable (${(e as Error).message}): the tester has to start the bot first`); |
| 594 | } |
| 595 | } |
| 596 | for (const p of problems) console.log(` ! ${p}`); |
| 597 | return problems.length === 0; |
| 598 | } |
| 599 |
| 600 | function describeSend(p: Post) { |
| 601 | const pics = p.photos.map((f) => `${f.w}×${f.h}${f.asDocument ? ` as a document: ${f.asDocument}` : ''}`); |
| 602 | return `widget ${p.zlib} B zlib${p.withoutCaption ? ' without a caption' : p.captionAbove ? ' with the caption above' : ''}${pics.length ? ` · ${pics.length === 1 ? 'picture' : 'pictures'} ${pics.join(', ')}` : ''}${p.width || p.height ? ` · as ${docName(p)}` : ''}`; |
| 603 | } |
| 604 |
| 605 | async function main() { |
| 606 | const config = loadConfig(); |
| 607 | if (!config && !DRY) die(`no bot config: put TW_BOT_TOKEN, TW_BOT_USER and TW_BOT_GROUP into ${path.join(CONFIG_DIR, 'test-bot.env')} (or the environment)`); |
| 608 | if (config) cfg = config; |
| 609 | DIRECT = !!config?.direct; |
| 610 | const online = !!config?.token; |
| 611 | const state = loadState(); |
| 612 | const gs: GroupState = (config && state.groups[config.group]) || { topics: {} }; |
| 613 |
| 614 | // What each selected topic should hold. |
| 615 | const all = channelPosts(); |
| 616 | const skipped: Record<string, string[]> = {}; |
| 617 | const want: Record<string, Post[]> = {}; |
| 618 | for (const t of SELECTED) { |
| 619 | skipped[t.name] = []; |
| 620 | const posts = t.channel ? all.filter((p) => p.topic === t.name) : corpusPosts(t, skipped[t.name]); |
| 621 | want[t.name] = posts.map(finish).filter((p) => selects(p.key)); |
| 622 | } |
| 623 |
| 624 | if (RESET) { |
| 625 | const orphans = gs.orphans ?? { group: [], user: [] }; |
| 626 | if (orphans.group.length + orphans.user.length) { |
| 627 | console.log(`orphans: ${orphans.group.length} in the group, ${orphans.user.length} in the private chat`); |
| 628 | if (!DRY) { |
| 629 | const group = [...orphans.group], user = [...orphans.user]; |
| 630 | keepOrphans(gs, 'group', group, await deleteMessages('group', group)); |
| 631 | keepOrphans(gs, 'user', user, await deleteMessages('user', user)); |
| 632 | saveState(state); |
| 633 | } |
| 634 | } |
| 635 | for (const t of SELECTED) { |
| 636 | const tr = gs.topics[t.name]; |
| 637 | if (!tr) continue; |
| 638 | const recs = tr.posts.filter((r) => selects(r.key)); |
| 639 | console.log(`${t.name}: delete ${recs.length} post(s)${DELETE_TOPICS && !ONLY ? ' and the topic' : ''}`); |
| 640 | if (DRY) continue; |
| 641 | const group = recs.flatMap(groupIds), user = recs.flatMap((r) => (r.private ? [r.private] : [])); |
| 642 | keepOrphans(gs, 'group', group, await deleteMessages('group', group)); |
| 643 | keepOrphans(gs, 'user', user, await deleteMessages('user', user)); |
| 644 | tr.posts = tr.posts.filter((r) => !recs.includes(r)); |
| 645 | if (DELETE_TOPICS && !ONLY) { |
| 646 | try { |
| 647 | await api('deleteForumTopic', { chat_id: cfg.group, message_thread_id: tr.threadId }); |
| 648 | } catch (e) { |
| 649 | console.warn(` could not delete the topic: ${(e as Error).message}`); |
| 650 | } |
| 651 | delete gs.topics[t.name]; |
| 652 | } |
| 653 | state.groups[cfg.group] = gs; |
| 654 | saveState(state); |
| 655 | } |
| 656 | return; |
| 657 | } |
| 658 |
| 659 | // The plan. |
| 660 | const plans = SELECTED.map((t) => { |
| 661 | const recs = (gs.topics[t.name]?.posts ?? []).filter((r) => selects(r.key)); |
| 662 | // --rebuild: the topic goes with everything in it, and every post is sent again. |
| 663 | if (REBUILD && gs.topics[t.name]) return { t, rebuild: true, steps: want[t.name].map((p): Step => ({ kind: 'send', post: p, repost: true })) }; |
| 664 | return { t, rebuild: false, steps: planTopic(want[t.name], recs) }; |
| 665 | }); |
| 666 | let groupMsgs = 0, userMsgs = 0, sends = 0; |
| 667 | for (const { t, steps, rebuild } of plans) { |
| 668 | const exists = gs.topics[t.name]; |
| 669 | console.log(`\n${t.name}${rebuild ? ' (rebuilt: the topic is deleted with everything in it, then posted again)' : exists ? '' : ' (new topic)'}: ${want[t.name].length} post(s)`); |
| 670 | for (const s of steps) { |
| 671 | if (s.kind === 'delete') { |
| 672 | // A tail is deleted only by a run that also sends its first post again. |
| 673 | console.log(` - ${s.rec.key} ${sends >= LIMIT ? 'to delete (after --limit)' : `delete${s.rec.complete ? '' : ' (incomplete)'}`}`); |
| 674 | continue; |
| 675 | } |
| 676 | const p = s.post; |
| 677 | if (s.kind === 'skip') console.log(` = ${p.key}`); |
| 678 | else if (s.kind === 'edit') console.log(` ~ ${p.key} edit ${[s.text && 'description', s.photos && 'picture'].filter(Boolean).join(' + ')}`); |
| 679 | else if (sends >= LIMIT) console.log(` · ${p.key} (after --limit)`); |
| 680 | else { |
| 681 | sends++; |
| 682 | groupMsgs += 2 + p.photos.length; |
| 683 | if (!DIRECT) userMsgs += 1; |
| 684 | console.log(` ${s.repost ? '↻' : '+'} ${p.key} ${describeSend(p)}`); |
| 685 | } |
| 686 | } |
| 687 | for (const k of skipped[t.name]) console.log(` x ${k} does not fit a mini-widget, left out`); |
| 688 | } |
| 689 | const minutes = Math.ceil((groupMsgs * PACE_MS.group) / 60000); |
| 690 | console.log(`\nto send: ${sends} post(s), ${groupMsgs} message(s) in the group${DIRECT ? '' : ` and ${userMsgs} in the private chat`}, about ${minutes} min at 20 a minute`); |
| 691 |
| 692 | if (!online) { |
| 693 | console.log(`\nno bot ${config ? 'token' : 'config'} (${opt('--config') ?? path.join(CONFIG_DIR, 'test-bot.env')}): plan only`); |
| 694 | return; |
| 695 | } |
| 696 | const ok = await check(); |
| 697 | if (DRY) return; |
| 698 | if (!ok) die('fix the problems above first'); |
| 699 |
| 700 | sends = 0; |
| 701 | state.groups[cfg.group] = gs; |
| 702 | for (const { t, steps, rebuild } of plans) { |
| 703 | let tr: TopicRecord | undefined = gs.topics[t.name]; |
| 704 | const pending = steps.some((s) => s.kind === 'edit' || (s.kind !== 'skip' && sends < LIMIT)); |
| 705 | if (!pending) continue; |
| 706 | if (tr && rebuild) { |
| 707 | await pace('group'); |
| 708 | await api('deleteForumTopic', { chat_id: cfg.group, message_thread_id: tr.threadId }); |
| 709 | const user = tr.posts.flatMap((r) => (r.private ? [r.private] : [])); |
| 710 | keepOrphans(gs, 'user', user, await deleteMessages('user', user)); |
| 711 | delete gs.topics[t.name]; |
| 712 | tr = undefined; |
| 713 | saveState(state); |
| 714 | console.log(`\n${t.name}: topic deleted`); |
| 715 | } |
| 716 | if (!tr) { |
| 717 | await pace('group'); |
| 718 | const topic = await api<{ message_thread_id: number }>('createForumTopic', { chat_id: cfg.group, name: t.name, icon_color: t.color }); |
| 719 | tr = gs.topics[t.name] = { threadId: topic.message_thread_id, posts: [] }; |
| 720 | saveState(state); |
| 721 | console.log(`\n${t.name}: topic created`); |
| 722 | } else console.log(`\n${t.name}`); |
| 723 | const thread = tr.threadId; |
| 724 | let refused = 0; |
| 725 | for (const s of steps) { |
| 726 | if (s.kind === 'skip') continue; |
| 727 | if (s.kind === 'delete') { |
| 728 | if (sends >= LIMIT) break; |
| 729 | const failed = await deleteMessages('group', groupIds(s.rec)); |
| 730 | const failedPrivate = s.rec.private ? await deleteMessages('user', [s.rec.private]) : []; |
| 731 | if (failed.length || failedPrivate.length) { |
| 732 | // What is still there stays recorded, as an incomplete post the next run deletes again. |
| 733 | const r = s.rec; |
| 734 | Object.assign(r, { |
| 735 | complete: false, |
| 736 | description: failed.includes(r.description!) ? r.description : undefined, |
| 737 | widget: failed.includes(r.widget!) ? r.widget : undefined, |
| 738 | photos: r.photos.filter((id) => failed.includes(id)), |
| 739 | private: failedPrivate.length ? r.private : undefined, |
| 740 | }); |
| 741 | refused += failed.length + failedPrivate.length; |
| 742 | } else tr.posts = tr.posts.filter((r) => r !== s.rec); |
| 743 | saveState(state); |
| 744 | console.log(` - ${s.rec.key}${failed.length || failedPrivate.length ? ' (not deleted)' : ''}`); |
| 745 | continue; |
| 746 | } |
| 747 | // Posting again behind messages that could not be deleted would leave both copies in the topic. |
| 748 | if (refused) { |
| 749 | console.error(` ${t.name}: ${refused} old message(s) could not be deleted, so nothing is posted again here. Delete them by hand, or run with --rebuild --topic "${t.name}" (deletes the topic with everything in it and posts it again).`); |
| 750 | break; |
| 751 | } |
| 752 | const p = s.post; |
| 753 | if (s.kind === 'edit') { |
| 754 | if (s.text) { |
| 755 | await pace('group'); |
| 756 | await api('editMessageText', { |
| 757 | chat_id: cfg.group, message_id: s.rec.description, text: p.text, parse_mode: 'HTML', link_preview_options: { is_disabled: true }, |
| 758 | }); |
| 759 | } |
| 760 | if (s.photos) await editPhotos(s.rec, p); |
| 761 | s.rec.hash = p.hash; |
| 762 | saveState(state); |
| 763 | console.log(` ~ ${p.key}`); |
| 764 | continue; |
| 765 | } |
| 766 | if (sends >= LIMIT) break; |
| 767 | sends++; |
| 768 | const rec: PostRecord = { key: p.key, hash: p.hash, complete: false, photos: [] }; |
| 769 | tr.posts.push(rec); |
| 770 | rec.description = await sendDescription(thread, p); |
| 771 | saveState(state); |
| 772 | if (DIRECT) rec.widget = await sendWidget(p, thread); |
| 773 | else { |
| 774 | rec.private = await sendWidget(p); |
| 775 | saveState(state); |
| 776 | rec.widget = await forwardWidget(thread, rec.private); |
| 777 | } |
| 778 | saveState(state); |
| 779 | rec.photos = await sendPhotos(thread, p); |
| 780 | if (asDocuments(p)) rec.photosAsDocuments = true; |
| 781 | rec.complete = true; |
| 782 | saveState(state); |
| 783 | console.log(` ${s.repost ? '↻' : '+'} ${p.key}`); |
| 784 | } |
| 785 | } |
| 786 | console.log('\ndone'); |
| 787 | } |
| 788 |
| 789 | main().catch((e) => { |
| 790 | console.error(`publish-channel: ${scrub(e instanceof Error ? e.message : String(e))}`); |
| 791 | if (e instanceof ApiError && /thread not found|TOPIC_DELETED|TOPIC_CLOSED/i.test(e.description)) { |
| 792 | console.error('the topic is gone or closed: run with --reset --topic <name> to forget it, then again to recreate it'); |
| 793 | } |
| 794 | process.exit(1); |
| 795 | }); |
| 796 |