-
Notifications
You must be signed in to change notification settings - Fork 2
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.
__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_TOKENTELEGRAM_API_BASE_URLTELEGRAM_TIMEOUTTELEGRAM_CONNECT_TIMEOUTTELEGRAM_WEBHOOK_SECRET_TOKEN
Webhook-only flows can instantiate the client without a bot token, but outbound methods and file download methods require a token.
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',
],
],
]);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,
]);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,
]);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');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,
]);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);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.
These methods cover the standard Telegram file flow:
- read the file metadata with
getFile() - take the returned
file_path - 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');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);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.
}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,
]);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_TOKENPAIR_LOGGER_TELEGRAM_CHAT_IDSPAIR_LOGGER_TELEGRAM_THRESHOLD
That makes TelegramBotClient the shared Telegram integration point for both direct messaging code and framework-level error notifications.
-
botTokenSet(): booltells you whether outbound requests can be made. -
webhookSecretTokenSet(): booltells you whether webhook-secret validation is configured. -
getWebhookInfo(): arrayreturns Telegram's current webhook metadata. -
deleteWebhook(bool $dropPendingUpdates = false): boolremoves the webhook. -
getChat(int|string $chatId): arrayfetches live metadata for a chat. -
chatId(string $username): ?inttries to resolve a numeric chat ID by scanning recent updates, so it is useful but not a universal directory lookup. -
username(int|string $chatId): ?stringreturns@usernamewhen the chat exposes one. -
link(int|string $chatId): stringbuilds a publict.melink from the resolved username. -
message()andphoto()are legacy convenience aliases forsendMessage()andsendPhoto().
- Outbound methods throw if the bot token is missing.
-
setWebhook()can also upload a local certificate path; Pair converts it toCURLFileinternally. - Null values are filtered out before request dispatch, while booleans and zeroes are preserved.
See also: Integrations, Configuration file, Env, Logger, PairException.