The Bot API Client
Pam\Telegram\Api is a thin client for the whole Telegram Bot API. Every method works, including methods Telegram adds after this package was released, because the client does not need a wrapper per method. The bot exposes its client as $bot->api and every context as $ctx->api; you can also use it on its own, for example to send notifications from a queue worker.
use Pam\Telegram\Api;
$api = new Api(getenv('TELEGRAM_BOT_TOKEN'));
$api->sendMessage(chat_id: 123456789, text: 'Your report is ready.');Calling methods
Section titled “Calling methods”There are three equivalent ways to call a method:
$api->sendMessage(chat_id: 42, text: 'Hi'); // named arguments$api->sendMessage(['chat_id' => 42, 'text' => 'Hi']); // one array$api->call('sendMessage', ['chat_id' => 42, 'text' => 'Hi']); // explicitEach returns Telegram’s result field decoded as PHP arrays and scalars. Parameters with a null value are omitted, and objects such as keyboards are JSON-encoded for you. Pass a third argument to call() to override the request timeout in seconds.
Constructor options
Section titled “Constructor options”use Pam\Telegram\Api;use Pam\Telegram\RateLimiter;
$api = new Api( getenv('TELEGRAM_BOT_TOKEN'), transport: null, // AutoTransport baseUrl: 'https://api.telegram.org', timeout: 15.0, // seconds per request maxRetries: 3, // retries after HTTP 429 maxRetryAfter: 60.0, // longest retry_after to wait for rateLimiter: new RateLimiter(), // optional);The token is validated when the client is created, and it never appears in exception messages or in var_dump() output.
To share one configured client with a bot, pass it instead of the token: new Bot($api).
Errors
Section titled “Errors”| Exception | Thrown when |
|---|---|
Pam\Telegram\Exception\TelegramException |
Telegram refused the request. Has method, errorCode, description, and parameters. |
Pam\Telegram\Exception\TransportException |
The Bot API could not be reached, or the response was invalid. |
use Pam\Telegram\Exception\TelegramException;
try { $api->sendMessage(chat_id: $chatId, text: 'Hello');} catch (TelegramException $exception) { if ($exception->errorCode === 403) { // The user blocked the bot: stop messaging them. }
if (($newId = $exception->migrateToChatId()) !== null) { // The group became a supergroup: store $newId and retry there. }}retryAfter() returns the retry_after seconds from a flood-control error, or null.
Flood control and retries
Section titled “Flood control and retries”When Telegram answers HTTP 429, the client waits retry_after seconds and tries again, up to maxRetries times, as long as the wait is no longer than maxRetryAfter. Network errors are not retried, so a message is never sent twice because a response was lost.
Rate limiting broadcasts
Section titled “Rate limiting broadcasts”Telegram limits how fast a bot may send: roughly 30 messages per second overall, 1 per second to the same private chat, and 20 per minute to the same group. Replies to a single user rarely hit these limits, but broadcasts do. Give the client a RateLimiter and it spaces out every send*, copyMessage, and forwardMessage call:
$api = new Api($token, rateLimiter: new RateLimiter( perSecond: 30.0, // overall privateChatInterval: 1.0, // seconds between messages to one private chat groupInterval: 3.0, // seconds between messages to one group or channel));
foreach ($subscriberIds as $chatId) { $api->sendMessage(chat_id: $chatId, text: 'Our summer sale starts today!');}Chat IDs that start with - or @ are treated as groups and channels. The limiter waits by sleeping: inside a PAM request it yields to the event loop, elsewhere it uses usleep(). It tracks at most 10,000 chats by default (maxTrackedChats).
Transports
Section titled “Transports”The client sends requests through a Pam\Telegram\Transport\Transport. The default AutoTransport picks the first one available:
CurlTransport: ext-curl with a reused keep-alive connection.PamTransport: the PAM runtime HTTP client.StreamTransport: plain PHP streams, which need no extension.
Pass new PamTransport() to make Bot API calls non-blocking inside a PAM HTTP request: the request is handed to the runtime, so other requests in the same worker keep running while Telegram answers. This is the best choice for webhook handlers served by PAM.
use Pam\Telegram\Bot;use Pam\Telegram\Transport\PamTransport;
$bot = new Bot(getenv('TELEGRAM_BOT_TOKEN'), new PamTransport());Transports never follow redirects and never include the request URL, which contains the token, in their errors. To use your own HTTP stack, implement the interface’s single request() method.
Self-hosted Bot API server
Section titled “Self-hosted Bot API server”To use a self-hosted Telegram Bot API server, for example to download files larger than 20 MB, change the base URL:
$api = new Api($token, baseUrl: 'http://localhost:8081');Downloading files
Section titled “Downloading files”$bytes = $api->download($fileId); // up to 20 MB by default$bytes = $api->download($fileId, 50 * 1024 * 1024); // raise the limit (self-hosted servers)See Downloading files for a complete handler.