Advertisement
ighormaia

Send Telegram Message

Mar 6th, 2025
33
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 1.21 KB | None | 0 0
  1. #!/bin/bash
  2.  
  3. # This script sends a Telegram message using the Telegram Bot API.
  4.  
  5. # Load environment variables from the .env file
  6. export $(grep -v '^#' "$(dirname "$0")/../.env" | xargs)
  7.  
  8. # Variables
  9. MESSAGE=$1
  10. TOKEN=$2
  11. CHAT_ID=$3
  12.  
  13. escape_markdown() {
  14.     local text="$1"
  15.     text=$(echo "$text" | sed 's/[-.]/\\&/g')
  16.     echo "$text"
  17. }
  18.  
  19. # Use the provided token if available, otherwise fall back to .env
  20. if [[ -n "$TOKEN" ]]; then
  21.     TELEGRAM_TOKEN="$TOKEN"
  22. fi
  23.  
  24. # Use the provided chat id if available, otherwise fall back to .env
  25. if [[ -n "$CHAT_ID" ]]; then
  26.     TELEGRAM_CHAT_ID="$CHAT_ID"
  27. fi
  28.  
  29. # Ensure required variables are set
  30. if [[ -z "$TELEGRAM_TOKEN" || -z "$TELEGRAM_CHAT_ID" ]]; then
  31.     echo "Error: Telegram configuration (TELEGRAM_TOKEN, TELEGRAM_CHAT_ID) is not set."
  32.     exit 1
  33. fi
  34.  
  35. # Send the message with Markdown formatting
  36. CURL_OUTPUT=$(curl -s -X POST "https://api.telegram.org/bot$TELEGRAM_TOKEN/sendMessage" \
  37.     -d chat_id="$TELEGRAM_CHAT_ID" \
  38.     -d text="$(escape_markdown "$MESSAGE")" \
  39.     -d parse_mode="MarkdownV2" 2>&1)
  40.  
  41. # Check if curl failed
  42. if [[ $? -eq 0 ]]; then
  43.     echo "$MESSAGE"
  44. else
  45.     echo "Failed to send the message."
  46.     echo "$CURL_OUTPUT"
  47. fi
  48.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement