back to scripts

notify-admin.sh

bash 76 lines secrets redacted

Central dispatcher for admin notifications.

Note Live script from my home-lab server. Tokens, IDs, phone numbers and other secrets have been replaced with placeholders like <WHATSAPP_GROUP_ID> — everything else is the real, running code.
#!/usr/bin/env bash
set -u
CONFIG=/etc/lanky-alerts/alerts.env
LOG=/home/lanky/reports/notify-admin.log
mkdir -p /home/lanky/reports

message="${*:-}"
if [ -z "$message" ]; then
  echo "Usage: $0 message" >&2
  exit 2
fi

if [ -f "$CONFIG" ]; then
  # shellcheck disable=SC1090
  . "$CONFIG"
fi
prefix="${ALERT_PREFIX:-[lankyserver]}"
body="$prefix $message"
provider="${ALERT_PROVIDER:-disabled}"

ts() { date -Is; }
log() { echo "[$(ts)] $*" >> "$LOG"; }

case "$provider" in
  disabled|''|callmebot_example|whapi_example|twilio_example)
    log "notification disabled/unconfigured: $body"
    exit 0
    ;;
  callmebot)
    if [ -z "${CALLMEBOT_PHONE:-}" ] || [ -z "${CALLMEBOT_APIKEY:-}" ]; then
      log "callmebot missing CALLMEBOT_PHONE or CALLMEBOT_APIKEY"
      exit 1
    fi
    curl -fsS --get 'https://api.callmebot.com/whatsapp.php' \
      --data-urlencode "phone=$CALLMEBOT_PHONE" \
      --data-urlencode "text=$body" \
      --data-urlencode "apikey=$CALLMEBOT_APIKEY" >/dev/null
    log "sent via callmebot"
    ;;
  whapi)
    if [ -z "${WHAPI_TOKEN:-}" ] || [ -z "${WHAPI_CHAT_ID:-}" ]; then
      log "whapi missing WHAPI_TOKEN or WHAPI_CHAT_ID"
      exit 1
    fi
    python3 - "$WHAPI_TOKEN" "$WHAPI_CHAT_ID" "$body" <<'PY'
import json, sys, urllib.request
_, token, chat_id, body = sys.argv
payload = json.dumps({'to': chat_id, 'body': body}).encode()
req = urllib.request.Request(
    'https://gate.whapi.cloud/messages/text',
    data=payload,
    headers={'Authorization': f'Bearer {token}', 'Content-Type': 'application/json'},
    method='POST',
)
with urllib.request.urlopen(req, timeout=20) as r:
    r.read()
PY
    log "sent via whapi"
    ;;
  twilio)
    if [ -z "${TWILIO_ACCOUNT_SID:-}" ] || [ -z "${TWILIO_AUTH_TOKEN:-}" ] || [ -z "${TWILIO_FROM:-}" ] || [ -z "${TWILIO_TO:-}" ]; then
      log "twilio missing required settings"
      exit 1
    fi
    curl -fsS -u "$TWILIO_ACCOUNT_SID:$TWILIO_AUTH_TOKEN" \
      --data-urlencode "From=$TWILIO_FROM" \
      --data-urlencode "To=$TWILIO_TO" \
      --data-urlencode "Body=$body" \
      "https://api.twilio.com/2010-04-01/Accounts/$TWILIO_ACCOUNT_SID/Messages.json" >/dev/null
    log "sent via twilio"
    ;;
  *)
    log "unknown provider '$provider': $body"
    exit 1
    ;;
esac

back to scripts