Bot Notifications using Telegram

This PHP setup is based off of the excellent Python article provided by Man Hay Hong.

To get started you need to download/install Telegram and set yourself up as a user.

Once it is installed you need to setup a new bot by interacting with @BotFather and sending the following:

  • /start {this will provide some help info}
  • /newbot {@botfather will walk you through creating your new bot}

You now have your bot token – keep this safe as it enables anyone to control your bot and for you to interact through it.

Now you need your chatID so using the following URL in your browser you will see the additional info you need:


Look for the following and record the digits as that is your chatID:

{"id":xxxxxxxxxxxxx <<<<<< chatID

Again, keep this information secure.

I used the following PHP code to then send messages from my internal web server. The code does also check that any messages sent originate internally otherwise it throws an error.

$bot_token = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
$bot_chatid = 'xxxxxxxxxxxx';

/* telegram_getUpdates() - get telepgram update info */
function telegram_getUpdates() {
global $bot_token;

$send_mesg = '' . $bot_token . '/getUpdates';
$retval = file_get_contents($send_mesg);

return $retval;

/* telegram_notify() - send message to telegram user from bot */
function telegram_notify($mesg) {
global $bot_token, $bot_chatid;

$url = '' . $bot_token . '/sendMessage';
$data = array('chat_id' => $bot_chatid , 'parse_mode' => 'Markdown', 'text' => $mesg);

// use key 'http' even if you send the request to https://...
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);

$retval = json_decode( $result);

return $retval;

if (preg_match('/192\.168\.1\./', $_SERVER['HTTP_X_REAL_IP'])) {
// Local network access via WEB
$mesg = '';

if (isset($_GET['mesg'])) {
/* We have a message to send so send it! */
$mesg = htmlspecialchars($_GET["mesg"]);

$result =  telegram_notify($mesg);
if ( $result->ok == true) 
echo "Sent";
echo "Failed - " . $result->description;
} else {
/* No message so get the status instead */
$result = telegram_getUpdates();
echo $result;
} else {
// If we see a remote connection then send a 404



About Warren Cross

A contract IT professional that has been in the technology industry a number of years at various blue chip companies. During his career he has been a successful application developer, analyst, project manager, IT manager and system administrator, and performed in both global and local roles. For contract opportunities feel free to contact Warren through this site.
This entry was posted in Code, Uncategorized and tagged , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *