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