Skip to content

Sessions & Scenes

Most bots need to remember something between messages: a language preference, a cart, or which question they just asked. PAM Telegram gives every chat a session, a plain PHP array loaded before your handlers run and saved after them. Scenes build on sessions to run multi-step conversations, such as a sign-up form, one message at a time.

Read and write $ctx->session like any array:

$bot->command('count', function (Context $ctx): void {
$ctx->session['count'] = ($ctx->session['count'] ?? 0) + 1;
$ctx->reply("You called /count {$ctx->session['count']} times.");
});

The session is saved only when it changed, and deleted when you set it to an empty array. By default the session key is the chat ID (or the user ID for updates without a chat). Pass sessionKey to change it, for example to keep one session per user across all chats:

$bot = new Bot(
getenv('TELEGRAM_BOT_TOKEN'),
sessionKey: fn (Context $ctx): ?string => $ctx->userId() === null ? null : 'user:'.$ctx->userId(),
);

Returning null skips the session for that update.

Store Use it when
MemorySessionStore (default) The bot is a long-lived process: PAM, or long polling with the PHP CLI.
CacheSessionStore($psr16Cache) PHP-FPM or several workers share sessions: Laravel Cache::store(), Symfony, or any PSR-16 cache.
Your own SessionStore You want sessions in a database, Redis, or elsewhere.
sessions: false The bot is stateless. Scenes are not available.

MemorySessionStore is bounded so a busy bot cannot grow without limit. It keeps at most maxEntries sessions (default 10000) and expires them after ttl seconds (default 86400):

use Pam\Telegram\Session\MemorySessionStore;
$bot = new Bot($token, sessions: new MemorySessionStore(maxEntries: 50_000, ttl: 3_600.0));

CacheSessionStore takes any Psr\SimpleCache\CacheInterface, plus an optional key prefix (default pam_telegram.session.) and TTL in seconds (default 86400):

use Pam\Telegram\Session\CacheSessionStore;
$bot = new Bot($token, sessions: new CacheSessionStore(Cache::store('redis'), ttl: 7 * 86_400));

To write your own store, implement Pam\Telegram\Session\SessionStore, which has three methods: read(string $key): ?array, write(string $key, array $data): void, and delete(string $key): void.

A scene is a named list of steps. When a chat enters a scene, step 0 runs immediately. Every later update from that chat goes to the current step, until the scene ends.

use Pam\Telegram\Context;
use Pam\Telegram\Scene;
$bot->scene('transfer',
function (Context $ctx, Scene $scene): void {
$ctx->reply('How much do you want to send?');
$scene->next();
},
function (Context $ctx, Scene $scene): void {
$amount = (float) $ctx->text();
if ($amount <= 0) {
$ctx->reply('Please send a positive amount.');
return; // no next(): this step runs again on the next message
}
$scene->data['amount'] = $amount;
$ctx->reply('Who should receive it?');
$scene->next();
},
function (Context $ctx, Scene $scene): void {
$ctx->reply(sprintf('Sending $%.2f to %s.', $scene->data['amount'], $ctx->text()));
$scene->leave();
},
);
$bot->command('transfer', fn (Context $ctx) => $ctx->enter('transfer'));
Call Effect
$scene->next() Go to the next step. After the last step, the scene ends.
$scene->back() Go to the previous step (not below 0).
$scene->to($step) Jump to a step by index. Throws OutOfRangeException for an invalid step.
$scene->leave() or $ctx->leave() End the scene now.
(none) Stay on the same step; it runs again on the next update.

Use $scene->data to carry values between steps; pass initial data with $ctx->enter('transfer', ['currency' => 'USD']). Inside a step, $scene->name and $scene->step tell you where you are, and $ctx->scene holds the running scene.

The scene state lives in the chat’s session, under the key Bot::SCENE_KEY (__scene). That means scenes:

  • need sessions (entering a scene with sessions: false throws LogicException);
  • survive restarts and work with webhooks and PHP-FPM, as long as the session store persists;
  • expire when idle. The default sceneTtl is 900 seconds; change it in the constructor: new Bot($token, sceneTtl: 1_800.0).

A /cancel command ends any scene. The update then continues through your normal handlers, so you can still answer it:

$bot->command('cancel', fn (Context $ctx) => $ctx->reply('Cancelled. Send /transfer to start again.'));

Change the cancel commands with $bot->cancelScenesOn(['cancel', 'stop']).