Мониторинг сайта с алертами в Telegram позволяет мгновенно узнавать об ошибках PHP и падении сервера. Разберём как это настроить без внешних платных сервисов.
Создание Telegram-бота
- Напишите
@BotFather→/newbot - Получите токен:
7123456789:AAHxxx... - Узнайте chat_id: напишите боту, затем откройте
https://api.telegram.org/bot{TOKEN}/getUpdates
Функция отправки алерта
function sendTelegramAlert(string $message): void
{
$token = 'ВАШ_ТОКЕН';
$chatId = 'ВАШ_CHAT_ID';
$url = "https://api.telegram.org/bot{$token}/sendMessage";
$ctx = stream_context_create(['http' => [
'method' => 'POST',
'header' => "Content-Type: application/x-www-form-urlencoded",
'content' => http_build_query([
'chat_id' => $chatId,
'text' => $message,
'parse_mode' => 'HTML',
]),
'timeout' => 5,
]]);
@file_get_contents($url, false, $ctx);
}
Перехват PHP-ошибок в init.php
set_error_handler(function(int $errno, string $errstr, string $errfile, int $errline) {
if (in_array($errno, [E_ERROR, E_PARSE, E_CORE_ERROR])) {
sendTelegramAlert(
"🔴 <b>PHP Error</b>
"
. "Ошибка: {$errstr}
"
. "Файл: {$errfile}:{$errline}"
);
}
return false;
});
Проверка доступности через cron
// /local/cron/health_check.php
$response = @get_headers('https://ваш-сайт.ru/', 1);
$code = $response ? substr($response[0], 9, 3) : '000';
if ($code !== '200') {
sendTelegramAlert("🚨 Сайт недоступен! HTTP {$code}");
}
Добавьте в cron:
*/5 * * * * php /var/www/site/local/cron/health_check.php
Дополнительно: алерты из лога Nginx
tail -f /var/log/nginx/error.log | grep --line-buffered "PHP Fatal" |
while read line; do
curl -s -X POST "https://api.telegram.org/bot{TOKEN}/sendMessage"
-d "chat_id={CHAT_ID}&text=🔴 ${line}"
done
