Get Server Notification on Telegram App

Monitoring the server is crucial to have uninterrupted services. There are different ways to configure alerts from the server. Here is an interesting way to get the notification from the server right on your Telegram Messenger application.

Telegram Messenger
Telegram is a cloud-based mobile and desktop messaging app with a focus on security and speed. For more details, please visit the official website.

Telegram Bot
Bots are simply Telegram accounts operated by software. They can do almost everything that a user can do in the chat application. For more details, refer to this link

Here, we will be using this bot feature to send notifications from server to Telegram Messenger application.

Creating Telegram Bot

  • By using botfather in the Telegram, we can create a new bot. Go to the search field in the Telegram and type botfather.
  • Go to message field and click on start.

Telegram-1

  • Type ‘/newbot’ without quotes in the message field and hit enter
  •  Now bot father asks you to name the new bot. Give any name of your choice. In this example, it is named as ‘Jarvis’.

Telegram-2

  • Bot requires a unique username. Type a username of your choice. If it is already taken, try a different one.
  • Once a username is successfully generated, you’ll get a congratulatory message from botfather with the token id of the bot. This token ID is used in the Telegram API to send messages.

Telegram-3

 

  • Next we need to get the chat ID. Search for the newly created bot in the search field and start a chat session.

Telegram-4

Telegram-5

          In the screenshot, the highlighted section has the chat id.
          In case of group chat, the bot has to be invited to the group and then run getupdates API to get the chat ID. The group chat ID will have a negative sign at the beginning.

Telegram-6

Simple bash script to send notification via telegram bot.

#!/bin/bash chat_id="123456789"
token="112233445:AABbcd1FfggHHi22jkLmmn0PPQQRstu"
msg="Test Message" curl -s -F chat_id=$chat_id -F text="$msg" https://api.telegram.org/bot$token/sendMessage > /dev/null

Bash Script to send report to telegram if high resource usage is found in the server.

Here is a bash script that can monitor server load and memory usage at regular intervals. It has been tested on Centos 7. The telegram API is used to send attachment instead of just text message. This is because sending text has character limit. Resource usage statistics can be sent in attachment instead of plain message.

#!/bin/bash
#This script monitors server load and memory usage for every 10 seconds and sends notification to telegram in case of high usage.

#Include telegram chat id and bot token ID here
chat_id="123456789"
token="112233445:AABbcd1FfggHHi22jkLmmn0PPQQRstu"

#Temporary files to store data
resource_usage_info=/tmp/resource_usage_info.txt
msg_caption=/tmp/telegram_msg_caption.txt

#Set threshold levels for memory usage and load here. If the usage exceeds these values, the notification will be sent.
mem_threshold=90 #Should be interger. This is in percentage
load_threshold=$(nproc) #Should be integer. Usually total number of cores.

#Telegram API to send notificaiton.
function telegram_send
{
curl -s -F chat_id=$chat_id -F document=@$resource_usage_info -F caption="$caption" https://api.telegram.org/bot$token/sendDocument > /dev/null 2&>1
}

#Monitoring Load on the server
while :
do
    min_load=$(cat /proc/loadavg | cut -d . -f1)
    if [ $min_load -ge $load_threshold ]
        then
        echo -e "High CPU usage detected on $(hostname)\n$(uptime)" > $msg_caption
        echo -e "CPU usage report from $(hostname)\nServer Time : $(date +"%d%b%Y %T")\n\n\$uptime\n$(uptime)\n\n%CPU %MEM USER\tCMD" >         $resource_usage_info
        ps -eo pcpu,pmem,user,cmd | sed '1d' | sort -nr >> $resource_usage_info
        caption=$(<$msg_caption)
        telegram_send
        rm -f $resource_usage_info
        rm -f $msg_caption
        sleep 900 #stop executing script for 15 minutes
    fi
    sleep 10

#Monitoring Memory usage on the server
    mem=$(free -m)
    mem_usage=$(echo "$mem" | awk 'NR==2{printf "%i\n", ($3*100/$2)}')
    if [ $mem_usage -gt $mem_threshold ]
    then
        echo -e "High Memory usage detected on $(hostname)\n$(echo $mem_usage% memory usage)" > $msg_caption
        echo -e "Memory consumption Report from $(hostname)\nServer Time : $(date +"%d%b%Y %T")\n\n\$free -m output\n$mem\n\n%MEM %CPU USER\tCMD" > $resource_usage_info
        ps -eo pmem,pcpu,user,cmd | sed '1d' | sort -nr >> $resource_usage_info
        caption=$(<$msg_caption)
        telegram_send
        rm -f $resource_usage_info
        rm -f $msg_caption
        sleep 900 #stop executing script for 15 minutes
    fi
    sleep 10
done

 

VIDEO

Thanks for reading the article. If you have any questions, leave the comments below.


Author: Deekshith Hadil
I am a computer geek. Fan of Linux and opensource. Love to try out different Linux Distributions. I currently work as System Engineer at Assistanz Networks. Have 3+ years of experience in webhosting, Linux and Servers.

14 Comments

  • p0150n

    Guess it isn’t working anymore… {“ok”:false,”error_code”:403,”description”:”Forbidden: bot can’t send messages to bots”}

  • Seems like bot is not configured correctly. Don’t use the token id, chat id given in the tutorial. These are dummy values.
    After creating the bot, you need to initiate chat with the bot by searching it in the search box. Then identify its chat ID.

  • suresh

    do you have any method to add multi user into script?

  • You can add multi users by modifying the script.

    The script can be modified as given below. For example, here are two different chatid and token ids.

    #Include telegram chat id and bot token ID here
    chat_id1="123456789"
    token1="112233445:AABbcd1FfggHHi22jkLmmn0PPQQRstu"
    chat_id2="9876654321"
    token1="15432345:AABbxxxxxxwwwwwwrrrrrmn0PPQQRstu"

    Include the additional users API

    #Telegram API to send notificaiton.
    function telegram_send
    {
    curl -s -F chat_id=$chat_id1 -F document=@$resource_usage_info -F caption="$caption" https://api.telegram.org/bot$token1/sendDocument > /dev/null 2&>1
    curl -s -F chat_id=$chat_id2 -F document=@$resource_usage_info -F caption="$caption" https://api.telegram.org/bot$token2/sendDocument > /dev/null 2&>1
    }

    Best option to send same notification to mulitple users is by creating a group. In place of user’s chat ID, you can mention the group ID. It starts with negative sign for group.

  • suresh

    thank you very much on the multi user script! and what do you mean by adding multiple user into a group?do you have example for that? so sorry for asking a lot.hehehe

  • Telegram allows you to create group and add members to it. You can check more details in this link

    After creating a group, add the telegram bot to it. So here bot is a member of the group. Then search for its id in the similar way which is mentioned in the above tutorial. Add other members to this group so that the message sent by bot can be viewed by everyone. Even you can have conversation in the same group.

  • suresh

    ahh i understand now.Thank you

  • Rendika Yoga

    can you help me how to make message notification via telegram
    when i start the script for download, bot will send me message Download will start and when download finish Bot will send me message Download Finished. I will Combine this notification with lftp to mirroring server this is script for my mirroring
    https://gist.github.com/pixeline/0f9f922cffb5a6bba97a

  • Domas

    Hi. Great tutorial !!! It is possible to send comands to Linux server from chat ?

  • @Rendika Yoga:
    You can use the method ‘sendMessage’ to send only messages without fileattachment.
    More info available here : https://core.telegram.org/bots/api#sendmessage

  • Rendika Yoga

    Okay Thank, Can I ask you about the problem why I can not send messages using bash script on Linux Server A but when I apply the bash script on linux server B I get the message sent Linux Server B, At first it can run on Linux server A but when Bash Notifications I created two types of Notification Update finished and Resource like the example above Server Linux A I can not send any more messages to my own ID. On Linux Servers A and B I use the same BOT but only from Server B that can send messages to my own ID Thanks

  • Shouki

    Great post! works perfectly. Is it possible to send a recovery mesaage after a high utilisation mesaage has gone?

  • @Rendika The telegram API should work in any server. API calls are made over https or http. You should check if you can reach port 80 and 443 of api.telegram.org in the server where you are facing problem.

  • @Shouki : It is possible. You can follow up the git link given below. I will get it updated soon.
    https://bitbucket.org/deekshith-hadil/server-load-monitor/src/master/

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.