Developing a production Telegram bot in Yii2 requires an architectural approach that goes beyond isolated cURL calls inside a controller. When a bot starts processing hundreds of incoming messages per minute, sending service notifications, and running background queue jobs, the lack of a single service layer leads to code duplication, testing difficulties, and crashes during timeouts or rate limit breaches Telegram Bot API.
In this article, we will build an isolated TelegramClient component for Yii2, configurable via the DI container. We will extract sensitive data into params-local.php, set up custom логирование ошибок API handling, JSON response processing, and automatic retries when encountering a 429 Too Many Requests error.
Why a Telegram Bot in Yii2 Needs a Separate Service Layer
A typical mistake when starting development in Yii2 is accessing the Telegram API directly via third-party wrapper libraries right inside WebhookController action methods or console commands. This creates several issues:
- Tight coupling: You cannot mock HTTP-клиент in unit tests or switch to a test bot token for staging.
- Secret leaks: Tokens end up in version control systems (Git) if hardcoded in source files or shared configuration files.
- Unhandled failures: On a network failure (timeout) or a
429 Retry-Afterresponse, the controller throws an unhandled exception, causing Telegram to resend the Webhook and duplicating events.
Decoupling the Bot API interaction logic into a separate service (component) with DI injection ensures fault tolerance and centralized network error handling.
Secure Configuration Storage: params.php and params-local.php
The Telegram-бот token is the primary access key for controlling your bot. It should never be committed to a repository. In the Yii2 framework, the standard configuration splitting mechanism relies on merging the params.php file (base values and keys) with params-local.php (environment-specific values added to .gitignore).
Let's define the base configuration structure in config/params.php:
<?php
return [
'adminEmail' => 'admin@example.com',
'telegram' => [
'botToken' => '', // Базовое пустое значение
'apiUrl' => 'https://api.telegram.org/bot',
'timeout' => 10,
'maxRetries' => 3,
],
];The token value is overridden in config/params-local.php, which reads an environment variable or contains the secret string locally:
<?php
return [
'telegram' => [
'botToken' => getenv('TELEGRAM_BOT_TOKEN') ?: '1234567890:ABCdefGHIjklMNOpqrsTUVwxyZ_example',
],
];Implementing the TelegramClient Component with cURL
Let's create the app\components\TelegramClient class inheriting from yii\base\Component. The component will handle sending HTTP POST requests via cURL, response status validation, JSON format error handling, and delays on Retry-After responses.
<?php
namespace app\components;
use Yii;
use yii\base\Component;
use yii\base\InvalidConfigException;
class TelegramClient extends Component
{
public string $botToken = '';
public string $apiUrl = 'https://api.telegram.org/bot';
public int $timeout = 10;
public int $maxRetries = 3;
public function init(): void
{
parent::init();
if (empty($this->botToken)) {
throw new InvalidConfigException('Параметр telegram.botToken должен быть заполнен.');
}
}
/**
* Выполнение запроса к Telegram Bot API
*/
public function request(string $method, array $params = []): array
{
$url = $this->apiUrl . $this->botToken . '/' . $method;
$attempt = 0;
while ($attempt < $this->maxRetries) {
$attempt++;
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $url,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => http_build_query($params),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => $this->timeout,
CURLOPT_CONNECTTIMEOUT => 5,
]);
$response = curl_exec($ch);
$errno = curl_errno($ch);
$error = curl_error($ch);
$httpCode = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
// Обработка сетевых ошибок cURL
if ($errno !== 0) {
Yii::error("cURL error ({$errno}): {$error} [Method: {$method}]", 'telegram');
if ($attempt >= $this->maxRetries) {
return [
'ok' => false,
'error_code' => 500,
'description' => 'cURL error: ' . $error
];
}
usleep(500000); // Задержка 500мс перед повтором
continue;
}
// Валидация JSON
$data = json_decode($response, true);
if (json_last_error() !== JSON_ERROR_NONE) {
Yii::error("Invalid JSON response: {$response} [Method: {$method}]", 'telegram');
return [
'ok' => false,
'error_code' => 500,
'description' => 'Invalid JSON response from Telegram'
];
}
// Обработка лимита запросов HTTP 429 Too Many Requests
if ($httpCode === 429) {
$retryAfter = $data['parameters']['retry_after'] ?? 1;
Yii::warning("Telegram 429 Rate Limit. Wait {$retryAfter}s (Attempt {$attempt}/{$this->maxRetries})", 'telegram');
if ($attempt < $this->maxRetries) {
sleep((int)$retryAfter);
continue;
}
}
// Логирование ошибок API со стороны Telegram (ok: false)
if ($httpCode !== 200 || empty($data['ok'])) {
$desc = $data['description'] ?? 'Unknown API Error';
Yii::error("Telegram API Error [HTTP {$httpCode}]: {$desc} [Method: {$method}]", 'telegram');
}
return $data;
}
return ['ok' => false, 'error_code' => 429, 'description' => 'Max execution retries exceeded'];
}
}Registering the Component in the Yii2 DI Container
To make the TelegramClient class available across all controllers, console commands, and background Queue Jobs via внедрение зависимостей (Dependency Injection), configure the Yii2 DI container in config/web.php or config/main.php.
<?php
$params = array_merge(
require __DIR__ . '/params.php',
require __DIR__ . '/params-local.php'
);
$config = [
'id' => 'app-bot',
'basePath' => dirname(__DIR__),
'components' => [
// Логирование ошибок Telegram в отдельный файл
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
'categories' => ['telegram'],
'logFile' => '@runtime/logs/telegram.log',
],
],
],
],
'container' => [
'singletons' => [
\app\components\TelegramClient::class => function () use ($params) {
return new \app\components\TelegramClient([
'botToken' => $params['telegram']['botToken'] ?? '',
'apiUrl' => $params['telegram']['apiUrl'] ?? 'https://api.telegram.org/bot',
'timeout' => $params['telegram']['timeout'] ?? 10,
'maxRetries' => $params['telegram']['maxRetries'] ?? 3,
]);
},
],
],
];
return $config;Using the Service in WebhookController
Now, component injection happens automatically via the constructor of the controller or action method. We inject dependencies and handle the incoming /start command, creating a unique lead identifier in the database.
<?php
namespace app\controllers;
use Yii;
use yii\web\Controller;
use yii\web\Response;
use app\components\TelegramClient;
class WebhookController extends Controller
{
public $enableCsrfValidation = false;
private TelegramClient $telegram;
// Внедрение TelegramClient через DI Контейнер
public function __construct($id, $module, TelegramClient $telegram, $config = [])
{
$this->telegram = $telegram;
parent::__construct($id, $module, $config);
}
public function actionIndex(): Response
{
$rawInput = Yii::$app->request->getRawBody();
$update = json_decode($rawInput, true);
if (!$update || !isset($update['message'])) {
return $this->asJson(['status' => 'ignored']);
}
$message = $update['message'];
$chatId = $message['chat']['id'] ?? null;
$text = trim($message['text'] ?? '');
if ($chatId && $text === '/start') {
// Генерация криптографически стойкого lead_id
$leadId = bin2hex(random_bytes(7));
// Сохранение лида в БД (пример)
Yii::$app->db->createCommand()->insert('leads', [
'lead_hash' => $leadId,
'chat_id' => $chatId,
'created_at' => time(),
])->execute();
// Отправка ответа пользователю через сервисный слой
$response = $this->telegram->request('sendMessage', [
'chat_id' => $chatId,
'text' => "Заявка зарегистрирована! Ваш номер: <b>" . htmlspecialchars($leadId) . "</b>",
'parse_mode' => 'HTML',
]);
if (empty($response['ok'])) {
Yii::error("Failed to send reply to chatId {$chatId}", 'telegram');
}
}
return $this->asJson(['status' => 'ok']);
}
}Logging and API Error Monitoring
By isolating the telegram category in FileTarget, all cURL network errors, invalid server responses, and HTTP statuses from 400 to 500 are logged to a separate file, runtime/logs/telegram.log. This allows monitoring system health without sifting through the general application log.
Key considerations when handling rate limits:
- When sending messages to different users, Telegram's limit is approximately 30 messages per second.
- During bulk broadcasts, an HTTP 429 error with a
retry_afterparameter is returned. A recursive or loop retry usingsleep()prevents message loss from background queues (Yii Queue). - Validating
json_last_error()protects against crashes during Telegram maintenance, when the server might return an HTML page with a 502/504 Bad Gateway error instead of valid JSON.
The BotCreator team helps build scalable turnkey Telegram solutions and complex integrations using https://botservice.biz.