Skip to content

Instantly share code, notes, and snippets.

@gilangvperdana
Last active May 27, 2023 12:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gilangvperdana/96e3f50017aee8a2d00b8231939a7778 to your computer and use it in GitHub Desktop.
Save gilangvperdana/96e3f50017aee8a2d00b8231939a7778 to your computer and use it in GitHub Desktop.
Monitor an Endpoint on Telegram
<?php
// Config information
$server = "IP/DOMAINWHOTOMONITOR"; // the address to test, without the "http://"
$port = "PORT";
// Telegram Bot API configuration
$telegramToken = 'YOURTELEGRAMTOKEN';
$chatId = 'YOURTELEGRAMCHATID';
// Create a text file to store the result of the ping for comparison
$db = "pingdata.txt";
if (file_exists($db)) {
$previous_status = file_get_contents($db, true);
} else {
file_put_contents($db, "up");
$previous_status = "up";
}
// Ping the server and check if it's up
$current_status = ping($server, $port, 10);
// If it's down, log it and send alert
if ($current_status == "down") {
echo "Server is down! ";
file_put_contents($db, "down");
if ($previous_status == "up") {
sendTelegramMessage("Server is down!");
echo "Alert sent.";
}
} else {
echo "Server is up! ";
file_put_contents($db, "up");
if ($previous_status == "down") {
sendTelegramMessage("Server is back up!");
echo "Alert sent.";
}
}
function ping($host, $port, $timeout)
{
$tB = microtime(true);
$fP = fsockopen($host, $port, $errno, $errstr, $timeout);
if (!$fP) {
return "down";
}
$tA = microtime(true);
return round((($tA - $tB) * 1000), 0) . " ms";
}
function sendTelegramMessage($message)
{
global $telegramToken, $chatId;
$telegramUrl = "https://api.telegram.org/bot" . $telegramToken . "/sendMessage";
$telegramParams = [
"chat_id" => $chatId,
"text" => $message,
];
$ch = curl_init($telegramUrl);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($telegramParams));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment