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:
- https://api.telegram.org/botput_your_token_here/getUpdates
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.
<?php
$bot_token = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
$bot_chatid = 'xxxxxxxxxxxx';
/* telegram_getUpdates() - get telepgram update info */
function telegram_getUpdates() {
global $bot_token;
$send_mesg = 'https://api.telegram.org/bot' . $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 = 'https://api.telegram.org/bot' . $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";
else
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
http_response_code(404);
}
?>