Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/bin/bash
- # This script sends a Telegram message using the Telegram Bot API.
- # Load environment variables from the .env file
- export $(grep -v '^#' "$(dirname "$0")/../.env" | xargs)
- # Variables
- MESSAGE=$1
- TOKEN=$2
- CHAT_ID=$3
- escape_markdown() {
- local text="$1"
- text=$(echo "$text" | sed 's/[-.]/\\&/g')
- echo "$text"
- }
- # Use the provided token if available, otherwise fall back to .env
- if [[ -n "$TOKEN" ]]; then
- TELEGRAM_TOKEN="$TOKEN"
- fi
- # Use the provided chat id if available, otherwise fall back to .env
- if [[ -n "$CHAT_ID" ]]; then
- TELEGRAM_CHAT_ID="$CHAT_ID"
- fi
- # Ensure required variables are set
- if [[ -z "$TELEGRAM_TOKEN" || -z "$TELEGRAM_CHAT_ID" ]]; then
- echo "Error: Telegram configuration (TELEGRAM_TOKEN, TELEGRAM_CHAT_ID) is not set."
- exit 1
- fi
- # Send the message with Markdown formatting
- CURL_OUTPUT=$(curl -s -X POST "https://api.telegram.org/bot$TELEGRAM_TOKEN/sendMessage" \
- -d chat_id="$TELEGRAM_CHAT_ID" \
- -d text="$(escape_markdown "$MESSAGE")" \
- -d parse_mode="MarkdownV2" 2>&1)
- # Check if curl failed
- if [[ $? -eq 0 ]]; then
- echo "$MESSAGE"
- else
- echo "Failed to send the message."
- echo "$CURL_OUTPUT"
- fi
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement