Skip to content

Handlers & Middleware

A bot is an ordered list of middleware. Each incoming update starts at the first one; a middleware either handles the update or passes it on by calling $next(). The convenience methods (command(), hears(), callbackQuery(), on()) are middleware that only run your handler when the update matches.

Method Runs when $ctx->match
use(fn ($ctx, $next) => ...) Every update. Call $next() to continue.
on('message:text', ...) A filter query matches.
command('start', ...) /start or /start@your_bot Text after the command
hears('Help', ...) The text is exactly Help. The text
hears('/^pay (\d+)$/i', ...) The text matches the regex. The regex groups
callbackQuery('ok', ...) A button with data ok is pressed. The data
callbackQuery('/^order:(\d+)$/', ...) Button data matches the regex. The regex groups
catch(fn (Throwable $e, Context $ctx) => ...) A handler throws.

All registration methods return the bot, so they can be chained.

$bot->command('start', function (Context $ctx): void {
// "/start ref_42" sets $ctx->match to "ref_42"
$ctx->reply('Welcome! Referral: '.($ctx->match ?: 'none'));
});
$bot->command(['help', 'about'], fn (Context $ctx) => $ctx->reply('Acme Bot, version 1.0'));

Command names are case-insensitive and may be written with or without the leading slash. A command addressed to another bot, like /start@other_bot, is ignored: the bot compares the mention with its own username, which it fetches once with getMe unless you pass username: to the constructor.

$ctx->command() gives you the parsed command of any message: ['name' => 'start', 'args' => 'ref_42', 'mention' => null], or null.

$bot->hears('Opening hours', fn (Context $ctx) => $ctx->reply('9:00 to 18:00, Monday to Friday.'));
$bot->hears('/^pay (\d+)$/i', function (Context $ctx): void {
$amount = (int) $ctx->match[1];
$ctx->reply("Paying \${$amount}...");
});

A pattern is treated as a regex when it starts with /, #, or ~ and compiles; otherwise it must equal the text exactly. hears() matches the message text or the media caption.

use Pam\Telegram\Keyboard\InlineKeyboard;
$bot->command('order', fn (Context $ctx) => $ctx->reply('Order #7 is ready.', [
'reply_markup' => InlineKeyboard::make()
->text('Confirm', 'order:7:confirm')
->text('Cancel', 'order:7:cancel'),
]));
$bot->callbackQuery('/^order:(\d+):(confirm|cancel)$/', function (Context $ctx): void {
[, $orderId, $action] = $ctx->match;
$ctx->answer($action === 'confirm' ? 'Confirmed' : 'Cancelled');
$ctx->edit("Order #{$orderId}: {$action}ed");
});

on() matches updates by type and content, using filter queries like grammY’s:

Query Matches
message Any new message
message:text A new message with text
message:photo A new message with a photo
:photo A photo in any message-like update: messages, channel posts, edits, and business messages
callback_query:data A button press with data
message:entities:url A message containing a URL entity
my_chat_member The bot was added to, removed from, or changed in a chat
edited_message An edited message

The first part is the update type; an empty first part means any of message, edited_message, channel_post, edited_channel_post, business_message, and edited_business_message. The second part requires a non-empty field, and the third part requires an entity of that type inside it. Pass a list to match any of several queries:

$bot->on([':photo', ':video'], fn (Context $ctx) => $ctx->reply('Thanks for the media!'));

Middleware runs for every update that reaches it. Use it for logging, access control, or loading data into the session:

$bot->use(function (Context $ctx, Closure $next): mixed {
$started = microtime(true);
$result = $next();
error_log(sprintf('update %d took %.1f ms', $ctx->updateId(), (microtime(true) - $started) * 1000));
return $result;
});
$bot->use(function (Context $ctx, Closure $next): mixed {
if (($ctx->chat()['type'] ?? null) !== 'private') {
return null; // ignore groups: do not call $next()
}
return $next();
});

Handlers run in registration order, and the first one that matches stops the chain unless it calls $next() itself. Register general middleware before specific handlers. Calling $next() twice throws LogicException.

Every handler receives a Pam\Telegram\Context for the current update:

$ctx->update; // the raw update array
$ctx->type(); // "message", "callback_query", "my_chat_member"...
$ctx->text(); // message text or media caption
$ctx->chatId(); // ?int
$ctx->userId(); // ?int
$ctx->from(); // the user array
$ctx->chat(); // the chat array
$ctx->message(); // message, edited message, channel post, or business message
$ctx->callbackQuery(); // ?array
$ctx->callbackData(); // ?string
$ctx->session; // per-chat array, saved after the update
$ctx->api; // the Api client

Shortcuts that act on the current chat or message:

Method Bot API method Notes
reply($text, $extra = []) sendMessage Keeps the forum topic and business connection.
replyWithPhoto($photo, $extra = []) sendPhoto An InputFile, a file_id, or a URL.
replyWithDocument($document, $extra = []) sendDocument Same as above.
typing($action = 'typing') sendChatAction Shows the action for up to 5 seconds.
answer($text = null, $alert = false) answerCallbackQuery Only for callback queries.
edit($text, $extra = []) editMessageText The message of the pressed button, or the current message.
editMarkup($markup) editMessageReplyMarkup Pass null to remove the keyboard.
delete() deleteMessage
enter($scene, $data = []) / leave() See scenes.

For anything else, call the Bot API directly: $ctx->api->call('pinChatMessage', [...]).

Without a catch() handler, an exception from a handler propagates out of handle(). When the bot runs with run() or handleWebhook(), one bad update never stops the bot: the error is written with error_log() and processing continues.

Register catch() to handle errors yourself, for example to apologize to the user and report the error:

$bot->catch(function (Throwable $error, Context $ctx): void {
error_log($error->getMessage());
if ($ctx->chatId() !== null) {
$ctx->reply('Sorry, something went wrong. Please try again.');
}
});