Prerequisites
Before setting up Telegram alerts, make sure you have:
- SSH access to your VPS
- A Telegram account
- Basic scripting knowledge
Step 1: Create a Telegram Bot
- Open Telegram and search for @BotFather
- Send
/newbotand follow prompts - Save the API token (looks like
123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11) - Get your Chat ID by messaging @userinfobot
Step 2: Create Alert Script
Connect to your VPS:
ssh hxroot@YOUR_SERVER_IP -p 22
sudo nano /usr/local/bin/telegram-alert.sh
Add content (replace TOKEN and CHAT_ID):
#!/bin/bash
TOKEN="YOUR_BOT_TOKEN"
CHAT_ID="YOUR_CHAT_ID"
MESSAGE="$1"
URL="https://api.telegram.org/bot$TOKEN/sendMessage"
curl -s -X POST $URL -d chat_id=$CHAT_ID -d text="$MESSAGE" > /dev/null
Make executable:
sudo chmod +x /usr/local/bin/telegram-alert.sh
Step 3: Test Alert Script
sudo /usr/local/bin/telegram-alert.sh "✅ Test alert from $(hostname)"
You should receive a Telegram message.
Step 4: Send Alerts for Specific Events
High CPU alert:
#!/bin/bash
CPU_LOAD=$(uptime | awk -F 'load average:' '{print $2}' | cut -d, -f1 | sed 's/ //g')
THRESHOLD=2.0
if (( $(echo "$CPU_LOAD > $THRESHOLD" | bc -l) )); then
/usr/local/bin/telegram-alert.sh "⚠️ High CPU load on $(hostname): $CPU_LOAD"
fi
Low disk space alert:
#!/bin/bash
USAGE=$(df -h / | awk 'NR==2 {print $5}' | sed 's/%//')
THRESHOLD=85
if [ $USAGE -gt $THRESHOLD ]; then
/usr/local/bin/telegram-alert.sh "⚠️ Low disk space on $(hostname): ${USAGE}% used"
fi
Failed SSH login alert:
#!/bin/bash
FAILED=$(grep "Failed password" /var/log/auth.log | tail -5)
if [ ! -z "$FAILED" ]; then
/usr/local/bin/telegram-alert.sh "⚠️ Failed SSH attempts on $(hostname):
$FAILED"
fi
Reboot alert:
#!/bin/bash
/usr/local/bin/telegram-alert.sh "🔄 $(hostname) has been rebooted at $(date)"
Step 5: Schedule Alerts with Cron
sudo crontab -e
Add:
# Check CPU every 5 minutes
*/5 * * * * /usr/local/bin/cpu-alert.sh
# Check disk every hour
0 * * * * /usr/local/bin/disk-alert.sh
# Check failed logins every 10 minutes
*/10 * * * * /usr/local/bin/failed-login-alert.sh
Step 6: Send HTML Formatted Messages
Modify script to support HTML:
curl -s -X POST $URL -d chat_id=$CHAT_ID -d text="$MESSAGE" -d parse_mode="HTML"
Example:
/usr/local/bin/telegram-alert.sh "<b>CRITICAL</b>: Server <i>$(hostname)</i> is down!"
✅ Telegram alerts configured. You will receive notifications for important server events.