summaryrefslogtreecommitdiffstats
path: root/scripts/telegram-host-notification.sh
blob: 5d427095d1ecd500271a65afb14b773a41a704bc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#!/bin/sh
# (C) Tobias Wiese | GPLv2+
# This file is based on mail-host-notification.sh from Icinga used under GPLv2+ license
# Except of function urlencode which is Copyright (C) by Brian White (brian@aljex.com) used under MIT license
# Changes: The script was adapted to send Telegram Messages instead of mail.

PROG="$(basename $0)"
ICINGA2HOST="$(hostname)"

if [ -z "$(type curl)" ] ; then
	echo "curl not found in \$PATH. Consider installing it." 2>&1
	exit 1
fi

## Function helpers
urlencode() {
  local LANG=C i=0 c e s="$1"

  while [ $i -lt ${#1} ]; do
    [ "$i" -eq 0 ] || s="${s#?}"
    c=${s%"${s#?}"}
    [ -z "${c#[[:alnum:].~_-]}" ] || c=$(printf '%%%02X' "'$c")
    e="${e}${c}"
    i=$((i + 1))
  done
  echo "$e"
}

## Keep formatting in sync with telegram-service-notification.sh
for P in DATE HOSTNAME HOSTDISPLAYNAME HOSTOUTPUT HOSTSTATE USERCHATID TYPE
do
	eval "PAR=\$${P}"

	if [ ! "$PAR" ] ; then
		echo "Required parameter '$P' is missing." >&2
		exit 1
	fi
done

## Build the notification message
NOTIFICATION_MESSAGE=`cat << EOF
***** Host Monitoring on $ICINGA2HOST *****

$HOSTDISPLAYNAME is $HOSTSTATE!

Info:    $HOSTOUTPUT

When:    $DATE
Host:    $HOSTNAME
EOF
`

## Check whether IPv4 was specified.
if [ -n "$ADDRESS" ] ; then
	NOTIFICATION_MESSAGE="$NOTIFICATION_MESSAGE
IPv4:   $ADDRESS"
fi

## Check whether IPv6 was specified.
if [ -n "$ADDRESS6" ] ; then
	NOTIFICATION_MESSAGE="$NOTIFICATION_MESSAGE
IPv6:   $ADDRESS6"
fi

## Check whether author and comment was specified.
if [ -n "$COMMENT" ] ; then
	NOTIFICATION_MESSAGE="$NOTIFICATION_MESSAGE

Comment by $AUTHOR:
	$COMMENT"
fi

## Check whether Icinga Web 2 URL was specified.
if [ -n "$ICINGAWEB2URL" ] ; then
	NOTIFICATION_MESSAGE="$NOTIFICATION_MESSAGE

$ICINGAWEB2URL/monitoring/host/show?host=$(urlencode "$HOSTNAME")"
fi

## Check whether verbose mode was enabled and log to syslog.
if [ "$VERBOSE" = "true" ] ; then
	logger "$PROG sends Telegram => $CHATID"
fi

## Send message via telegram
curl -X POST "https://api.telegram.org/bot${TOKEN}/sendMessage" \
	--data-urlencode "chat_id=$USERCHATID" \
	--data-urlencode "text=$NOTIFICATION_MESSAGE" \
	--data-urlencode "disable_web_page_preview=true"