Setup Telegram bot to get alert notifications (2024)

There are many other channels where we can receive notifications. Email, Discord, Ntfy.sh, Gotify and many others. But sometime we need to get notification on a chat apps we already use, so that we don’t need to install any third application and can be accessed from our cellphone or desktop.

Telegram can be useful in this case. It is an open-source chat app used by millions. It boast to be more secure and privacy-focused chat application.

We can create a telegram bot which is a non-human account which will be used to send message on Telegram. This can be utilized to send alerts from your self-hosted applications, servers alert or any other kind of notifications. This can also be used to create chat-bot.

Setup Telegram bot to get alert notifications (3)

How do we setup that ? Let’s find out.

Contents

  1. Create a Telegram bot
  2. Send message using Telegram bot
  3. Use Cases
    1. Receive Alert to Telegram when root volume of server is getting full
    2. Setup Telegram notification in uptime kuma
    3. Send telegram notification using Golang program

All the credentials, bots, chat ids and accounts created during this demo and visible on screenshots are temporary and are deleted before publishing this article.

Create a Telegram bot

A telegram bot is born from his father, which is another bot which creates bots.

  1. Search for botfather in telegram and open its chat. Make sure it has blue tick to confirm its authenticity.
Setup Telegram bot to get alert notifications (4)

2. To list all the available options/commands, type /start in chatbox. It will list all the available command you can send to botfather.

Setup Telegram bot to get alert notifications (5)

3. Send /newbot to create a bot. This command may change in future. So always refer the output of /start command first.

4. It will ask you for a name of bot. I will use Media Server Alert name. Type the name in chatbox and send it to botfather.

5. Next, It will ask for username for bot. Username must end with bot like myusername_bot or myusernamebot. In my case, I will give linuxshots_mediaserver_alert_bot. Bot’s username should be unique across Telegram.

6. Once you provide username, Botfather will respond you with chat link of new bot and a HTTP API token. Keep API token secure and safe as anyone with token can use and send any message using your Telegram bot.

Setup Telegram bot to get alert notifications (6)

7. Once Chat bot is created, Send any message to chatbot. This will create a chat room, with bot.

Setup Telegram bot to get alert notifications (7)

8. Get Chat ID of the chatroom using bot API. We will use curl utility on Linux for API call.

curl https://api.telegram.org/bot<bot-api-token>/getUpdates

Replace <bot-api-token> with your HTTP token of bot.

Fetch the chat id from the json output. It should be under results[0].message.chat.id.

Setup Telegram bot to get alert notifications (8)

Send message to chat using bot

To send a message to chat using chat, We need to use Telegram Bot API. Here, I will be using curl on Linux bash shell to make the API call. Any other available tool or programming language can also be used like Potsman, Golang, Python or any other.

To send message, Use below command on Linux

curl -X POST https://api.telegram.org/bot<bot-api-token>/sendMessage -H 'Content-Type: application/json' -d '{"chat_id": "<chat-id>", "text": "<Your Message>"}'

Replace <bot-api-token> with telegram bot’s HTTP token, <chat-id> with chat id fetched in previous step and <Your Message> with your message.

After running this, You should be receiving the message from bot in your chat box.

Setup Telegram bot to get alert notifications (9)
Setup Telegram bot to get alert notifications (10)

Use Cases:

1. Receive Alert to Telegram when root volume of server is getting full

Lets write a simple script which will check root volume size and used space. If used space is greater than 80%, It should send a alert to telegram.

Create a bash script file root-volume-alert.sh

#!/usr/bin/env bash
used_space_perc=$(df -h / | tail -1 | tr -s " " | cut -d " " -f 5 | tr -d "%")
if [ $used_space_perc -gt 80 ]; then
curl -X POST https://api.telegram.org/bot<bot-api-token>/sendMessage -H 'Content-Type: application/json' -d '{"chat_id": "<chat-id>", "text": "ALERT! Root volume is about to be full. Current usage is $used_space_perc %"}'
fi

Execute this script using cron every 30 min.

crontab -e

# Add below line to execute it every 30 minutes
0,30 * * * * bash /path/to/script/root-volume-alert.sh

That’s it.

2. Setup Telegram notification in uptime Kuma

Uptime Kuma is an opensource self-hosted tool used to check health status of our applications or servers and send alert.

  1. Login to uptime kuma and open settings.
  2. Click on Notifications and Setup Notification
  3. Choose Notification Type as Telegram and add bot token and Chat id in respective fields.
Setup Telegram bot to get alert notifications (11)

3. Send telegram notification using Golang program

Telegram bot can also be utilized in any application or tool developed using Golang. Below snippet of a Go function sends a Telegram message to chatId.

// LICENSE

// MIT License

// Copyright (c) 2023 Navratan Lal Gupta

// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

func SendTelegramNotification(botToken, chatId, message string) error {

log.Println("Preparing to send Telegram notification")

type reqBody struct {
ChatId string `json:"chat_id"`
Text string `json:"text"`
}

apiUrl := "https://api.telegram.org/bot" + botToken + "/sendMessage"

// Create request

var reqBodyValue reqBody

reqBodyValue.ChatId = chatId
reqBodyValue.Text = message

reqBodyValueJson, err := json.Marshal(reqBodyValue)
if err != nil {
log.Println("Failed to send Telegram notification", err.Error())
return err
}

requestBodyJson := bytes.NewReader(reqBodyValueJson)
if err != nil {
log.Println("Failed to send Telegram notification", err.Error())
return err
}

req, err := http.NewRequest(http.MethodPost, apiUrl, requestBodyJson)
if err != nil {
log.Println("Failed to send Telegram notification", err.Error())
return err
}

req.Header.Add("accept", "application/json")
req.Header.Add("Content-Type", "application/json")

// Create client
client := http.Client{
Timeout: 30 * time.Second,
}

// Make request
res, err := client.Do(req)
if err != nil {
log.Println("Failed to send Telegram notification", err.Error())
return err
}

if res.StatusCode/100 != 2 {
log.Println("Failed to send Telegram notification", res.Status)
return errors.New("Failed to send Telegram notification")
}

log.Println("Notification sent to Telegram")

return nil
}

Similar way, Telegram bot can be used with Python, Java script or any other programming language. Many opensource tools come with feature to integrate Telegram notification.

You can read more about Telegram bot and its API here, https://core.telegram.org/bots/

Hope this article helped you know more about telegram bots. Don’t forget to clap if you liked it.

You can support my article by buying me a cup of coffee on https://www.buymeacoffee.com/linuxshots.

Thanks

Navratan Lal Gupta

Linux Shots

Setup Telegram bot to get alert notifications (2024)

References

Top Articles
Request Letter for Replacement of Tyres - Sample Letter for Requesting Tyres Replacement of Company Vehicle - Letters in English
5 Templates and 7 Examples: How to Write a Memo - Status.net
Swissport Timecard
排期 一亩三分地
Kpschedule Lawson
211475039
Smoke Terminal Waterbury Photos
Sarah Bustani Boobs
Best Transmission Service Margate
Frank 26 Forum
Cristiano Ronaldo's Jersey Number: The Story Behind His No. 7 Shirt | Football News
Minneapolis Rubratings
Black Adam Showtimes Near Kerasotes Showplace 14
Bullocks Grocery Weekly Ad
Honda Accord 2012 gebraucht - AutoUncle
Blind Guardian - The God Machine Review • metal.de
Craigslist Shelves
Traveltalkonline
Juliewiththecake Wiki / Biography - Age, Boyfriend, Height, Net Worth - WikiBravo
The Four Fours Puzzle: To Infinity and Beyond!
Amsterdam, Netherlands to PST - Savvy Time
Mynorthwoodtech
David Knowles, journalist who helped make the Telegraph podcast Ukraine: The Latest a runaway success
Jennifer Beals Bikini
Numerous people shot in Kentucky near Interstate 75, officials say | CNN
Seanna: meaning, origin, and significance explained
Baddiehub Cover
Shaws Star shines bright selling for 16,000gns at the Red Ladies and Weaned Calf sale.
پنل کاربری سایت همسریابی هلو
Insidekp.kp.org Myhr Portal
افضل موقع سكسي عربي
Po Box 182223 Chattanooga Tn 37422 7223
north bay garage & moving sales "moving" - craigslist
How to Learn Brazilian Jiu‐Jitsu: 16 Tips for Beginners
Busted Barren County Ky
Influencing Factors and Differences in Born Aggregometry in Specialized Hemostaseological Centers: Results of a Multicenter Laboratory Comparison
Aig Cyberedge Policy Wording
Dicks Sporting Good Lincoln Ne
8004966305
Glassbox Eyecare
Black Adam Showtimes Near Cinemark Texarkana 14
Raz-Plus Literacy Essentials for PreK-6
Mvsu Canvas
Honda Fury Forums
Webworx Call Management
Broadcastify Thurston County
Deml Ford Used Cars
Stafford Rotoworld
Ohio (OH) Lottery Results & Winning Numbers
SF bay area cars & trucks "chevrolet 50" - craigslist
Funny Roblox Id Codes 2023
Lizzyboat African Market
Latest Posts
Article information

Author: Arline Emard IV

Last Updated:

Views: 6086

Rating: 4.1 / 5 (52 voted)

Reviews: 83% of readers found this page helpful

Author information

Name: Arline Emard IV

Birthday: 1996-07-10

Address: 8912 Hintz Shore, West Louie, AZ 69363-0747

Phone: +13454700762376

Job: Administration Technician

Hobby: Paintball, Horseback riding, Cycling, Running, Macrame, Playing musical instruments, Soapmaking

Introduction: My name is Arline Emard IV, I am a cheerful, gorgeous, colorful, joyous, excited, super, inquisitive person who loves writing and wants to share my knowledge and understanding with you.