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

  1. Open Telegram and search for “BotFather.”

  2. Start a chat with BotFather and run the command:

    /newbot

  3. Follow the instructions to name your bot and get a unique token.

  4. Save the API token for later use.


Step 2: Install Required Packages

  1. 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

  1. Create a script to send messages:

    sudo nano /usr/local/bin/telegram_notify.sh

  2. 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"

  3. Make the script executable:

    sudo chmod +x /usr/local/bin/telegram_notify.sh


Step 4: Find Your Chat ID

  1. Run the following command to get your chat ID:

    curl -s "https://api.telegram.org/bot/getUpdates" | jq .

  2. Look for “chat”:{“id”:<chat_id>} in the output and note the ID.


Step 5: Set Up a Server Event Notification

  1. Create a Systemd service to notify on a system event:

    sudo nano /etc/systemd/system/telegram-alert.service

  2. 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

  3. Save and close the file.

  4. Enable and test the service:

    sudo systemctl daemon-reload

    sudo systemctl start telegram-alert.service


Step 6: Automate Alerts with Cron

  1. Edit the crontab:

    crontab -e

  2. 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.