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
.
-
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
-
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,...}
#!/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
-
Make it executable:
chmod +x health_alert_telegram.sh
-
Run the script:
./health_alert_telegram.sh
-
If CPU or memory exceeds thresholds, you’ll receive a Telegram message instantly.
-
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
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 |
🚨 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.” 🛠️💬