Search by

pushinbr / pam-telegram

DavidWilliamBalbino

Telegram Bot API framework for PHP: middleware, commands, sessions, wizard scenes, long polling and webhooks. Built for the PAM runtime, works anywhere.

v0.1.3 2026-12-02 19:23 UTC

This package is auto-updated.

Last update: 2026-12-02 19:24:42 UTC


README

PAM Telegram

Telegram bots in PHP that stay alive.

PHP 8.3+ PAM Runtime Packagist CI License

Commands · filters · sessions · multi-step scenes · keyboards · uploads · long polling · webhooks

Documentation · Start here · Features · Webhooks · Anywhere else

A middleware-based framework for the official Telegram Bot API. PAM keeps the process alive, so sessions and conversations live in memory, the connection to Telegram is reused and an idle bot costs nothing. The package has no Composer dependencies and also runs on PHP-FPM, Laravel, Symfony or a plain script.

Two Telegram chats with a bot: commands with an inline Refresh button, and a multi-step transfer scene

Want your own account instead of a bot (log in by QR, read and send as you)? Use pushinbr/pam-telegram-web.

Start here

1. Install PAM

curl --proto '=https' --proto-redir '=https' --tlsv1.2 \
    --connect-timeout 15 --max-time 60 --max-filesize 1048576 -fsSL \
    https://pamphp.com/install | sh

pam doctor

2. Create your project and install the library

mkdir my-bot && cd my-bot
pam composer init --no-interaction
pam composer require pushinbr/pam-telegram:^0.1

3. Get a bot token

Open @BotFather in Telegram, send /newbot and copy the token it gives you.

export TELEGRAM_BOT_TOKEN='123456789:AA...'

4. Create bot.php

<?php

declare(strict_types=1);

require __DIR__.'/vendor/autoload.php';

use Pam\Telegram\Bot;
use Pam\Telegram\Context;
use Pam\Telegram\Keyboard\InlineKeyboard;

$bot = new Bot(getenv('TELEGRAM_BOT_TOKEN'));

$bot->command('start', fn (Context $ctx) => $ctx->reply('Hi! Send /balance.'));

$bot->command('balance', fn (Context $ctx) => $ctx->reply('Your balance: $150.00', [
    'reply_markup' => InlineKeyboard::make()->text('Refresh', 'balance:refresh'),
]));

$bot->callbackQuery('balance:refresh', function (Context $ctx): void {
    $ctx->answer('Updated');
    $ctx->edit('Your balance: $151.00');
});

$bot->on('message:photo', fn (Context $ctx) => $ctx->reply('Nice photo!'));

echo "✓ Bot running. Press Ctrl+C to stop.\n";
$bot->run();

5. Run it

pam bot.php

Send /start to your bot. run() uses long polling: no public URL, no open port. Telegram holds each request open for 30 seconds, so an idle bot uses no CPU. Ctrl+C (or SIGTERM) stops it cleanly, under pam and on CLI PHP with pcntl: the bot finishes the update in hand (or the long poll in flight, at most 30 seconds), confirms the updates it already handled so a restart never processes them twice, and returns from run(). Press Ctrl+C again to quit at once.

What's included

Handlers

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, /start@your_bot text after the command
hears('Help', …) / hears('/^pay (\d+)$/i', …) exact text or regex text or regex groups
callbackQuery('ok', …) / callbackQuery('/^order:(\d+)$/', …) button press data or regex groups
catch(fn (Throwable $e, Context $ctx) => …) a handler throws

The first handler that matches wins. It continues the chain only if it calls $next().

Filter queries

message, message:text, :photo (any message-like update: messages, channel posts, edits, business messages), callback_query:data, message:entities:url, my_chat_member… Pass a list to match any of them.

Context

$ctx->text();            // text or caption
$ctx->chatId(); $ctx->userId(); $ctx->from(); $ctx->chat(); $ctx->message();
$ctx->command();         // ['name' => 'start', 'args' => 'ref_42', 'mention' => null]
$ctx->reply('<b>Hi</b>', ['parse_mode' => 'HTML']);  // keeps forum topic and business connection
$ctx->replyWithPhoto(InputFile::fromPath('/tmp/qr.png'));
$ctx->replyWithDocument('BQACAgEAAx…');              // file_id or URL: no upload
$ctx->typing();
$ctx->answer('Done');                                // always answer callback queries
$ctx->edit('New text'); $ctx->editMarkup(null); $ctx->delete();
$ctx->api->call('anyBotApiMethod', [...]);

Escape untrusted text with Format::html() or Format::markdownV2() before putting it in a formatted message.

Sessions

$ctx->session is a per-chat array, saved after each update.

Store Use it when
MemorySessionStore (default) PAM, long polling, any long-lived process. Bounded by entries and TTL
CacheSessionStore($psr16Cache) PHP-FPM or several workers: Laravel Cache::store(), Symfony, Nimbus
your own SessionStore database, Redis…
sessions: false stateless bots

Scenes (multi-step conversations)

A scene is a list of steps. Step 0 runs when the chat enters the scene; every later message of that chat goes to the current step until the scene ends. State lives in the session, so scenes survive restarts and work with webhooks. /cancel leaves any scene.

use Pam\Telegram\Scene;

$bot->scene('transfer',
    function (Context $ctx, Scene $scene): void {
        $ctx->reply('How much?');
        $scene->next();
    },
    function (Context $ctx, Scene $scene): void {
        $amount = (float) $ctx->text();
        if ($amount <= 0) {
            $ctx->reply('Invalid amount, try again.'); // this step runs again

            return;
        }
        $scene->data['amount'] = $amount;
        $ctx->reply('To whom?');
        $scene->next();
    },
    function (Context $ctx, Scene $scene): void {
        $ctx->reply("Sending \${$scene->data['amount']} to {$ctx->text()}.");
        $scene->leave();
    },
);

$bot->command('transfer', fn (Context $ctx) => $ctx->enter('transfer'));

$scene->next(), back(), to($step), leave(). A step that calls none of them runs again on the next message. Idle scenes expire after 15 minutes (sceneTtl).

Bot API client

Every Bot API method works, including ones released after this package:

$api = $bot->api; // or new Api($token)
$api->sendMessage(chat_id: 42, text: 'Hi');
$api->sendMessage(['chat_id' => 42, 'text' => 'Hi']);
$api->sendMediaGroup(chat_id: 42, media: [
    ['type' => 'photo', 'media' => InputFile::fromPath('a.jpg')], // uploaded as attach://
    ['type' => 'photo', 'media' => 'AgACAgEAAx…'],               // existing file_id
]);
$bytes = $api->download($fileId);
  • TelegramException (errorCode, description, retryAfter(), migrateToChatId()) when Telegram refuses.
  • TransportException when the Bot API cannot be reached. Messages never contain the token.
  • HTTP 429 is retried after retry_after (maxRetries, maxRetryAfter). Network errors are not retried, so a message is never sent twice.
  • Broadcasting? Pass rateLimiter: new RateLimiter() to the Api to stay under 30 msg/s overall, 1 msg/s per private chat and 20 msg/min per group.
  • Self-hosted Bot API server: new Api($token, baseUrl: 'http://localhost:8081').

Webhooks

$bot = new Bot(getenv('TELEGRAM_BOT_TOKEN'), webhookSecret: getenv('TELEGRAM_WEBHOOK_SECRET'));
$bot->setWebhook('https://example.com/telegram'); // once

handleWebhook($body, $secretHeader) returns the HTTP status to answer: 401 for a wrong secret, 400 for a bad body, otherwise 200. Handler errors still answer 200, so Telegram does not redeliver the update in a loop.

// PAM HTTP / Nimbus
$app->post('/telegram', fn ($request, $response) => $response->json([], $bot->handleWebhook(
    $request->body(),
    $request->getHeader('x-telegram-bot-api-secret-token'),
)));

Use it outside PAM

The package needs only PHP 8.3+. Outside PAM, use CacheSessionStore so sessions survive between requests.

// Laravel
Route::post('/telegram', fn (Request $r) => response('', $bot->handleWebhook(
    $r->getContent(),
    $r->header('X-Telegram-Bot-Api-Secret-Token'),
)));

// Plain PHP-FPM
http_response_code($bot->handleWebhook(
    file_get_contents('php://input'),
    $_SERVER['HTTP_X_TELEGRAM_BOT_API_SECRET_TOKEN'] ?? null,
));

Long polling works the same with php bot.php.

Transports

AutoTransport (default) uses ext-curl with a reused connection, then the PAM runtime HTTP client, then PHP streams: no extension is required. Pass new PamTransport() to the Api to make Bot API calls non-blocking inside a PAM request Fiber, or implement Transport yourself.

Testing your bot

Implement Transport with canned responses and call $bot->handle($update) with an update array: no network needed. See tests/Support/FakeTransport.php.

pam composer verify   # PHPStan level 9 + PHPUnit

Architecture

your PHP code
      │
      ▼
PAM Telegram ─── middleware, filters, sessions, scenes
      │
      ▼
Transport ────── cURL keep-alive · PAM HTTP client · PHP streams
      │
      ▼
Telegram Bot API (official HTTPS API)

Responsible use

Telegram limits bulk messaging and bans bots that spam. Only message users who started your bot, honour /stop, and use RateLimiter for broadcasts. This project is not affiliated with Telegram.

License

Open source under the Apache License 2.0. You may use, modify, and distribute it, including commercially. API design inspired by grammY (MIT); see NOTICE.