Setup Telegram bot to get alert notifications
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.
How do we setup that ? Let’s find out.
Contents
- Create a Telegram bot
- Send message using Telegram bot
- 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.
- Search for
botfather
in telegram and open its chat. Make sure it has blue tick to confirm its authenticity.
2. To list all the available options/commands, type /start
in chatbox. It will list all the available command you can send to botfather.
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.
7. Once Chat bot is created, Send any message to chatbot. This will create a chat room, with bot.
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
.
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.
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.
- Login to uptime kuma and open settings.
- Click on
Notifications
andSetup Notification
- Choose
Notification Type
asTelegram
and add bot token and Chat id in respective fields.
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