Creating a Telegram Bot to Notify You About Server Events
Introduction
Monitoring server events in real time can help you respond to issues quickly. By setting up a Telegram bot, you can receive instant notifications about important server activities. This guide will show you how to create a Telegram bot and configure it to send alerts from your server.
Step 1: Create a Telegram Bot
-
Open Telegram and search for “BotFather.”
-
Start a chat with BotFather and run the command:
/newbot
-
Follow the instructions to name your bot and get a unique token.
-
Save the API token for later use.
Step 2: Install Required Packages
-
Install Curl and jq to interact with the Telegram API:
sudo apt update && sudo apt install curl jq -y
Step 3: Create a Notification Script
-
Create a script to send messages:
sudo nano /usr/local/bin/telegram_notify.sh
-
Example script:
#./bin/bash
BOT_TOKEN="your-telegram-bot-token"
CHAT_ID="your-chat-id"
MESSAGE="$1"
curl -s -X POST "https://api.telegram.org/bot$BOT_TOKEN/sendMessage" -d chat_id="$CHAT_ID" -d text="$MESSAGE"
-
Make the script executable:
sudo chmod +x /usr/local/bin/telegram_notify.sh
Step 4: Find Your Chat ID
-
Run the following command to get your chat ID:
curl -s "https://api.telegram.org/bot/getUpdates" | jq .
-
Look for “chat”:{“id”:<chat_id>} in the output and note the ID.
Step 5: Set Up a Server Event Notification
-
Create a Systemd service to notify on a system event:
sudo nano /etc/systemd/system/telegram-alert.service
-
Example service file:
[Unit]
Description=Send Telegram Alert on Event
[Service]
ExecStart=/usr/local/bin/telegram_notify.sh "Alert: A critical event occurred on the server"
[Install]
WantedBy=multi-user.target
-
Save and close the file.
-
Enable and test the service:
sudo systemctl daemon-reload
sudo systemctl start telegram-alert.service
Step 6: Automate Alerts with Cron
-
Edit the crontab:
crontab -e
-
Add a line to send a message every day at midnight:
0 0 * * * /usr/local/bin/telegram_notify.sh "Daily server check-in: All systems operational."
Conclusion
By creating a Telegram bot, you can receive instant alerts about server events. You can extend this setup by integrating it with log monitoring or security tools like Fail2Ban.