Skip to content

TelegramBotClient

Viames Marino edited this page Mar 26, 2026 · 1 revision

Pair framework: TelegramBotClient

Pair\Services\TelegramBotClient is Pair's current Telegram Bot API client.

It is the class to use when a Pair project needs:

  • outbound Telegram notifications
  • custom bot commands or message handling
  • webhook validation
  • file download from Telegram storage
  • low-level access to Bot API methods that Pair does not wrap explicitly

This class deliberately combines modern wrapper methods such as sendMessage() with historic convenience helpers such as message() and photo(), so existing Pair applications can migrate without keeping two Telegram abstractions around.

Constructor

__construct(?string $botToken = null, ?string $apiBaseUrl = null, ?int $timeout = null, ?int $connectTimeout = null, ?string $webhookSecretToken = null)

Builds the client from explicit arguments or .env.

Relevant env keys:

  • TELEGRAM_BOT_TOKEN
  • TELEGRAM_API_BASE_URL
  • TELEGRAM_TIMEOUT
  • TELEGRAM_CONNECT_TIMEOUT
  • TELEGRAM_WEBHOOK_SECRET_TOKEN

Webhook-only flows can instantiate the client without a bot token, but outbound methods and file download methods require a token.

Main methods

call(string $method, array $params = [], string $httpMethod = 'POST'): mixed

Low-level escape hatch for any Bot API method.

Use it when Telegram adds a new endpoint and your project wants to use it immediately without waiting for a dedicated wrapper.

use Pair\Services\TelegramBotClient;

$telegram = new TelegramBotClient();

// Call a Bot API method that does not need a dedicated Pair wrapper.
$telegram->call('setMyCommands', [
    'commands' => [
        [
            'command' => 'status',
            'description' => 'Show current system status',
        ],
    ],
]);

sendMessage(int|string $chatId, string $text, array $options = []): array

Sends a text message.

$options is passed through to Telegram, so this is the method most projects use for HTML formatting, silent notifications, inline keyboards, and similar Bot API parameters.

use Pair\Services\TelegramBotClient;

$telegram = new TelegramBotClient();

// Send an HTML-formatted notification to a private chat.
$telegram->sendMessage(123456789, '<b>Deployment completed</b>', [
    'parse_mode' => 'HTML',
    'disable_notification' => true,
]);

sendPhoto(int|string $chatId, string $photo, ?string $caption = null, array $options = []): array

Sends a photo using:

  • a local file path
  • a Telegram file_id
  • an HTTP / HTTPS URL

If the value looks like a local file path but the file does not exist, Pair fails fast with PairException instead of sending a broken payload to Telegram.

use Pair\Services\TelegramBotClient;

$telegram = new TelegramBotClient();

// Upload a local file directly from disk.
$telegram->sendPhoto('@channelusername', '/tmp/daily-report.png', 'Daily report', [
    'disable_notification' => true,
]);

sendChatAction(int|string $chatId, string $action, array $options = []): bool

Sends actions such as typing or upload_photo.

use Pair\Services\TelegramBotClient;

$telegram = new TelegramBotClient();

// Show the typing indicator before generating a slower response.
$telegram->sendChatAction(123456789, 'typing');

setWebhook(string $url, array $options = []): bool

Registers the bot webhook endpoint.

If the client has a configured webhook secret token and secret_token is not passed explicitly, Pair injects it automatically.

use Pair\Services\TelegramBotClient;

$telegram = new TelegramBotClient();

// Register the webhook and let Pair inject the configured secret token.
$telegram->setWebhook('https://example.com/api/telegramWebhook', [
    'allowed_updates' => ['message', 'callback_query'],
    'drop_pending_updates' => true,
]);

assertWebhookSecretToken(?string $providedToken = null): void

verifyWebhookSecretToken(?string $providedToken = null): bool

Use these methods in webhook endpoints to validate the X-Telegram-Bot-Api-Secret-Token header.

If you do not pass an explicit token, Pair reads the header from $_SERVER.

use Pair\Services\TelegramBotClient;

$telegram = new TelegramBotClient();
$payload = file_get_contents('php://input') ?: '';

// Reject spoofed requests before decoding the update.
$telegram->assertWebhookSecretToken();
$update = $telegram->decodeWebhookPayload($payload);

decodeWebhookPayload(string $payload): array

Decodes the raw webhook JSON and throws if the body is empty or invalid.

This keeps controller code smaller and avoids repeating the same JSON validation logic in each project.

getFile(string $fileId): array

downloadFileContents(string $filePath): string

downloadFileToPath(string $filePath, string $destinationPath): string

These methods cover the standard Telegram file flow:

  1. read the file metadata with getFile()
  2. take the returned file_path
  3. download the file contents or save them to disk
use Pair\Services\TelegramBotClient;

$telegram = new TelegramBotClient();

// Resolve the Telegram file path and persist the binary locally.
$file = $telegram->getFile($fileId);
$telegram->downloadFileToPath($file['file_path'], '/tmp/telegram-upload.bin');

Common integration patterns

Outbound notifications from app code

use Pair\Services\TelegramBotClient;

$telegram = new TelegramBotClient();

// Reuse the same client anywhere the app needs lightweight alerts.
$telegram->sendMessage(123456789, 'New order received: #' . $order->id);

Webhook endpoint

use Pair\Services\TelegramBotClient;

$telegram = new TelegramBotClient();

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    $payload = file_get_contents('php://input') ?: '';

    // Validate the shared secret before reading the update body.
    $telegram->assertWebhookSecretToken();
    $update = $telegram->decodeWebhookPayload($payload);

    // Route the Telegram update inside your application.
}

Polling during development or migrations

use Pair\Services\TelegramBotClient;

$telegram = new TelegramBotClient();

// Useful for quick debugging when a webhook is not configured yet.
$updates = $telegram->getUpdates([
    'limit' => 10,
    'timeout' => 0,
]);

Logger integration

Pair's Logger can use this client for Telegram alerts. In the current codebase, the logger instantiates TelegramBotClient when these values are configured:

  • TELEGRAM_BOT_TOKEN
  • PAIR_LOGGER_TELEGRAM_CHAT_IDS
  • PAIR_LOGGER_TELEGRAM_THRESHOLD

That makes TelegramBotClient the shared Telegram integration point for both direct messaging code and framework-level error notifications.

Secondary methods

  • botTokenSet(): bool tells you whether outbound requests can be made.
  • webhookSecretTokenSet(): bool tells you whether webhook-secret validation is configured.
  • getWebhookInfo(): array returns Telegram's current webhook metadata.
  • deleteWebhook(bool $dropPendingUpdates = false): bool removes the webhook.
  • getChat(int|string $chatId): array fetches live metadata for a chat.
  • chatId(string $username): ?int tries to resolve a numeric chat ID by scanning recent updates, so it is useful but not a universal directory lookup.
  • username(int|string $chatId): ?string returns @username when the chat exposes one.
  • link(int|string $chatId): string builds a public t.me link from the resolved username.
  • message() and photo() are legacy convenience aliases for sendMessage() and sendPhoto().

Notes

  • Outbound methods throw if the bot token is missing.
  • setWebhook() can also upload a local certificate path; Pair converts it to CURLFile internally.
  • Null values are filtered out before request dispatch, while booleans and zeroes are preserved.

See also: Integrations, Configuration file, Env, Logger, PairException.

Clone this wiki locally