Skip to content

Setting Up a Telegram Bot for VPS Alert Notifications

Published:

Create a Telegram Bot

  1. In Telegram, search for botfather ensuring it’s the verified one (marked with a blue tick).
  2. Initiate your bot creation by sending /newbot. Note: This command might change; always verify with /start.
  3. The BotFather will provide a chat link for your new bot and a crucial HTTP API token. Treat this token with utmost confidentiality as it grants full access to your bot. Example: 532613213321:AAHDSxxxxx_xxxxxsdoidsa

Retrieve the Chat ID

  1. Start by sending any message to your newly created bot.
  2. To fetch the Chat ID, we’ll employ the curl utility on Linux for making an API call.
  3. Execute: curl https://api.telegram.org/bot<bot-api-token>/getUpdates
  4. From the JSON output, locate the chat id under results[0].message.chat.id.

Send Messages to Chat Using Your Bot

Now you can send messages from your server, utilise the following 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>"}'

This is useful to be notified of problems that happens in your server, as an alternative of the email.

Use Case Example

Imagine you’ve set up a nightly backup routine on your VPS, designed to securely store your data on a remote storage. You can create a script that not only performs the backup but also notifies you via Telegram in the event of a failure:

...
# Execute the backup and upload process
# (The actual backup and upload commands should be here)

# Evaluate the success of the rclone command
if [ $? -eq 0 ]; then
    echo "Backup uploaded successfully to Cloudflare R2."
    ...
else
    echo "Failed to upload backup to Cloudflare R2."
    # Send Telegram Notification for failure
    curl -X POST https://api.telegram.org/bot69XXXXXXX:AXXXXXXXXXxxxxXXX-uxxxxE4h_XXXX/sendMessage \
    -H 'Content-Type: application/json' \
    -d '{"chat_id": "13XXXXXXX2", "text": "⚠️ Alert: Database backup upload to Cloudflare R2 failed."}'
fi
...