Skip to content

Instantly share code, notes, and snippets.

@ravikant-pal
Last active July 15, 2025 13:48
Show Gist options
  • Save ravikant-pal/cdcd36cf1bf2cc25d25a21df1feb2c3a to your computer and use it in GitHub Desktop.
Save ravikant-pal/cdcd36cf1bf2cc25d25a21df1feb2c3a to your computer and use it in GitHub Desktop.
Telegram Notification — System Alerting Exercise

📣 Telegram Notification — System Alerting Exercise

⏱ Duration: 45 minutes

👨‍💻 Mode: Individual Hands-on

🧰 Tools: Bash, curl, Telegram Bot API

📡 Real-World Application: System Monitoring + Automation


🎯 Objective

Write a Bash script that checks system health (CPU & memory usage), and when it crosses a defined threshold, sends a real-time Telegram message using the Telegram Bot API and curl.


🛠 Setup (One-Time Configuration)

1. Create Your Telegram Bot

  • Open Telegram and search @BotFather

  • Start with /start/newbot

  • Set name and username (e.g., sithealthbot)

  • Copy your bot token, e.g.:

    123456789:ABCDefGhIjklMNOPQRST_uvWXyZ123456
    

2. Get Your Chat ID

  • Open Telegram and send any message to your new bot

  • Run:

    curl -s https://api.telegram.org/bot<your_token>/getUpdates
  • Note the chat.id from the response:

    "chat":{"id":123456789,...}
    

📜 Script: health_alert_telegram.sh

#!/bin/sh

# ===============================
# 🔧 Telegram Bot Configuration
# ===============================
TOKEN="<your_bot_token>"        # Replace with your actual bot token
CHAT_ID="<your_chat_id>"        # Replace with your actual chat ID

# ===============================
# 📊 System Usage Calculations
# ===============================

# ✅ CPU usage (BusyBox/Alpine compatible)
CPU=$(top -bn1 | grep "^CPU:" | awk '{gsub("%", "", $8); print 100 - $8}')

# ✅ Memory usage using /proc/meminfo (no 'free' dependency)
MEM=$(awk '/MemTotal/ {total=$2} /MemAvailable/ {avail=$2} END {printf("%.0f", (total - avail) / total * 100)}' /proc/meminfo)

# 🕒 Timestamp in IST with AM/PM
TIME=$(TZ="Asia/Kolkata" date "+%Y-%m-%d %I:%M:%S %p IST")

# ===============================
# ✉️ Telegram Message Formatting
# ===============================
MSG="🚨 *System Alert!*
*CPU:* ${CPU}%
*Memory:* ${MEM}%
*Time:* ${TIME}"

# ===============================
# 🚦 Alert Logic (customizable thresholds)
# ===============================
if [ "$CPU" -gt 75 ] || [ "$MEM" -gt 80 ]; then
  echo "⚠️ High resource usage detected. Sending alert to Telegram..."
  curl -s -X POST "https://api.telegram.org/bot${TOKEN}/sendMessage" \
    -d chat_id="${CHAT_ID}" \
    -d text="$MSG" \
    -d parse_mode="Markdown"
else
  echo "✅ System healthy. CPU=${CPU}%, MEM=${MEM}%."
fi

✅ How to Use

  1. Make it executable:

    chmod +x health_alert_telegram.sh
  2. Run the script:

    ./health_alert_telegram.sh
  3. If CPU or memory exceeds thresholds, you’ll receive a Telegram message instantly.


💡 Bonus Ideas

  • Add disk usage alerts with df -h

  • Write alerts to a log file (alert.log) for audit

  • Schedule hourly checks using cron:

    crontab -e
    # Every hour:
    0 * * * * /path/to/health_alert_telegram.sh

📚 Concepts Reinforced

Bash Feature Real-World Application
curl API integration / webhook automation
awk, top, free Resource monitoring
Bash conditions Control logic for alert thresholds
Telegram Bot API Serverless communication for alerts

📌 Sample Telegram Output

🚨 System Alert!
CPU: 84.3%
Memory: 91%
Time: Sat Jul 13 14:20:01 IST 2025

“This is how you go from developer to DevOps — one webhook at a time.” 🛠️💬

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment