From d7fe4d2e81c76a0374d8fa97b290614c1ca48311 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 4 Nov 2026 15:56:02 +0000 Subject: [PATCH 1/2] Automate Bot API drift detection and quality checks - scripts/check-bot-api.mjs compares the latest Bot API spec with data.js (update types, admin rights, getMe flags, scopes, setWebhook params, bot settings methods); unit-tested with a synthetic spec - Weekly "Bot API watch" workflow opens/updates a bot-api-update issue - CI on pull requests: unit tests, build, Playwright e2e with mocked API, Lighthouse audit; duplicate push runs removed - Bot API version defined once in data.js; locales use {botApiVersion} and the OG image reads it too - CLAUDE.md with the update procedure; README automation section Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Ti9i15KJoZzEDMWsyiELNj --- .github/workflows/bot-api-watch.yml | 50 +++++++++++++ .github/workflows/ci.yml | 54 +++++++++++++- .gitignore | 1 + CHANGELOG.md | 11 +++ CLAUDE.md | 18 +++++ README.md | 6 ++ lighthouserc.json | 23 ++++++ package.json | 3 +- scripts/build.mjs | 10 +++ scripts/check-bot-api.mjs | 112 ++++++++++++++++++++++++++++ scripts/images.mjs | 3 +- src/i18n/en.json | 6 +- src/i18n/es.json | 6 +- src/i18n/pt.json | 6 +- src/i18n/ru.json | 6 +- src/i18n/zh.json | 6 +- tests/check-bot-api.test.mjs | 64 ++++++++++++++++ 17 files changed, 366 insertions(+), 19 deletions(-) create mode 100644 .github/workflows/bot-api-watch.yml create mode 100644 CLAUDE.md create mode 100644 lighthouserc.json create mode 100644 scripts/check-bot-api.mjs create mode 100644 tests/check-bot-api.test.mjs diff --git a/.github/workflows/bot-api-watch.yml b/.github/workflows/bot-api-watch.yml new file mode 100644 index 0000000..e9718d3 --- /dev/null +++ b/.github/workflows/bot-api-watch.yml @@ -0,0 +1,50 @@ +name: Bot API watch + +# Weekly check of the latest Telegram Bot API spec against src/assets/js/data.js. +# Opens (or updates) an issue labelled "bot-api-update" when something is missing. +on: + schedule: + - cron: '17 6 * * 1' + workflow_dispatch: + +permissions: + contents: read + issues: write + +jobs: + check: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v5 + - uses: actions/setup-node@v5 + with: + node-version: 22 + - id: check + name: Compare with Bot API spec + run: | + set +e + node scripts/check-bot-api.mjs > report.md + code=$? + cat report.md + echo "status=$code" >> "$GITHUB_OUTPUT" + [ "$code" -le 1 ] + - name: Open or update issue + if: steps.check.outputs.status == '1' + env: + GH_TOKEN: ${{ github.token }} + run: | + gh label create bot-api-update --color 2481cc --description "Telegram Bot API changed" 2>/dev/null || true + version=$(sed -n 's/^Spec: \*\*Bot API \([0-9.]*\)\*\*.*/\1/p' report.md) + { + echo "The Telegram Bot API spec differs from \`src/assets/js/data.js\`." + echo + cat report.md + echo + echo "To update: edit \`src/assets/js/data.js\` (lists and \`BOT_API_VERSION\`), add labels to all \`src/i18n/*.json\`, then run \`npm test\` and \`node scripts/check-bot-api.mjs\`." + } > body.md + existing=$(gh issue list --label bot-api-update --state open --json number --jq '.[0].number') + if [ -n "$existing" ]; then + gh issue edit "$existing" --title "Update to Telegram Bot API $version" --body-file body.md + else + gh issue create --title "Update to Telegram Bot API $version" --label bot-api-update --body-file body.md + fi diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 45d0117..bd31164 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,13 +1,17 @@ name: CI +# Runs once per pull request update (no duplicate push runs); main is checked by the deploy workflow. on: pull_request: - push: - branches-ignore: [main] + workflow_dispatch: permissions: contents: read +concurrency: + group: ci-${{ github.ref }} + cancel-in-progress: true + jobs: test: runs-on: ubuntu-latest @@ -18,3 +22,49 @@ jobs: node-version: 22 - run: npm test - run: npm run build + - uses: actions/upload-artifact@v4 + with: + name: dist + path: dist + include-hidden-files: true + retention-days: 3 + + e2e: + needs: test + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v5 + - uses: actions/setup-node@v5 + with: + node-version: 22 + - uses: actions/download-artifact@v4 + with: + name: dist + path: dist + - name: Install Playwright + run: | + npm install --no-save playwright@1.56.1 + npx playwright install --with-deps chromium + # Mocked Bot API flows; fails on any console error or CSP violation. + - run: node scripts/screenshots.mjs --no-shots + + lighthouse: + needs: test + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v5 + - uses: actions/setup-node@v5 + with: + node-version: 22 + - uses: actions/download-artifact@v4 + with: + name: dist + path: dist + - run: npx --yes @lhci/cli@0.15.1 autorun + - if: always() + uses: actions/upload-artifact@v4 + with: + name: lighthouse-reports + path: .lighthouseci + include-hidden-files: true + retention-days: 14 diff --git a/.gitignore b/.gitignore index 87ca375..f52882b 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,4 @@ dist/ Thumbs.db .idea/ .vscode/ +.lighthouseci/ diff --git a/CHANGELOG.md b/CHANGELOG.md index 692e594..3e48c7a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,16 @@ # Changelog +## 3.1.0 — 2026-11-04 + +### Added +- `scripts/check-bot-api.mjs`: compares the latest Bot API spec with the project's reference data. +- Weekly “Bot API watch” workflow that opens an issue when the API changes. +- CI runs the end-to-end test and a Lighthouse audit on every pull request; duplicate push runs removed. +- `CLAUDE.md` with the Bot API update procedure. + +### Changed +- The Bot API version is defined once in `data.js`; translations and the OG image use it automatically. + ## 3.0.1 — 2026-10-08 ### Fixed diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..0995338 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,18 @@ +# Telegram Bot Manager — notes for agents + +Static site (GitHub Pages) that calls the Telegram Bot API from the browser. No backend, no npm dependencies. + +- Build: `npm run build` → `dist/`. Unit tests: `npm test`. E2E with mocked API: `node scripts/screenshots.mjs --no-shots` (needs Playwright). +- Deploy: every push to `main` runs `.github/workflows/pages.yml`. Work on a branch and merge via PR; CI (`ci.yml`) runs unit tests, e2e and Lighthouse on PRs. +- UI strings live in `src/i18n/{en,ru,es,pt,zh}.json`; all locales must have the same keys (tests enforce it). Write natural translations, not machine-literal ones. +- The Bot API version is defined only in `BOT_API_VERSION` in `src/assets/js/data.js`; locale strings use the `{botApiVersion}` token. +- Never commit bot tokens. Never add analytics or third-party scripts: the page handles bot tokens and has a strict CSP. + +## Updating to a new Bot API version + +1. `node scripts/check-bot-api.mjs` — lists new update types, admin rights, getMe flags, command scopes, setWebhook params and bot-settings methods (spec: PaulSonOfLars/telegram-bot-api-spec; core.telegram.org may be unreachable). +2. Update `src/assets/js/data.js`: `UPDATE_GROUPS` (mark `optIn` if the spec says it must be requested explicitly), `ADMIN_RIGHTS` (with `target`), `ME_FLAGS`, `COMMAND_SCOPES`, `BOT_API_VERSION`. +3. Add labels for every new key to all five locale files (`app.updates.*`, `app.rights.*`, `app.me.*`, `app.scopes.*`). `npm test` lists anything missing. +4. A new bot-settings method that needs its own UI (a new tab or form) is a design change: describe it in the PR instead of building it silently. +5. Update `CHANGELOG.md` and the version badge in `README.md`; bump `package.json` patch/minor version. +6. Re-run the check (must print “Up to date”), `npm test`, `npm run build`, the e2e test, then `node scripts/images.mjs` to refresh the OG image. diff --git a/README.md b/README.md index 94d227c..323101d 100644 --- a/README.md +++ b/README.md @@ -90,6 +90,12 @@ npm run build && node scripts/screenshots.mjs # e2e smoke test (Playwright + C **New Bot API version:** update `src/assets/js/data.js` (update types, admin rights, `getMe` flags) and the translations; `npm test` lists every missing label. +## Automation + +- **CI** (`.github/workflows/ci.yml`, on pull requests): unit tests, build, end-to-end test in Chromium against a mocked Bot API, and a Lighthouse audit (accessibility and best practices must stay ≥ 95/90; reports are attached to the run). +- **Bot API watch** (`.github/workflows/bot-api-watch.yml`, weekly): compares the latest Bot API spec with `src/assets/js/data.js` via `scripts/check-bot-api.mjs` and opens an issue labelled `bot-api-update` when something is missing. +- **Agent instructions** for updating the project are in [`CLAUDE.md`](CLAUDE.md). + ## FAQ **How do I check my bot's webhook?** Connect the bot and open the Webhook tab: it calls `getWebhookInfo` and explains the last error. diff --git a/lighthouserc.json b/lighthouserc.json new file mode 100644 index 0000000..152445e --- /dev/null +++ b/lighthouserc.json @@ -0,0 +1,23 @@ +{ + "ci": { + "collect": { + "staticDistDir": "./dist", + "url": [ + "http://localhost/index.html", + "http://localhost/ru/index.html", + "http://localhost/set-webhook/index.html" + ], + "numberOfRuns": 1, + "settings": { "chromeFlags": "--no-sandbox --headless=new" } + }, + "assert": { + "assertions": { + "categories:accessibility": ["error", { "minScore": 0.95 }], + "categories:best-practices": ["error", { "minScore": 0.9 }], + "categories:seo": ["warn", { "minScore": 0.9 }], + "categories:performance": ["warn", { "minScore": 0.85 }] + } + }, + "upload": { "target": "filesystem", "outputDir": ".lighthouseci" } + } +} diff --git a/package.json b/package.json index 951dc99..92e227d 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "telegram-bot-manager", - "version": "3.0.1", + "version": "3.1.0", "private": true, "description": "Free online Telegram Bot Manager: set, check and delete webhooks, edit commands, profile, menu button and admin rights right in your browser.", "type": "module", @@ -8,6 +8,7 @@ "build": "node scripts/build.mjs", "test": "node --test \"tests/*.test.mjs\"", "serve": "node scripts/serve.mjs", + "check:bot-api": "node scripts/check-bot-api.mjs", "start": "node scripts/build.mjs && node scripts/serve.mjs" }, "engines": { diff --git a/scripts/build.mjs b/scripts/build.mjs index e2c094f..eef224b 100644 --- a/scripts/build.mjs +++ b/scripts/build.mjs @@ -131,6 +131,14 @@ export function compareLocales(base, other, path = '') { return problems; } +// The Bot API version lives only in data.js; locale strings reference it as {botApiVersion}. +function fillVersion(node, version) { + if (typeof node === 'string') return node.replaceAll('{botApiVersion}', version); + if (Array.isArray(node)) return node.map((x) => fillVersion(x, version)); + if (node && typeof node === 'object') return Object.fromEntries(Object.entries(node).map(([k, v]) => [k, fillVersion(v, version)])); + return node; +} + export async function loadLocales() { const locales = {}; for (const lang of LANGS) { @@ -138,6 +146,8 @@ export async function loadLocales() { } const problems = LANGS.slice(1).flatMap((lang) => compareLocales(locales.en, locales[lang.code], lang.code)); if (problems.length) throw new Error(`Locale mismatch:\n ${problems.join('\n ')}`); + const { BOT_API_VERSION } = await import('../src/assets/js/data.js'); + for (const code of Object.keys(locales)) locales[code] = fillVersion(locales[code], BOT_API_VERSION); return locales; } diff --git a/scripts/check-bot-api.mjs b/scripts/check-bot-api.mjs new file mode 100644 index 0000000..e32c8a6 --- /dev/null +++ b/scripts/check-bot-api.mjs @@ -0,0 +1,112 @@ +// Compares the project's Bot API reference data (src/assets/js/data.js) with the latest +// machine-readable Bot API spec and reports what is missing or outdated. +// Usage: node scripts/check-bot-api.mjs [--spec path/to/api.json] [--json] +// Exit code: 0 = up to date, 1 = drift found, 2 = error. +import { readFile, readdir } from 'node:fs/promises'; +import { join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import * as data from '../src/assets/js/data.js'; + +export const SPEC_URL = 'https://raw.githubusercontent.com/PaulSonOfLars/telegram-bot-api-spec/main/api.json'; +const JS_DIR = fileURLToPath(new URL('../src/assets/js/', import.meta.url)); + +// Methods the tool deliberately does not expose (dangerous or unrelated to bot settings). +const IGNORED_METHODS = new Set(['getMyStarBalance', 'logOut', 'close']); +const BOT_SETTINGS_METHOD = /^(set|get|delete|remove)(My[A-Z]|Webhook|WebhookInfo|ChatMenuButton)/; + +const diff = (spec, ours) => ({ + added: spec.filter((x) => !ours.includes(x)), + removed: ours.filter((x) => !spec.includes(x)), +}); + +async function usedMethods() { + const files = []; + const walk = async (dir) => { + for (const entry of await readdir(dir, { withFileTypes: true })) { + const full = join(dir, entry.name); + if (entry.isDirectory()) await walk(full); + else if (entry.name.endsWith('.js')) files.push(full); + } + }; + await walk(JS_DIR); + const methods = new Set(); + for (const file of files) { + // Methods are passed either directly (api.call('getMe')) or via request objects ({ method: 'setMyName' }). + for (const m of (await readFile(file, 'utf8')).matchAll(/(?:\.call\(|method: )'([a-z]\w+)'/g)) methods.add(m[1]); + } + return [...methods]; +} + +export async function checkBotApi(spec) { + const fields = (type) => spec.types[type].fields.map((f) => f.name); + const version = spec.version.replace(/^Bot API\s*/, ''); + const used = await usedMethods(); + + const report = { + specVersion: version, + specReleaseDate: spec.release_date, + ourVersion: data.BOT_API_VERSION, + changelog: spec.changelog, + updateTypes: diff(fields('Update').filter((f) => f !== 'update_id'), data.UPDATE_TYPES), + adminRights: diff(fields('ChatAdministratorRights'), data.ADMIN_RIGHTS.map((r) => r.key)), + meFlags: diff( + spec.types.User.fields.filter((f) => f.description.includes('Returned only in getMe')).map((f) => f.name), + data.ME_FLAGS, + ), + commandScopes: diff( + spec.types.BotCommandScope.subtypes.map((t) => spec.types[t].fields.find((f) => f.name === 'type').description.match(/must be (\w+)/)[1]), + data.COMMAND_SCOPES.map((s) => s.type), + ), + setWebhookParams: diff(spec.methods.setWebhook.fields.map((f) => f.name), + ['url', 'certificate', 'ip_address', 'max_connections', 'allowed_updates', 'drop_pending_updates', 'secret_token']), + botSettingsMethods: { + added: Object.keys(spec.methods).filter((m) => BOT_SETTINGS_METHOD.test(m) && !used.includes(m) && !IGNORED_METHODS.has(m)), + removed: used.filter((m) => !spec.methods[m]), + }, + }; + const sections = Object.values(report).filter((v) => v && typeof v === 'object'); + report.upToDate = report.specVersion === report.ourVersion + && sections.every((s) => s.added.length === 0 && s.removed.length === 0); + return report; +} + +export function toMarkdown(r) { + const lines = [ + `Spec: **Bot API ${r.specVersion}** (${r.specReleaseDate}) · project: **${r.ourVersion}**`, + `Changelog: ${r.changelog}`, + '', + ]; + const labels = { + updateTypes: 'Update types (allowed_updates)', + adminRights: 'ChatAdministratorRights', + meFlags: 'getMe flags', + commandScopes: 'BotCommandScope types', + setWebhookParams: 'setWebhook parameters', + botSettingsMethods: 'Bot settings methods not used by the tool', + }; + for (const [key, label] of Object.entries(labels)) { + const { added, removed } = r[key]; + if (!added.length && !removed.length) continue; + lines.push(`### ${label}`); + if (added.length) lines.push(`- New: ${added.map((x) => `\`${x}\``).join(', ')}`); + if (removed.length) lines.push(`- Removed from spec: ${removed.map((x) => `\`${x}\``).join(', ')}`); + lines.push(''); + } + if (r.upToDate) lines.push('✅ Up to date.'); + return lines.join('\n'); +} + +if (process.argv[1] === fileURLToPath(import.meta.url)) { + const specIndex = process.argv.indexOf('--spec'); + try { + const spec = specIndex > -1 + ? JSON.parse(await readFile(process.argv[specIndex + 1], 'utf8')) + : await (await fetch(SPEC_URL)).json(); + const report = await checkBotApi(spec); + console.log(process.argv.includes('--json') ? JSON.stringify(report, null, 2) : toMarkdown(report)); + process.exitCode = report.upToDate ? 0 : 1; + } catch (error) { + console.error(`check-bot-api failed: ${error.message}`); + process.exitCode = 2; + } +} diff --git a/scripts/images.mjs b/scripts/images.mjs index 38fc210..1125549 100644 --- a/scripts/images.mjs +++ b/scripts/images.mjs @@ -3,6 +3,7 @@ import { readFile, writeFile } from 'node:fs/promises'; import { fileURLToPath } from 'node:url'; import { loadPlaywright } from './playwright.mjs'; +import { BOT_API_VERSION } from '../src/assets/js/data.js'; const root = (p) => fileURLToPath(new URL(`../${p}`, import.meta.url)); const svg = await readFile(root('src/assets/img/favicon.svg'), 'utf8'); @@ -29,7 +30,7 @@ const card = (width, height) => `

Telegram Bot
Manager

Set, check & delete webhooks, edit commands, profile, menu button and admin rights — online, in your browser.

-
setWebhookgetWebhookInfodeleteWebhooksetMyCommandsBot API 10.3
+
setWebhookgetWebhookInfodeleteWebhooksetMyCommandsBot API ${BOT_API_VERSION}
github.com/f1devbin/telegram-bot-manager `; diff --git a/src/i18n/en.json b/src/i18n/en.json index 351327f..5a66aee 100644 --- a/src/i18n/en.json +++ b/src/i18n/en.json @@ -153,11 +153,11 @@ } }, "home": { - "eyebrow": "Free · Open source · Bot API 10.3", + "eyebrow": "Free · Open source · Bot API {botApiVersion}", "h1": "Telegram Bot Manager: webhooks, commands and profile online", "lead": "Set, check and delete your bot's webhook, edit commands, name, description, avatar, menu button and default admin rights — without writing code or running scripts.", "point1": "Works right in the browser — no install, no backend", - "point2": "Supports the latest Telegram Bot API 10.3", + "point2": "Supports the latest Telegram Bot API {botApiVersion}", "point3": "Shows webhook errors with hints on how to fix them", "featuresTitle": "Everything BotFather can't do in one place", "features": [ @@ -189,7 +189,7 @@ { "icon": "🛡", "title": "Admin rights", - "text": "Default administrator rights for groups and channels, including the newest rights from Bot API 10.3." + "text": "Default administrator rights for groups and channels, including the newest rights from Bot API {botApiVersion}." }, { "icon": "🧰", diff --git a/src/i18n/es.json b/src/i18n/es.json index 55980eb..aa9ccab 100644 --- a/src/i18n/es.json +++ b/src/i18n/es.json @@ -153,11 +153,11 @@ } }, "home": { - "eyebrow": "Gratis · Código abierto · Bot API 10.3", + "eyebrow": "Gratis · Código abierto · Bot API {botApiVersion}", "h1": "Telegram Bot Manager: webhooks, comandos y perfil del bot en línea", "lead": "Configura, revisa y elimina el webhook de tu bot, edita comandos, nombre, descripción, avatar, botón de menú y permisos de administrador, sin escribir código ni ejecutar scripts.", "point1": "Funciona en el navegador: sin instalación ni backend", - "point2": "Compatible con la última Telegram Bot API 10.3", + "point2": "Compatible con la última Telegram Bot API {botApiVersion}", "point3": "Muestra los errores del webhook con pistas para solucionarlos", "featuresTitle": "Todo lo que BotFather no ofrece, en un solo lugar", "features": [ @@ -189,7 +189,7 @@ { "icon": "🛡", "title": "Permisos de admin", - "text": "Permisos de administrador por defecto para grupos y canales, incluidos los más nuevos de Bot API 10.3." + "text": "Permisos de administrador por defecto para grupos y canales, incluidos los más nuevos de Bot API {botApiVersion}." }, { "icon": "🧰", diff --git a/src/i18n/pt.json b/src/i18n/pt.json index 64e9759..5588cee 100644 --- a/src/i18n/pt.json +++ b/src/i18n/pt.json @@ -153,11 +153,11 @@ } }, "home": { - "eyebrow": "Grátis · Código aberto · Bot API 10.3", + "eyebrow": "Grátis · Código aberto · Bot API {botApiVersion}", "h1": "Telegram Bot Manager: webhooks, comandos e perfil do bot online", "lead": "Configure, verifique e exclua o webhook do seu bot, edite comandos, nome, descrição, avatar, botão de menu e permissões de administrador — sem escrever código nem rodar scripts.", "point1": "Funciona no navegador — sem instalação, sem backend", - "point2": "Compatível com a Telegram Bot API 10.3 mais recente", + "point2": "Compatível com a Telegram Bot API {botApiVersion} mais recente", "point3": "Mostra erros do webhook com dicas de como corrigi-los", "featuresTitle": "Tudo o que o BotFather não faz, em um só lugar", "features": [ @@ -189,7 +189,7 @@ { "icon": "🛡", "title": "Permissões de admin", - "text": "Permissões de administrador padrão para grupos e canais, incluindo as mais novas da Bot API 10.3." + "text": "Permissões de administrador padrão para grupos e canais, incluindo as mais novas da Bot API {botApiVersion}." }, { "icon": "🧰", diff --git a/src/i18n/ru.json b/src/i18n/ru.json index 8c5651b..b9e46cd 100644 --- a/src/i18n/ru.json +++ b/src/i18n/ru.json @@ -153,11 +153,11 @@ } }, "home": { - "eyebrow": "Бесплатно · Open source · Bot API 10.3", + "eyebrow": "Бесплатно · Open source · Bot API {botApiVersion}", "h1": "Telegram Bot Manager: вебхуки, команды и профиль бота онлайн", "lead": "Устанавливайте, проверяйте и удаляйте вебхук, редактируйте команды, имя, описание, аватар, кнопку меню и права администратора бота — без кода и скриптов.", "point1": "Работает прямо в браузере — без установки и бэкенда", - "point2": "Поддерживает актуальный Telegram Bot API 10.3", + "point2": "Поддерживает актуальный Telegram Bot API {botApiVersion}", "point3": "Показывает ошибки вебхука с подсказками, как их исправить", "featuresTitle": "Всё, чего нет в BotFather, — в одном месте", "features": [ @@ -166,7 +166,7 @@ { "icon": "📜", "title": "Редактор команд", "text": "setMyCommands в виде простого текста с проверкой — для каждой области (личные чаты, группы, админы, конкретный чат) и языка." }, { "icon": "📝", "title": "Профиль и аватар", "text": "Имя бота, короткое и полное описание на любом языке. Загрузка фото или видеоаватара и его удаление." }, { "icon": "📱", "title": "Кнопка меню", "text": "Переключайте кнопку меню между командами и вашим Mini App (Web App) — для всех чатов или для одного." }, - { "icon": "🛡", "title": "Права администратора", "text": "Права по умолчанию для групп и каналов, включая новые права из Bot API 10.3." }, + { "icon": "🛡", "title": "Права администратора", "text": "Права по умолчанию для групп и каналов, включая новые права из Bot API {botApiVersion}." }, { "icon": "🧰", "title": "Инструменты разработчика", "text": "Сырые JSON-ответы, журнал запросов и готовая команда curl для каждого действия." }, { "icon": "🌍", "title": "5 языков, тёмная тема", "text": "English, Русский, Español, Português и 简体中文. Светлая и тёмная темы, удобно на телефоне." } ], diff --git a/src/i18n/zh.json b/src/i18n/zh.json index 88f3f5a..799ee3f 100644 --- a/src/i18n/zh.json +++ b/src/i18n/zh.json @@ -153,11 +153,11 @@ } }, "home": { - "eyebrow": "免费 · 开源 · Bot API 10.3", + "eyebrow": "免费 · 开源 · Bot API {botApiVersion}", "h1": "Telegram Bot Manager:在线管理机器人 Webhook、命令和资料", "lead": "设置、检查和删除机器人的 Webhook,编辑命令、名称、描述、头像、菜单按钮和默认管理员权限——无需写代码或运行脚本。", "point1": "直接在浏览器中运行——无需安装,无需后端", - "point2": "支持最新的 Telegram Bot API 10.3", + "point2": "支持最新的 Telegram Bot API {botApiVersion}", "point3": "显示 Webhook 错误并给出修复提示", "featuresTitle": "BotFather 做不到的,这里一站搞定", "features": [ @@ -166,7 +166,7 @@ { "icon": "📜", "title": "命令编辑器", "text": "以纯文本编辑 setMyCommands 并自动校验,支持不同范围(私聊、群组、管理员、指定聊天)和语言。" }, { "icon": "📝", "title": "资料和头像", "text": "以任意语言设置机器人名称、简短描述和描述。上传或删除照片或视频头像。" }, { "icon": "📱", "title": "菜单按钮", "text": "在命令列表和你的小程序(Web App)之间切换菜单按钮,可全局设置,也可针对单个聊天。" }, - { "icon": "🛡", "title": "管理员权限", "text": "群组和频道的默认管理员权限,包括 Bot API 10.3 中的最新权限。" }, + { "icon": "🛡", "title": "管理员权限", "text": "群组和频道的默认管理员权限,包括 Bot API {botApiVersion} 中的最新权限。" }, { "icon": "🧰", "title": "开发者工具", "text": "原始 JSON 响应、请求日志,以及每个操作可直接复制的 curl 命令。" }, { "icon": "🌍", "title": "5 种语言,深色模式", "text": "English、Русский、Español、Português 和简体中文。浅色和深色主题,支持手机。" } ], diff --git a/tests/check-bot-api.test.mjs b/tests/check-bot-api.test.mjs new file mode 100644 index 0000000..ab0d414 --- /dev/null +++ b/tests/check-bot-api.test.mjs @@ -0,0 +1,64 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { readFile } from 'node:fs/promises'; +import { checkBotApi, toMarkdown } from '../scripts/check-bot-api.mjs'; +import { loadLocales, LANGS } from '../scripts/build.mjs'; +import * as data from '../src/assets/js/data.js'; + +const field = (name, description = '') => ({ name, description }); + +// Minimal spec that mirrors the project's data.js exactly. +function specFromProject() { + const scopeTypes = data.COMMAND_SCOPES.map((s) => `Scope_${s.type}`); + const types = { + Update: { fields: [field('update_id'), ...data.UPDATE_TYPES.map((t) => field(t))] }, + ChatAdministratorRights: { fields: data.ADMIN_RIGHTS.map((r) => field(r.key)) }, + User: { fields: [field('id'), ...data.ME_FLAGS.map((f) => field(f, 'Optional. Returned only in getMe.'))] }, + BotCommandScope: { subtypes: scopeTypes }, + }; + data.COMMAND_SCOPES.forEach((s, i) => { + types[scopeTypes[i]] = { fields: [field('type', `Scope type, must be ${s.type}`)] }; + }); + const methods = { + setWebhook: { fields: ['url', 'certificate', 'ip_address', 'max_connections', 'allowed_updates', 'drop_pending_updates', 'secret_token'].map((n) => field(n)) }, + }; + for (const m of ['getMe', 'getWebhookInfo', 'deleteWebhook', 'getUserProfilePhotos', 'getFile', 'getMyName', 'setMyName', + 'getMyDescription', 'setMyDescription', 'getMyShortDescription', 'setMyShortDescription', 'getMyCommands', 'setMyCommands', + 'deleteMyCommands', 'getChatMenuButton', 'setChatMenuButton', 'getMyDefaultAdministratorRights', + 'setMyDefaultAdministratorRights', 'setMyProfilePhoto', 'removeMyProfilePhoto', 'getMyStarBalance']) { + methods[m] ??= { fields: [] }; + } + return { version: `Bot API ${data.BOT_API_VERSION}`, release_date: 'today', changelog: 'url', types, methods }; +} + +test('reports up to date when spec matches data.js', async () => { + const report = await checkBotApi(specFromProject()); + assert.equal(report.upToDate, true, toMarkdown(report)); +}); + +test('detects a new version, update type, admin right and bot method', async () => { + const spec = specFromProject(); + spec.version = 'Bot API 99.0'; + spec.types.Update.fields.push(field('brand_new_update')); + spec.types.ChatAdministratorRights.fields.push(field('can_do_magic')); + spec.methods.setMyEmojiStatus = { fields: [] }; + const report = await checkBotApi(spec); + assert.equal(report.upToDate, false); + assert.deepEqual(report.updateTypes.added, ['brand_new_update']); + assert.deepEqual(report.adminRights.added, ['can_do_magic']); + assert.deepEqual(report.botSettingsMethods.added, ['setMyEmojiStatus']); + const md = toMarkdown(report); + assert.ok(md.includes('99.0') && md.includes('`brand_new_update`')); +}); + +test('Bot API version is defined only in data.js', async () => { + for (const lang of LANGS) { + const raw = await readFile(new URL(`../src/i18n/${lang.code}.json`, import.meta.url), 'utf8'); + assert.ok(!raw.includes(`Bot API ${data.BOT_API_VERSION}`), `${lang.code}.json hardcodes the version; use {botApiVersion}`); + } + const locales = await loadLocales(); + for (const lang of LANGS) { + assert.ok(locales[lang.code].home.eyebrow.includes(data.BOT_API_VERSION), `${lang.code} eyebrow gets the version`); + assert.ok(!JSON.stringify(locales[lang.code]).includes('{botApiVersion}'), `${lang.code} has unfilled token`); + } +}); From ee7bb1570acbb8e0f76775dcb811ce2215fd3063 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 4 Nov 2026 16:19:02 +0000 Subject: [PATCH 2/2] CI: run e2e on ubuntu-24.04 (Playwright 1.56 lacks 26.04 builds) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Ti9i15KJoZzEDMWsyiELNj --- .github/workflows/ci.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index bd31164..11c3ed8 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -31,7 +31,8 @@ jobs: e2e: needs: test - runs-on: ubuntu-latest + # Pinned: Playwright 1.56 has no browser builds for ubuntu-latest (26.04) yet. + runs-on: ubuntu-24.04 steps: - uses: actions/checkout@v5 - uses: actions/setup-node@v5