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 ===
curl -s -X POST "https://api.telegram.org/bot$TELEGRAM_TOKEN/sendMessage" \
-d chat_id="$TELEGRAM_CHAT_ID" \
-d text="$MESSAGE" \
-d parse_mode="Markdown"
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