admin-scripts/helpers/tg_notify.sh

55 lines
1.5 KiB
Bash
Executable File

#!/bin/bash
################################################################################
# TG_NOTIFY.SH
# ------------
# This script takes input via stdin or parameters, replaces newlines with
# telegram compatible ones and then sends the message to a chat
#
# Author: Robin Meier - robin@meier.si
################################################################################
script_dir=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
set -o allexport
source ${script_dir}/../config/tg_notify
set +o allexport
BOT_API_URL=https://api.telegram.org/bot${BOT_TOKEN}
# Get input from standard input or via first parameter
if [[ $# -eq 0 ]]; then
MESSAGE=$(timeout 32 cat)
elif [[ $# -eq 1 ]]; then
MESSAGE=$1
elif [[ $# -eq 2 ]]; then
CHAT_ID=$1
MESSAGE=$2
else
echo "[ERROR] Too many arguments!"
fi
# Exit if input is empty
if [[ -z "${MESSAGE}" ]]; then
exit 0
fi
# Replace newlines in message for telegram
TG_MESSAGE=${MESSAGE//$'\n'/\%0A}
# Send telegram to chat
resp=$(curl -s -f -X POST ${BOT_API_URL}/sendMessage -d chat_id=$CHAT_ID -d text="⚠️ *$(hostname -s | tr . ' ')* ⚠️%0A\`\`\`%0A${TG_MESSAGE}%0A\`\`\`" -d parse_mode=markdown)
# Check if request succeeded
if [[ $? -ne 0 ]]; then
echo "[ERROR] Telegram request failed!"
else
if [ "${resp:1:9}" == "\"ok\":true" ]; then
# echo "Sent Telegram: \n${MESSAGE//$'\n'/\n}"
sleep 0
else
echo "[ERROR] Telegram sending did not succeed: $resp"
echo "MESSAGE: \n${MESSAGE//$'\n'/\n}"
fi
fi