admin-scripts/telegram_notification.sh

58 lines
1.6 KiB
Bash
Executable File

#!/bin/bash
################################################################################
# TELEGRAM_NOTIFICATION.SH
# ------------------------
# This script takes input via stdin or parameters, removes timestamps from each
# line and replaces newlines with telegram compatible ones and then sends the
# message to a chat
#
# Author: Robin Meier - robin@meier.si
################################################################################
set -o allexport
source /root/scripts/.telegram_notification_env
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 30 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
# Strip timestamps from message
if [ "${MESSAGE:0:12}" == "$(echo '' | ts "[%Y-%m-%d")" ]; then
MESSAGE=$(echo -e "$MESSAGE" | cut -c 23-)
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 | 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}"
else
echo "[ERROR] Telegram sending did not succeed: $resp"
echo "MESSAGE: \n${MESSAGE//$'\n'/\n}"
fi
fi