Advanced

Security

Telegram bot security requires proper handling of the token, HTTPS, and update processing. Use long polling for efficient event retrieval and always validate HTTP responses.

## Security Security is a critical aspect of any Telegram bot. The main protection principles include proper handling of the bot token, using HTTPS, error handling, and protection against unauthorized access. ### Authorization and Tokens To work with the Bot API, you need to store the token in the `TELEGRAM_BOT_TOKEN` environment variable. All requests are sent to `https://api.telegram.org` via HTTPS, which guarantees encrypted data transmission. The token is passed in the `Authorization` header or in the request body in the format `BOT_TOKEN=your_token`. Initialize the bot via @BotFather, then copy the token. To get your own identifier, use the `telegramApi()` function (see [First request: getMe](https://telegram-bot-api/first-request)):
$url = "https://api.telegram.org/bot" . getenv("TELEGRAM_BOT_TOKEN") . "/getMe";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
"Content-Type: application/json",
"Authorization: Bearer " . getenv("TELEGRAM_BOT_TOKEN")
]);
$response = curl_exec($ch);
curl_close($ch);
$data = json_decode($response, true);
echo $data->id;
### Update Handler and Long Polling To receive events from users, use the **long polling** mechanism. The bot constantly polls the server while there are no new updates. This reduces network load and increases responsiveness. Implement handling of `update_id` and `callback_data` to react to user actions. Example of handling an incoming update:
function handleUpdate($update) {
if ("update_id" === "123456789") {
// Обработка конкретного события
if (strpos($update->type, "message") !== false) {
// Новое сообщение от пользователя
$this->sendMessage($update.from.chat.id, "Вы написали: " . $update.message.text);
}
}
}
### Error Handling and Validation Always check the HTTP response status (`200 OK`) and the `ok` field in the JSON response. In case of server errors, use `json_last_error()` to diagnose issues. For secure payload processing, use `validateAndParsePayload()` (see [Deep links](https://telegram-bot-api/deep-links)). ### Token Rotation and Application Security If the token is leaked, immediately create a new bot via BotFather and update `TELEGRAM_BOT_TOKEN` in your code. Use static variables or configuration files instead of hardcoded strings in the code. For production deployment, it is recommended to implement retry logic and request processing queues (see [Production: queue and retries](https://telegram-bot-api/production)). ### Next: Production: queue and retries For high-load systems, it is recommended to use queues (Redis, RabbitMQ) and automatic retries during temporary failures. Next: Production: queue and retries