Loading..
Processing... Please wait...

Product was successfully added to your shopping cart.



How to send Telegram phone alarms with PHP script for dummies

Recently I had some CPU outages on one of the servers I overlook.

It started randomly and I didn't know what the problem was. By the time I got to the server outage had already ended.

I was wondering if there was a way I could get an instance notification right to my phone when outage started. Then I could get to the server right away and see what was going on.

Turned out there was a way - Telegram Messenger. Its api let's you send messages from PHP script (it also supports a bunch of other languages).

Telegram Messenger Telegram Messenger

Disclaimer: it was a bit difficult to figure out how to setup Telegram to send alarms with PHP. I have to say that documentation is quite complex and confusing. Here I will describe the steps I took to make it work. Maybe there is the right way to do that I don't know of but those steps worked me and I guess this tutorial saves you some hair pulling time.

 

1. Install Telegram on your phone.

Go to App Store or Google Play Market and install Telegram APP. That should be straightforward.

 

2. Create a Telegram bot.

Once you install Telegram you have to create a bot. Bot is a special thing that will be actually doing all the dirty work. You will reference a bot by its Bot Token.

2.1 Go to https://telegram.me/botfather in your browser on your phone:

Botfather open in a browser
Botfather open in a browser

Click on send message and it will bring up Telegram app with botfather chat open.

BotFather chat
BotFather chat

With botfather help you will create your own bot.

Now click on Start and then type in /newbot :

Newbot command
Newbot command

Click send. It will ask for bot name. Enter any name you like (for example 'chatty'). Click send.

Then it will ask for bot username. It must end with 'bot'. Choose any username you like for example chatty123Bot. (chattyBot might have been already taken by somebody else)

Then telegram will create your new bot and will send its Bot Token:

New Bot Token
New Bot Token

Official documentation can be found here.

Now go to https://telegram.me/<your bot username> in your phone browser. (in out case that would be https://telegram.me/Chatt123Bot)

It will open a telegram bot conversation window. Click start.

New Bot Chat Window
New Bot Chat Window

Now we can move forward to installing Telegram PHP API.

You have to have PHP 7 in order to run API.

 

2. Install a composer

Composer is a dependency checker for PHP projects. We will be using it to install Telegram PHP API.

Install composer on Debian 8:

curl -sS https://getcomposer.org/installer | sudo php -- --install-dir=/usr/local/bin --filename=composer

Taken from here.

 

3. Install Telegram PHP API

Here is a complete Telegram PHP API project on github.

We will install it with composer.

First create a directory:

mkdir telegram

Then go to that directory and create a composer project:

composer init

Answer a few questions, set the name of your project, author etc. It is all pretty much self explanatory.

Then open up the newly created composer.json and "unreal4u/telegram-api": "~2.3" require section so that composer.json looks like this (name,type,authors might vary):

{
    "name": "root/telegram",
    "type": "project",
    "authors": [
        {
            "name": "Konstantin G.",
            "email": "sales@goivvy.com"
        }
    ],
    "require": {
      "unreal4u/telegram-api": "~2.3"     
    }
}

Once it is done install composer dependencies:

composer install

It will install telegram api and its dependencies:

root ~/telegram # composer install
Do not run Composer as root/super user! See https://getcomposer.org/root for details
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 6 installs, 0 updates, 0 removals
  - Installing psr/log (1.0.2) Downloading: 100%         
  - Installing guzzlehttp/promises (v1.3.1) Downloading: 100%         
  - Installing psr/http-message (1.0.1) Downloading: 100%         
  - Installing guzzlehttp/psr7 (1.3.1) Downloading: 100%         
  - Installing guzzlehttp/guzzle (6.2.2) Downloading: 100%         
  - Installing unreal4u/telegram-api (v2.3.0) Downloading: 100%         
Writing lock file
Generating autoload files

Telegram API should now be installed and ready to be used.

 

4. Send message to your bot within PHP

First we need to get bot chat id.

Go to https://telegram.me/get_id_bot in your browser on your phone. It should open up get id bot chat telegram window:

Get id bot telegram chat window
Get id bot telegram chat window

Click on Start. It should display your Chat ID:

Your Chat ID
Your Chat ID

Now go to telegram folder you created on your server (the one you installed telegram-api to).

cd telegram

Create a php file with the following contents:

<?php
include('vendor/autoload.php');
use GuzzleHttp\Exception\ClientException;
use \unreal4u\TelegramAPI\TgLog;
use \unreal4u\TelegramAPI\Telegram\Methods\SendMessage;
$tgLog = new TgLog('<BOT_TOKEN>');
$sendMessage = new SendMessage();
$sendMessage->chat_id = <CHAT_ID>;
$sendMessage->text = "test message";
try {
    $tgLog->performApiRequest($sendMessage);
} catch (ClientException $e) {
    echo 'Error detected trying to send message to user: <pre>';
    var_dump($e->getRequest());
    echo '</pre>';
    die();
}

Where <BOT_TOKEN> and <CHAT_ID> are bot token and chat id you obtained earlier.

Execute this script with php:

php test.php

You should now receive a test message right on your phone!

Test message
Test message

 

5. Monitory CPU usage with instant notifications

Now we will be able to create a monitoring bash script that will alarm us if CPU load exceeds certain threashold.

#!/bin/bash
load=`cat /proc/loadavg | awk '{print $1}'`
response=`echo | awk -v T=8 -v L=$load 'BEGIN{if ( L > T){ print "greater"}}'`
if [[ $response = "greater" ]]
then
 /usr/bin/php /root/telegram/send.php
fi

I have 8 CPU cores and I choose to get alarms when load exceeds 8.

 

 

 

 

If you find this post interesting do not hesitate to sign up for our newsletter and join the 721 people who receive Magento news, tips and tricks regularly.

Thank You!

 

 

2 thoughts on “How to send Telegram phone alarms with PHP script for dummies”

  • Konstantin Gerasimov

    you should write to unreal4/telegram-api creators and ask how to make it work with php 5.6

  • Tijn

    Thanks for this post, cool initiative! My website is running on PHP 5.6, and currently I'm not able to upgrade due to incompatibilities of my site.
    At this moment I'm getting the following error:

    Loading composer repositories with package information
    Updating dependencies (including require-dev)
    Your requirements could not be resolved to an installable set of packages.

    Problem 1
    - Installation request for unreal4u/telegram-api ^2.3 -> satisfiable by unreal4u/telegram-api[v2.3.0].
    - unreal4u/telegram-api v2.3.0 requires php >=7.0.0 -> your PHP version (5.6.27) does not satisfy that requirement.

    Is there any way to make your method compatible with PHP 5.6?