umbot
    Preparing search index...

    umbot recipes: ready-made solutions for common tasks

    This page is machine-translated from the Russian original. If something reads oddly, the Russian version is the source of truth — open an issue.

    Короткие законченные примеры для частых задач: эхо-навык, регистрация, игра со счётом, карточка товара, пагинация, HTTP-запрос с тайм-аутом, авторизация Алисы, кнопки с payload, логгер, NLU- и i18n-плагины, inline-режим Telegram, свои таблицы в БД, рассылка по расписанию, меню из экранов.

    In all recipes bot is a Bot instance created and configured as in the minimal example; imports are shown where a recipe uses something beyond Bot and BotController. Concepts are explained in the guide, full signatures are in the API reference.

    import { Bot, WELCOME_INTENT_NAME, FALLBACK_COMMAND } from 'umbot';
    import { fullPlatforms } from 'umbot/plugins';

    const bot = new Bot()
    .use(fullPlatforms)
    .setAppConfig({ isLocalStorage: true })
    .setAppMode('strict_prod');

    bot.addCommand(WELCOME_INTENT_NAME, ['hello'], (_, bc) => {
    bc.text = 'Hi! I repeat after you.';
    bc.buttons.addBtn('Help');
    });

    bot.addCommand(FALLBACK_COMMAND, [], (userCommand, bc) => {
    bc.text = `You said: ${userCommand}`;
    });

    bot.start('0.0.0.0', 3000);
    import { Bot, BotController, IUserData } from 'umbot';

    interface RegData extends IUserData {
    name?: string;
    age?: number;
    }

    // The trigger command — userData is not used here, no need to type it
    bot.addCommand('register', ['register'], (_, bc) => {
    bc.text = 'Enter your name:';
    bc.thisIntentName = 'reg_name';
    });

    // A step — typed through the generic parameter
    bot.addStep('reg_name', (bc: BotController<RegData>) => {
    bc.userData.name = bc.originalUserCommand ?? '';
    bc.text = `Hi, ${bc.userData.name}! How old are you?`;
    bc.thisIntentName = 'reg_age';
    });

    bot.addStep('reg_age', (bc: BotController<RegData>) => {
    const age = parseInt(bc.userCommand || '', 10);
    if (isNaN(age) || age < 1 || age > 120) {
    bc.text = 'That does not look like an age. A number from 1 to 120:';
    bc.thisIntentName = 'reg_age';
    return;
    }
    bc.userData.age = age;
    bc.text = `Done! You are ${age} years old.`;
    bc.thisIntentName = null;
    });
    import { BotController, IUserData } from 'umbot';

    interface GameData extends IUserData {
    score: number;
    level: number;
    lastPlayed?: string;
    }

    // The bc annotation — TypeScript knows about the userData fields
    bot.addCommand('play', ['play'], (_, bc: BotController<GameData>) => {
    bc.userData.score ??= 0;
    bc.userData.level ??= 1;
    bc.userData.score += 10;
    if (bc.userData.score % 100 === 0) bc.userData.level += 1;
    bc.userData.lastPlayed = new Date().toISOString();
    bc.text = `+10 points! Total: ${bc.userData.score}, level: ${bc.userData.level}`;
    bc.buttons.addBtn('Again');
    });
    bot.addCommand('show_product', ['show product'], (_, bc) => {
    if (!bc.isScreen) {
    bc.text = 'This section needs a screen. Open the skill on a device with a screen.';
    return;
    }
    bc.text = '';
    bc.tts = 'Take a look at this product';
    bc.card
    .addOneImage('https://shop.example.com/img/1.jpg', 'iPhone 15', '99 990 ₽')
    .addButton({ title: 'Buy', payload: { action: 'buy', id: 1 } });
    });
    import { SoundConstants } from 'umbot';

    bot.addCommand('win', ['victory', 'i won'], (_, bc) => {
    bc.text = 'You won!';
    // The standard victory sound (Alice/Marusia only)
    bc.tts = `${SoundConstants.S_EFFECT_HAMSTER}Hooray!${SoundConstants.S_EFFECT_END} Congratulations! ${SoundConstants.S_AUDIO_GAME_WIN} You are amazing!`;
    });
    import { Navigation, BotController, IUserData } from 'umbot';

    interface ListData extends IUserData {
    page?: number;
    }

    const items = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'];
    const nav = new Navigation<string>(3); // 3 items per page

    bot.addCommand(
    'list',
    ['список', 'дальше', 'назад'], // Navigation recognizes the Russian "next"/"back" words
    (userCommand, bc: BotController<ListData>) => {
    bc.userData.page ??= 0;
    nav.thisPage = bc.userData.page;

    const page = nav.getPageElements(items, userCommand || '');
    bc.userData.page = nav.thisPage;

    bc.text = page.map((s, i) => `${i + 1}. ${s}`).join('\n');
    for (const cap of nav.getPageNav()) {
    bc.buttons.addBtn(cap);
    }
    const info = nav.getPageInfo();
    if (info) bc.buttons.addBtn(info);
    },
    );

    // Selecting an item by name is a separate command (it fires if the user said a name rather than "next")
    bot.addCommand('select_item', items, (userCommand, bc: BotController<ListData>) => {
    nav.thisPage = bc.userData.page ?? 0;
    const selected = nav.selectedElement(items, userCommand || '', []);
    if (selected) {
    bc.text = `You selected: ${selected}`;
    } else {
    bc.text = 'There is no such item on the current page.';
    }
    });

    Для HTTP-запросов используйте стандартный fetch (доступен в Node.js 20.19+). Обязательно ставьте тайм-аут через AbortController — иначе внешний API может зависнуть и съесть весь лимит времени ответа.

    bot.addCommand('weather', ['weather'], async (_, bc) => {
    const controller = new AbortController();
    const timeout = setTimeout(() => controller.abort(), 3000);
    try {
    const url = 'https://api.weather.example.com/current?city=moscow';
    const res = await fetch(url, { signal: controller.signal });
    if (!res.ok) throw new Error(`HTTP ${res.status}`);
    const data = (await res.json()) as { temp: number; condition: string };
    bc.text = `It is ${data.temp}°C now, ${data.condition}`;
    } catch (e) {
    bc.text = 'Could not get the weather. Please try again later.';
    } finally {
    clearTimeout(timeout);
    }
    });

    То же через встроенный Request: тайм-аут (2 секунды по умолчанию) уже стоит, исключений нет — результат проверяется по status, а в тестах запрос подменяется моком appContext.httpClient (пример — в Кастомизации HTTP-слоя):

    import { Request } from 'umbot';

    bot.addCommand('weather', ['weather'], async (_, bc) => {
    const request = new Request(bc.appContext);
    request.get = { city: 'moscow' };
    const res = await request.send<{ temp: number; condition: string }>(
    'https://api.weather.example.com/current',
    );
    bc.text =
    res.status && res.data
    ? `It is ${res.data.temp}°C now, ${res.data.condition}`
    : 'Could not get the weather. Please try again later.';
    });

    The Request fields (the body, headers, method, file upload) are in the API reference.

    Authorization is a special case: the framework itself sets controller.userEvents.auth.status and controller.userToken, so it is more convenient to keep the logic in the controller (via action) rather than in addCommand. But the trigger "the user said 'sign in'" can be a command.

    // The trigger — the user initiated authorization
    bot.addCommand('auth', ['sign in', 'log in'], (_, bc) => {
    bc.isAuth = true; // the framework sends start_account_linking
    bc.text = 'Redirecting you to authorization...';
    });

    // The controller handles authorization events (they arrive automatically)
    bot.initBotController(
    class extends BotController {
    action(intentName: string | null, isCommand?: boolean, isStep?: boolean): void {
    if (isCommand || isStep) return;

    // Event: Alice sent account_linking_complete_event
    // In THIS request userEvents.auth.status === true, but userToken is still null!
    if (this.userEvents?.auth?.status === true) {
    this.userData.authCompleted = true;
    this.text = 'Authorization is complete! All features are now available to you.';
    return;
    }

    // In subsequent regular requests userToken is already filled in
    if (this.userToken) {
    // Make authorized requests to your API:
    // const res = await fetch('https://api.example.com/me', {
    // headers: { Authorization: `Bearer ${this.userToken}` },
    // });
    }
    }
    },
    );

    Important: between step 2 (receiving account_linking_complete_event) and step 3 (userToken is filled in) there can be a delay — the next request from Alice. Do not count on userToken being available right away in the same request.

    When the user presses a button with a payload, the framework passes the payload to controller.payload. It is more convenient to handle the press in the controller via action() (rather than a separate command) — because the payload check must come before the intentName check, otherwise collisions are possible.

    // A button with a payload (an object is recommended)
    bot.addCommand('show_product', ['show product'], (_, bc) => {
    bc.card
    .addOneImage('https://shop.example.com/1.jpg', 'Product 1', '99 ₽')
    .addButton({ title: 'Buy', payload: { action: 'buy', id: 1 } });
    });

    // The controller handles button presses
    bot.initBotController(
    class extends BotController {
    action(intentName: string | null, isCommand?: boolean, isStep?: boolean): void {
    // Check the payload first — otherwise a collision: if the "Buy" button
    // matches the 'buy' command slot, the command fires, isCommand=true,
    // and we leave via the early return without reaching the payload.
    const data = this.payload as Record<string, unknown> | null;
    if (data?.action === 'buy') {
    this.text = `The purchase of product #${data.id} has been initiated.`;
    this.buttons.addBtn('Help');
    return;
    }

    // If a command/step fired, it has already done everything — exit.
    if (isCommand || isStep) return;

    // Regular handling by intentName (welcome, help, ...)
    this.buttons.addBtn('Help');
    }
    },
    );

    Tip: check the payload before intentName, otherwise collisions are possible. For example, if a button is called "Play", pressing it sets userCommand='play', and the play intent fires instead of your button handler.

    A button press is easier to handle with bot.addAction('buy', cb), and a button with data — with bot.defineAction<{ id: number }>('buy'): the handler receives { id } already parsed. The payload 'buy', {"action":"buy"} or {"command":"buy"} is turned into the action name by the adapter (see the API reference).

    import { Bot } from 'umbot';
    import { fullPlatforms, MongoAdapter } from 'umbot/plugins';
    import { rateLimiter } from 'umbot/middleware';

    new Bot()
    .use(fullPlatforms)
    .use(new MongoAdapter({ host: 'mongodb://...', database: 'umbot' }))
    .use(rateLimiter()) // globally
    .use('telegram', rateLimiter(50, 120_000)) // a separate limit for TG
    .start('0.0.0.0', 3000);
    import express from 'express';
    import { Bot } from 'umbot';
    import { fullPlatforms } from 'umbot/plugins';

    const bot = new Bot();
    bot.use(fullPlatforms);
    bot.setAppConfig({ isLocalStorage: true });
    bot.initBotController(MyController);

    const app = express();
    // ⚠️ Do NOT add express.json(): webhookHandle reads the request body itself
    app.post('/webhook', (req, res) => bot.webhookHandle(req, res));
    app.get('/health', (req, res) => res.json({ status: 'ok', ts: Date.now() }));
    app.listen(3000, () => console.log('Server started on :3000'));
    import { Bot } from 'umbot';
    import { fullPlatforms, T_ALISA } from 'umbot/plugins';
    import { Preload } from 'umbot/preload';

    const bot = new Bot();
    bot.use(fullPlatforms);
    bot.setAppConfig({ isLocalStorage: true });
    bot.initBotController(MyController);

    const preload = new Preload(bot.getAppContext());
    await Promise.all([
    ...preload.loadImages(['./media/img1.jpg', './media/img2.png'], [T_ALISA], {
    alisaSkillId: 'your-skill-id',
    }),
    ...preload.loadSounds(['./media/win.mp3', './media/lose.mp3'], [T_ALISA], {
    alisaSkillId: 'your-skill-id',
    }),
    ]);

    bot.start('0.0.0.0', 3000);
    import winston from 'winston';
    import { Bot } from 'umbot';

    const logger = winston.createLogger({
    level: 'info',
    format: winston.format.json(),
    transports: [new winston.transports.Console()],
    });

    const bot = new Bot();
    bot.setLogger({
    log: (...args) => logger.info(args.join(' ')),
    error: (msg, meta) => logger.error(msg, meta),
    warn: (msg, meta) => logger.warn(msg, meta),
    metric: (name, value, labels) => logger.info({ metric: name, value, labels }),
    maskSecrets: true,
    });
    import { BotController, MiddlewareNext } from 'umbot';
    import { T_ALISA, T_TELEGRAM } from 'umbot/plugins';

    // A factory: one logic, different labels
    const logMiddleware = (label: string) => async (ctx: BotController, next: MiddlewareNext) => {
    ctx.appContext.log(`[${label}] → ${ctx.userCommand}`);
    await next();
    // The response is NOT built yet here: the handler runs after the whole middleware chain
    ctx.appContext.log(`[${label}] ←`);
    };

    bot.use(logMiddleware('global'));
    bot.use(T_ALISA, logMiddleware('alisa'));
    bot.use(T_TELEGRAM, logMiddleware('telegram'));

    Output order: [global] → → [global] ← → [alisa] → → [alisa] ← — the global chain finishes completely before the platform chain starts. Log the response text in responseCb of bot.start() — only there is it ready.

    // plugins/MyNluPlugin.ts
    import { AppContext, Bot, INlu } from 'umbot';

    export class MyNluPlugin {
    init(appContext: AppContext, bot: Bot): void {
    appContext.plugins.nlu = (
    text: string,
    platformNlu: INlu,
    platform: string,
    request: unknown,
    ): INlu => {
    return {
    ...platformNlu,
    intents: {
    ...platformNlu.intents,
    custom: { slots: [] },
    },
    } as INlu;
    };
    }

    // A required part of the IPlugin contract: called on bot.clearUse() / bot.close()
    destroy(): void {}
    }

    // Usage
    bot.use(new MyNluPlugin());

    The i18n slot is typed as (key: string, ...params: unknown[]) => string, but in practice the framework calls it with a single argument — the current controller.text as the key — and expects a translated string back. The call is made by BaseBotController (the default controller) after the command runs, before the response is sent. If you connected your own controller extending BotController, the translation will not happen — extend BaseBotController or call the plugin yourself. Both a function and an object with a getData(key) method are supported.

    // plugins/I18nPlugin.ts
    import { AppContext, Bot, createPlugin } from 'umbot';

    const translations: Record<string, Record<string, string>> = {
    ru: { hello: 'Привет!', bye: 'Пока!' },
    en: { hello: 'Hello!', bye: 'Bye!' },
    };

    // The language can be determined from user or platform data — a constant here for simplicity
    const lang = 'ru';

    export const i18nPlugin = createPlugin((appContext: AppContext, bot: Bot): void => {
    appContext.plugins.i18n = (text: string): string => {
    return translations[lang]?.[text] ?? text;
    };
    });

    // Nothing needs to be done in the controller: BaseBotController runs
    // this.text through the plugin before sending the response:
    // this.text = 'hello' → the user gets "Привет!"

    A Telegram inline query arrives as the universal inline event. Answer it with the ready-made answerInlineQuery() method (not via call() — that sends messages, not inline search results):

    import { TelegramRequest } from 'umbot/plugins';

    bot.addEvent('inline', async (ctx) => {
    // The 'inline' event arrives only with inline_query in the request
    const req = ctx.requestObject as { inline_query?: { id: string; query: string } };
    if (!req.inline_query) return;
    const telegramApi = new TelegramRequest(ctx.appContext);
    await telegramApi.answerInlineQuery(req.inline_query.id, [
    {
    type: 'article',
    id: '1',
    title: 'Example',
    input_message_content: { message_text: 'Hello from inline mode!' },
    },
    ]);
    ctx.skipAutoReply = true; // the response has already been sent
    });

    Your own model extends Model (an example is in the API reference), and its table is described by IDbTableSchema. Pass the description to appConfig.dbTables: after connecting to the database the core passes it to the adapter's ensureSchema() together with the built-in tables — an SQL adapter creates the table and the indexes, MongoDB — the indexes. A separate middleware or a manual connect() is not needed for this.

    import { IDbTableSchema } from 'umbot';

    const ROOMS_TABLE: IDbTableSchema = {
    tableName: 'Rooms', // the same name the model's tableName() returns
    primaryKeyName: 'roomId',
    uniqueKeys: [],
    fields: {
    roomId: { type: 'string', maxLength: 32 },
    ownerId: { type: 'string', maxLength: 250 },
    data: { type: 'text' },
    },
    indexes: [['ownerId']], // the fields the model looks up records by (where/whereOne)
    };

    bot.setAppConfig({ dbTables: [ROOMS_TABLE] });

    ensureSchema() is called after every successful connection (and after reconnecting to a database that went down), so it must be idempotent — the built-in adapters, umbot-knex-adapter and umbot-ydb-adapter follow this (all columns of the dbTables tables are Utf8 for the YDB adapter; the column types are set by its tables option). If a table could not be created, the error is written to the log and the bot keeps working.

    Outside requests — in a cron task, a migration script, a broadcast from a separate process — the tables are created by bot.connect(): this is the same path the core takes on the first request. A script example is in recipe 19.

    A weekly digest, a "you have not visited for a while" reminder, cleaning up old records — work without an incoming request. There is no built-in scheduler (like in other bot frameworks): the task is started by an external scheduler, and the script connects to the database, does the work and exits.

    Let the bot remember the visit time — no more than once an hour, so as not to add a database record for every message:

    const HOUR = 60 * 60 * 1000;

    bot.use(async (ctx, next) => {
    if (Date.now() - Number(ctx.userData.lastVisit ?? 0) > HOUR) {
    ctx.userData.lastVisit = Date.now();
    }
    await next();
    });

    The broadcast script uses the same bot setup (adapters, database, tokens) but does not start a server. It is convenient to move the setup into a shared module used by both the server and the script:

    // src/setup.ts — the shared setup; the server calls createBot().start(...), the scripts call only createBot()
    import { Bot } from 'umbot';
    import { TelegramAdapter, MongoAdapter } from 'umbot/plugins';

    export function createBot(): Bot {
    const bot = new Bot();
    bot.use(new TelegramAdapter(process.env.TELEGRAM_TOKEN));
    bot.use(new MongoAdapter());
    bot.setAppConfig({
    env: '.env',
    db: { host: process.env.DB_HOST ?? '', database: process.env.DB_NAME ?? 'umbot' },
    });
    return bot;
    }
    // src/jobs/comeBack.ts — once a day: "you have not visited for a while"
    import { UsersData } from 'umbot';
    import { T_TELEGRAM } from 'umbot/plugins';
    import { createBot } from '../setup';

    const WEEK = 7 * 24 * 60 * 60 * 1000;

    async function main(): Promise<void> {
    const bot = createBot();
    try {
    if (!(await bot.connect())) {
    throw new Error('No database connection');
    }
    // userData is stored in the UsersData table: the data field is a JSON string
    const res = await new UsersData(bot.getAppContext()).where({ platform: T_TELEGRAM });
    const rows = res.status && Array.isArray(res.data) ? res.data : [];
    const sleepers = rows
    .filter((row) => {
    const data = typeof row.data === 'string' ? JSON.parse(row.data) : row.data;
    const lastVisit = Number(data?.lastVisit ?? 0);
    return lastVisit > 0 && Date.now() - lastVisit > WEEK;
    })
    .map((row) => String(row.userId));

    const { sent, failed } = await bot.broadcast(
    sleepers,
    { text: 'Long time no see! Come back — we have new quests.', buttons: ['Play'] },
    T_TELEGRAM,
    );
    console.log(`Delivered ${sent.length}, not delivered ${failed.length}`);
    } finally {
    await bot.close(); // closes the database — without it the open pool would keep the process alive
    }
    }

    main().catch((e) => {
    console.error(e);
    process.exitCode = 1;
    });

    Run it with any scheduler, one instance per schedule:

    # crontab: every day at 12:00
    0 12 * * * cd /app && node dist/jobs/comeBack.js >> logs/jobs.log 2>&1
    • The script exits on its own: broadcast waits for all the sends (the queue pauses keep the process until the end), close() closes the database. process.exit() is not needed.
    • The UsersData table is read whole — fine for thousands of users. For a large database select them on the database side: with MongoAdapter — query() with a condition on the time field, or keep the subscribers in your own table with an index (recipe 18, the query conditions are in the API reference).
    • A re-run must not send the message a second time: mark the sends (onResult of broadcast) or select by a time window, as here.
    • Where to run the tasks (a server, Docker, Yandex Cloud) and why not setInterval inside a bot with several replicas — Deployment, "Background tasks".

    Do not call connect() on the adapter itself: the core does not know about such a connection, bot.close() will not close it, and the first request will connect again (in some adapters this recreates the connection pool).

    A "Home → Pricing / Questions → Back" menu is a set of screens: each has text and navigation buttons. bot.defineMenu assembles it from the description: it adds a "Back" button to the screens with a parent and understands both a button press and its title spoken by voice or typed as text.

    const menu = bot.defineMenu('main', {
    screens: {
    home: {
    text: 'How can I help?',
    buttons: [
    { title: 'Pricing', to: 'prices' },
    { title: 'Questions', to: 'faq' },
    { title: 'Website', url: 'https://example.com' },
    ],
    },
    prices: {
    text: (ctx) =>
    `Your plan: ${String(ctx.userData.plan ?? 'Basic')}. Premium — 299 ₽ per month.`,
    parent: 'home',
    },
    faq: {
    text: 'Frequently asked questions:',
    buttons: [{ title: 'Payments', to: 'faq_pay' }],
    parent: 'home',
    },
    faq_pay: { text: 'We accept cards and SBP.', parent: 'faq' },
    },
    });

    bot.addCommand('menu', ['menu', '/start'], (_, ctx) => menu.show(ctx));
    • A press always works: the screen the button leads to is written in its payload. The menu does not break if the user wrote something else between presses.
    • A button title ("pricing", "back") is recognized only among the buttons of the shown screen; the rest of the text goes to regular commands — "back" in the menu and "back" in a form do not interfere with each other.
    • A screen button can lead not to a screen but to an action: { title: 'Buy', payload: buy.payload({ id: 7 }) }, where buy is bot.defineAction.
    • A screen with cards or a long list — onShow: (ctx) => { ... }: called after the screen text and buttons (Navigation — recipe 6). To return the user to the menu from any handler — menu.show(ctx, 'home'), a transition button outside the menu — ctx.buttons.addBtn('To the menu', '', menu.payload('home')).
    • The menu and screen names go into the button payload (Telegram accepts up to 64 bytes) — keep them short; about too long ones defineMenu warns in the log.

    All the parameters are in the API reference.

    These are not shortcomings of the framework — they are simply scenarios that have no ready examples in the repository. The developer will have to implement them, building on the API.

    In serverless, use bot.webhookEvent(body, headers, clientIp) instead of bot.start(): it verifies the webhook signature and returns a ready { statusCode, body } for the cloud function. A project with a ready handler and a deployment script is generated by npx umbot create from-flow flow.json --usecloud; a manual handler is in Deployment.

    The full flow:

    1. The user says "sign in".
    2. The controller sets this.isAuth = true.
    3. The framework sends start_account_linking — Yandex opens a browser.
    4. The browser redirects to your backend.
    5. The backend generates an access_token and redirects back to Yandex with access_token.
    6. Alice sends a special request with account_linking_complete_event: true.
      • In this request: controller.userEvents.auth.status === true.
      • In this request: controller.userToken is still null (the token is not passed in this request).
    7. In subsequent regular requests (when the user says something else) Alice sends session.user.access_token, and controller.userToken is filled in.

    The backend part (between steps 4–5) is not implemented in the framework — you write it yourself.

    The framework caches uploaded media but does not show the remaining quota (1 GB per account). You can check it via YandexImageRequest.checkOutPlace():

    import { YandexImageRequest } from 'umbot/plugins';

    // The constructor argument order: oauth, skillId, appContext.
    // If you pass null instead of oauth, the token from appConfig.tokens.alisa.token is used.
    const req = new YandexImageRequest(null, 'skill_id', controller.appContext);

    // If needed, the token can be set explicitly (without the "OAuth " prefix —
    // setOAuth adds it itself):
    req.setOAuth('y0_AgAAAA...');

    const res = await req.checkOutPlace();
    if (res) {
    // used/total come in bytes
    console.log(`Used: ${res.used} / Total: ${res.total}`);
    }

    Alice recognizes "yes"/"no" automatically as built-in intents. You can use them without any setup in Yandex Dialogs:

    public action(intentName: string | null): void {
    if (this.nlu.isIntentConfirm(this.userCommand || '')) {
    // the user said "да", "конечно", "хорошо" (yes, of course, okay), ...
    }
    if (this.nlu.isIntentReject(this.userCommand || '')) {
    // "нет", "не надо", "отмена" (no, don't, cancel), ...
    }
    }

    UsersData.save() performs an upsert (select → insert/update). If you need transactions, use model.query(cb) with MongoAdapter:

    const userData = new UsersData(this.appContext);
    await userData.query(async (client, db) => {
    const session = client.startSession();
    await session.withTransaction(async () => {
    // atomic operations
    });
    });

    Via setLogger:

    bot.setLogger({
    error: (msg, meta) => Sentry.captureException(new Error(msg), { extra: meta }),
    warn: (msg, meta) => Sentry.captureMessage(msg, 'warning', { extra: meta }),
    // ...
    });

    Not part of the framework. Use bot.send(userId, text, platform) together with an external WS server.

    userData is different for each user, so keep the match (the board, whose turn it is, the move deadline) in your own table (recipe 18), and in the player's userData — only the match id. The reply to the player who moved — a regular ctx.text, to the opponent — bot.send():

    // GameModel, renderBoard, opponentOf, finishGame — your game code
    const move = bot.defineAction<{ cell: number }>('move');

    move.handle(async (data, ctx) => {
    const game = new GameModel(ctx.appContext); // your own model: gameId, board, turn, playerX, playerO, deadline
    if (!(await game.whereOne({ gameId: String(ctx.userData.gameId) }))) {
    return 'Match not found';
    }
    if (Date.now() > Number(game.state.deadline)) {
    return finishGame(game, 'The move time is up'); // the deadline is checked on every request
    }
    if (game.state.turn !== String(ctx.userId)) {
    return 'The opponent is moving now';
    }
    // ... check the cell, record the move, pass the turn, deadline = Date.now() + 30_000
    await game.update();
    ctx.text = renderBoard(game);
    const delivered = await bot.send(
    opponentOf(game, ctx.userId),
    { text: renderBoard(game) },
    ctx.appType!,
    );
    if (delivered === false) {
    await finishGame(game, 'The opponent is unavailable'); // blocked the bot — do not keep the match open
    }
    });
    • Тайм-аут — не setTimeout. Таймер живёт в памяти процесса: он теряется при рестарте, в serverless (каждый вызов может попасть в новый экземпляр) и срабатывает не в той реплике. Храните срок (deadline) в записи партии и проверяйте его при каждом входящем запросе, а брошенные партии закрывайте задачей по расписанию (рецепт 19): она выбирает партии с истёкшим сроком и сообщает игрокам.
    • Несколько реплик. Два игрока могут попасть в разные процессы одновременно. Проверка «чей ход» и запись хода должны быть одной операцией в БД — с MongoAdapter это updateOne с условием { gameId, turn } через query() (см. «Atomic-операции с БД» выше); обычный update() перезапишет запись целиком.
    • Тесты. Два игрока в BotTest — чередуйте bot.simulate(текст, { userId: 'a' }) и { userId: 'b' }, а bot.send замените моком (jest.spyOn(bot, 'send')).
    • Голосовые платформы написать сопернику не могут: на Алисе и Марусе ход соперника игрок узнает только своим следующим запросом.

    In the unified API every reply is a new message. In games and counters where the board must change in place, call the platform method directly. In MAX for button presses there is the option new MaxAdapter(token, { max_callback_edit_message: true }) — the reply replaces the message with the button. In Telegram — editMessageText via TelegramRequest.call(method, chatId, params); any Bot API method without a dedicated wrapper is called the same way (deleteMessage, pinChatMessage, sendInvoice):

    import { T_TELEGRAM, TelegramRequest } from 'umbot/plugins';

    bot.addAction('refresh', async (_, ctx) => {
    const text = `Updated at ${new Date().toLocaleTimeString('ru-RU')}`;
    if (ctx.appType !== T_TELEGRAM) {
    ctx.text = text; // the other platforms get it as a new message
    return;
    }
    const chatId = ctx.platformOptions.requestData?.telegram?.chatId ?? ctx.userId;
    const result = await new TelegramRequest(ctx.appContext).call(
    'editMessageText',
    String(chatId),
    {
    message_id: ctx.messageId, // on a button press — the id of the message with this button
    text,
    reply_markup: { inline_keyboard: [[{ text: 'Refresh', callback_data: 'refresh' }]] },
    },
    );
    if (result) {
    await ctx.api?.answerCallback(''); // remove the loading indicator from the button
    ctx.skipAutoReply = true; // the message is already updated — do not send a new one
    } else {
    ctx.text = text; // it did not work (the reason is in the log) — send it as a new message
    }
    });

    call() берёт токен из настроек бота, держит тайм-аут и при ошибке возвращает null, записав причину в лог (токен в логе маскируется).

    There are no payment APIs (Telegram Payments, VK Pay) in the unified API. The scheme that works on all platforms:

    1. A link button to the payment page: ctx.buttons.addLink('Pay', checkoutUrl), where checkoutUrl contains the user id and the platform (signed by your backend, so that they cannot be forged).
    2. The payment service sends a webhook about the payment to your backend — not to the bot.
    3. The backend writes the subscription to its own table (the user, the platform, the expiration date, the payment id) and notifies the user: bot.send(userId, 'Payment received, premium enabled', platform).
    4. The paid section checks the expiration date (until > Date.now()), not a flag — an overdue subscription is handled on the first request without background tasks. It is convenient to make it your own middleware that does not call next() for the paid commands without a subscription (how to write your own — in Middleware).

    The built-in i18n plugin is too simple. Use i18next or @formatjs/intl by connecting them to the i18n slot — BaseBotController runs controller.text through it before sending the response (see recipe 16 about your own controller):

    import i18next from 'i18next';
    import { createPlugin } from 'umbot';

    bot.use(
    createPlugin((appContext) => {
    appContext.plugins.i18n = (text: string) => i18next.t(text, { lng: 'ru' });
    }),
    );

    If the user sent an image URL and you want to send it — the framework can do this (just pass the URL to card.addImage). But there is no ready function to "download an image, process it, upload it" — you need your own logic with fetch:

    import { promises as fsPromises } from 'node:fs';

    bot.addCommand('repost', ['repost'], async (_, bc) => {
    const userUrl = bc.originalUserCommand || '';
    try {
    const res = await fetch(userUrl, {
    signal: AbortSignal.timeout(3000), // do not let a third-party URL hang
    });
    if (!res.ok) throw new Error(`HTTP ${res.status}`);
    const buf = Buffer.from(await res.arrayBuffer());
    const tmpPath = '/tmp/downloaded.jpg';
    await fsPromises.writeFile(tmpPath, buf);
    bc.card.addImage(tmpPath, 'Uploaded');
    bc.text = 'Here is your image.';
    } catch (e) {
    bc.text = 'Could not download the image.';
    }
    });

    A common task with no ready example. Use Navigation + card.addImage (see recipe 6 and the section about cards in the guide).