Skip to content

Polling & Webhooks

Telegram delivers updates to a bot in one of two ways. With long polling, your bot asks Telegram for updates in a loop; it needs no public URL and is the simplest way to run a bot on PAM. With webhooks, Telegram sends each update to an HTTPS endpoint you expose; it suits applications that already serve HTTP. Your handlers are the same either way.

Long polling Webhooks
Public HTTPS URL Not needed Required
Process One long-running process Your web server
Sessions MemorySessionStore is fine Use a persistent store outside PAM
Start with $bot->run() $bot->setWebhook($url) once, then handleWebhook()

A bot can use only one at a time: run() deletes any configured webhook before it starts polling.

$bot->run();

run() accepts optional arguments:

Argument Default Description
timeout 30 Seconds Telegram holds each request open (0 to 50).
allowedUpdates [] Update types to receive, such as ['message', 'callback_query']. Empty means Telegram’s default set.
dropPendingUpdates false Discard updates that arrived while the bot was offline.
limit 100 Maximum updates per request (1 to 100).
shouldStop null A closure checked before each request; return true to stop.
$bot->run(
allowedUpdates: ['message', 'callback_query'],
dropPendingUpdates: true,
);

Network errors and Telegram server errors are retried with exponential backoff, up to 30 seconds between attempts. Errors that need you to act are thrown instead: 401 (invalid token), 404, and 409 (another instance is polling, or a webhook is set and could not be removed).

$bot->stop() ends the loop after the current update. When the loop ends, the bot confirms the updates it handled with one last getUpdates call, so a restart does not process them again.

run() stops on SIGINT and SIGTERM automatically only under the PHP CLI SAPI with the PCNTL extension. Under PAM the SAPI is not cli, so install the handlers yourself; PCNTL is available in PAM:

bot.php
pcntl_async_signals(true);
pcntl_signal(SIGINT, fn () => $bot->stop());
pcntl_signal(SIGTERM, fn () => $bot->stop());
$bot->run();

Without handlers, Ctrl+C ends the process immediately. Updates handled before the last poll are still confirmed by that poll, so at most the batch being processed at that moment can be delivered again.

Telegram allows a single getUpdates consumer per bot token. Running two copies of the same bot makes one of them fail with error 409. To scale, switch to webhooks behind a load balancer.

Create the bot with a secret token and register your endpoint once, for example from a deploy script:

$bot = new Bot(getenv('TELEGRAM_BOT_TOKEN'), webhookSecret: getenv('TELEGRAM_WEBHOOK_SECRET'));
$bot->setWebhook('https://example.com/telegram', [
'allowed_updates' => ['message', 'callback_query'],
'drop_pending_updates' => true,
]);

The secret must be 1 to 256 characters of A-Z, a-z, 0-9, _, and -. Telegram sends it back in the X-Telegram-Bot-Api-Secret-Token header of every request, and handleWebhook() rejects requests without the right value using a constant-time comparison.

handleWebhook($body, $secretHeader) processes one update and returns the HTTP status to answer with:

Status When
401 The secret header is missing or wrong.
400 The body is not a JSON update.
200 The update was handled, even if a handler threw.

A handler error still answers 200 so Telegram does not redeliver the same update in a loop; the error goes to your catch() handler or error_log().

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

Create the Bot once at boot and reuse it for every request; in a persistent PAM worker the memory session store keeps working across requests handled by the same worker. See PAM HTTP for routing.

routes/web.php
use Illuminate\Http\Request;
Route::post('/telegram', fn (Request $request) => response('', $bot->handleWebhook(
$request->getContent(),
$request->header('X-Telegram-Bot-Api-Secret-Token'),
)));

Exclude the route from CSRF protection, and give the bot a CacheSessionStore so sessions survive between requests.

public/telegram.php
http_response_code($bot->handleWebhook(
file_get_contents('php://input'),
$_SERVER['HTTP_X_TELEGRAM_BOT_API_SECRET_TOKEN'] ?? null,
));