Secure Telegram Notifications with .env Files

Saurab Thakur Saurab Thakur
⏳ 2 min read

Sending Telegram notifications from your server is πŸ”₯ powerful β€” but hardcoding your bot token and chat ID into scripts? 😱 That’s risky!

Let’s fix that. In this quick guide, you’ll learn how to safely store credentials in a .env file and use them in your telegram_notify.sh script β€” the right way. πŸ›‘οΈ


πŸ›‘οΈ Why Use a .env File?

  • πŸ”’ Security: Keep sensitive credentials out of your scripts.
  • πŸ—‚οΈ Organization: Manage all credentials in one clean place.
  • βœ… Best Practice: Industry-standard way to handle secrets.

πŸ› οΈ Step-by-Step Setup

1️⃣ Create the .env File

Store your Telegram Bot credentials securely:

sudo nano /usr/local/bin/.telegram.env

Add the following inside:

TELEGRAM_TOKEN="YOUR_TELEGRAM_BOT_TOKEN"
TELEGRAM_CHAT_ID="YOUR_TELEGRAM_CHAT_ID"

Secure it:

chmod 600 /usr/local/bin/.telegram.env

2️⃣ Modify telegram_notify.sh

Edit the script to use the .env file:

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

Paste this inside:

#!/bin/bash

# === LOAD VARIABLES FROM .env FILE ===
ENV_FILE="/usr/local/bin/.telegram.env"
if [ -f "$ENV_FILE" ]; then
    source "$ENV_FILE"
else
    echo "[ERROR] Environment file $ENV_FILE not found!"
    exit 1
fi

# === MESSAGE TO SEND ===
MESSAGE="$1"

# === SEND TO TELEGRAM β€” NO MARKDOWN (plain text, NO parse_mode) ===
curl -s -X POST "https://api.telegram.org/bot$TELEGRAM_TOKEN/sendMessage" \
     -d chat_id="$TELEGRAM_CHAT_ID" \
     -d text="$MESSAGE"

Make it executable:

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

3️⃣ Test It Out

Run the script:

/usr/local/bin/telegram_notify.sh "πŸ” Secure Telegram Notification Test!"

βœ… If everything's working, you’ll get a message on Telegram!


πŸŽ‰ Wrapping Up

Using a .env file makes your Telegram scripts:

  • βœ… Secure
  • βœ… Cleaner
  • βœ… Easier to manage in the long run

This tiny improvement can make your automation game safer and more professional. πŸ’ͺ


πŸ”— Also Check: Automated Docker Backup OpenMediaVault

Comments

Loading comments...