This page is machine-translated from the Russian original. If something reads oddly, the Russian version is the source of truth — open an issue.
umbot supports telegraf- and vk-io-style middleware — functions that are called before the business logic runs (BotController.action).
import { T_ALISA } from 'umbot/plugins';
// Global middleware (for all platforms)
bot.use(async (ctx, next) => {
console.log('Request:', ctx.appType);
await next(); // you must call next() to continue
});
// middleware for a specific platform
bot.use(T_ALISA, async (ctx, next) => {
// requestObject is the raw platform payload (unknown), a cast is required
const request = ctx.requestObject as Record<string, unknown> | null;
const session = request?.session as Record<string, unknown> | undefined;
if (!session?.user_id) {
ctx.text = 'Invalid request';
ctx.isEnd = true;
// next() is not called → action() will not run
return;
}
await next();
});
action(), commands, steps): it is not a Koa-style "onion".
The order is: first the whole global chain — including the code after await next(), then the platform chain,
and only then the handler. Example with a global mw1 (logging before/after next()) and a platform mw2:
the order is 1, 4, 2, 3, action() — the code after next() in mw1 runs before the platform chain and before
the handler. So after await next() the response (ctx.text, buttons) is not built yet — do not read it there.
The full response is available in responseCb of bot.start() / bot.webhookHandle() (example below).npx umbot add middleware <name> creates a scaffold of a middleware factory with options and a test — the file
src/middleware/<name>.ts (more in the CLI description).
bot.use(async (ctx, next) => {
console.log(`[${ctx.appType}] Request from ${ctx.userId}: ${ctx.userCommand}`);
await next();
});
In middleware the response is not built yet (the handler runs after all middleware). To log the response,
use responseCb of the built-in server (webhookHandle has the same third argument):
bot.start('0.0.0.0', 3000, (_req, res, state) => {
console.log(`Response ${state.statusCode}:`, state.body);
state.defaultSend(res, state);
});
bot.use(async (ctx, next) => {
// Let the greeting and help through
if (ctx.messageId === 0 || ctx.userCommand === 'help') {
await next();
return;
}
// Check whether the user is authorized
if (!ctx.userData?.isAuthorized) {
ctx.text = 'You need to sign in to use this bot.';
ctx.isEnd = true;
return; // next() is not called — action() will not run
}
await next();
});
import { T_TELEGRAM } from 'umbot/plugins';
// Telegram only
bot.use(T_TELEGRAM, async (ctx, next) => {
// ⚠️ payload can be a string or an object — always narrow the type first
const payload = ctx.payload as { command?: string } | null | undefined;
if (payload?.command === 'cancel') {
ctx.text = 'Action cancelled.';
ctx.isEnd = true;
return;
}
await next();
});
The framework ships with built-in middleware that limits the rate of incoming requests (rateLimiter). The limit comes from the platform adapter's limit property: for Telegram, VK, Viber and MAX it is 30 req/sec. Outgoing MAX messages are limited separately by the API client queue to 2 messages per second per dialog. If limit is not set or is 0/null, rateLimiter lets requests through without limits.
import { rateLimiter } from 'umbot/middleware';
bot.use(rateLimiter()); // default: queue=100, idle=60s
// or with custom parameters
bot.use(rateLimiter(200, 120_000)); // queue=200, idle 2 min
// a shared limit per platform instead of a per-user limit
bot.use(rateLimiter(100, 60_000, (ctx) => ctx.appType ?? ''));
Counter key (getKey, the third parameter). By default the limit is counted per {platform, userId} pair. If the
platform has no webhook signature or the secret is not set, userId is chosen by the sender of the request, and by changing it one can bypass
the per-user limit. getKey sets your own key (the platform is appended to it): ctx => ctx.appType ?? '' limits
the total load per platform. Keep in mind that the limit comes from the adapter's limit: Alice, SmartApp and Marusia do not set it,
so the middleware does not limit them.
What it does:
appContext.platforms[platform].limit (TG/VK/Viber/MAX = 30 by default; 0/null — no limits).{platform, userId}: the request counter is reset every second.maxQueueSize).ctx.platformOptions.rateLimitOverflow = true and
throws RateLimitQueueOverflowError (exported from umbot/middleware). The core logs the error and does not run
command handling; the platform gets 200, so there is no redelivery. The flag and the error class let you tell
an overload rejection from an error in the business logic (for example, in responseCb of bot.start()).destroyRateLimiter() (also from umbot/middleware) stops the cleanup timers and rejects the queued
requests of all created limiters — for hot reload and tests; you do not need to call it on a normal process exit,
the timers do not keep the process alive.inactivityTimeout) are O(1) per entry: a stream of requests with
new userIds (on Alice and Marusia it is chosen by the sender) does not turn every request into a walk over all keys..unref() — they do not block the process from exiting.Important: rateLimiter limits incoming requests (from the platform to you), not outgoing API calls (from you to the platform API).
Checks whether the user is allowed to continue the dialog.
import { authGuard } from 'umbot/middleware';
// An allowlist of user IDs
const ADMIN_IDS = ['12345', '67890'];
bot.use(
authGuard((ctx) => ADMIN_IDS.includes(String(ctx.userId)), {
deniedText: 'This command is available to administrators only',
}),
);
// An asynchronous check — for example, via a database
bot.use(
authGuard(async (ctx) => {
const user = await db.users.findOne({ id: ctx.userId });
return !!user?.isActive;
}),
);
Behavior:
check returned true, next() is called.false or check threw an exception, the user gets deniedText and next() is NOT called.check are logged via appContext.logError but do not break the pipeline.Signature: authGuard(check, options?) where check: (ctx) => boolean | Promise<boolean>.
Assigns a unique requestId to every incoming request — useful for end-to-end log tracing.
import { requestId } from 'umbot/middleware';
bot.use(requestId());
// In other middleware or commands:
// ⚠️ addCommand requires non-empty slots (except welcome/help — they have defaults).
// A command with an empty slots array is simply not registered.
bot.addCommand('debug', ['debug'], (_, ctx) => {
console.log('request id:', ctx.platformOptions.requestId);
});
What it does:
ctx.platformOptions.requestId = crypto.randomUUID() (или fallback на timestamp+random для старых рантаймов).bot.getAppContext().lastRequestId — последний выданный ID доступен и вне обработки запроса (для логов без доступа к ctx).Replies "the service is under maintenance" while check() returns true.
import { maintenance } from 'umbot/middleware';
let isDown = false;
// An admin command can change isDown
bot.addCommand('admin_maintenance', ['enable maintenance'], (_, ctx) => {
isDown = true;
ctx.text = 'Maintenance mode ON';
});
bot.use(
maintenance(() => isDown, {
message: 'The bot is being updated. Please try again in 5 minutes.',
}),
);
Behavior:
check() returns false, the request proceeds normally.true, the user gets message and next() is not called.check() throws, the request is let through (protection against accidentally taking the service down).check functions are supported.Filters incoming requests by client IP.
import { ipFilter } from 'umbot/middleware';
// Trusted networks only (for example, the platform's IP ranges)
bot.use(
ipFilter({
whitelist: ['203.0.113.0/24', '198.51.100.0/24'],
deniedText: 'Forbidden',
rejectWithoutIp: true, // a request with an unknown client IP is rejected too
}),
);
// Or a blacklist (block spam ranges)
bot.use(
ipFilter({
blacklist: ['203.0.113.42', '198.51.100.0/24'],
}),
);
Behavior:
'192.168.1.10'), так и CIDR ('10.0.0.0/8').whitelist, запросы проходят только с совпавших IP.
Если ни одна запись whitelist не является валидным CIDR (опечатка во всех записях), фильтр блокирует все запросы
и пишет предупреждение — ошибка конфигурации не должна молча открывать доступ.::ffff:127.0.0.1 → 127.0.0.1).ctx.platformOptions.clientIp. В bot.start()/webhookHandle() фреймворк заполняет его из
req.socket.remoteAddress; в serverless его нужно передать третьим аргументом:
bot.webhookEvent(body, headers, clientIp). Обработчик Yandex Cloud Functions, сгенерированный CLI
(create from-flow --usecloud), передаёт event.requestContext.identity.sourceIp.bot.run()/BotTest, webhookEvent() без clientIp): по умолчанию запрос пропускается без
фильтрации (одно предупреждение в лог), чтобы бот не ломался в dev/test окружении. Опция rejectWithoutIp: true
отклоняет такие запросы — включайте её в продакшене вместе с whitelist, иначе забытый clientIp молча отключает
фильтр. У long polling (bot.startPolling()) IP клиента нет вовсе: с rejectWithoutIp: true отклоняются все
обновления, а сам фильтр для polling не нужен.X-Forwarded-For не используется, потому что клиент может его
подделать. За прокси ограничивайте доступ на уровне самого прокси.⚠️ Important: ipFilter does NOT replace real protection with a reverse proxy / firewall. It is an additional layer.
import { MiddlewareNext, BotController } from 'umbot';
export function myMiddleware(options: { skip?: boolean } = {}) {
return async (ctx: BotController, next: MiddlewareNext): Promise<void> => {
try {
// your logic BEFORE the request is handled
} catch (e) {
ctx.appContext.logError('myMiddleware error', { error: e });
// Decide: hide the error (continue) or block (return without next)
}
await next(); // required so that commands/steps handle the request next
// your logic AFTER handling (for example, timing, response logging)
};
}
Rules:
next() or deliberately finish the response with ctx.text = ... (without next()).bot.use(mw1); bot.use(mw2); → mw1 first).bot.use(T_TELEGRAM, mw).Full reference — API v-3.1 · all versions.