Now it’s time to talk about sending alerts to Telegram. Indeed the alerts were first sent to Telegram in late 2020 and a new decision was made to switch to Discord instead this May. The script part will be largely the same. The major difference is that Discord and Telegram treat new lines differently, so the string manipulation part is a bit different. Also they use different markdown syntaxes.
If you do not know how to create Telegram groups and bots, you can follow the official documentation from the following links.
https://telegram.org/tour/groups
https://core.telegram.org/bots
After all the Telegram part has been set up, we can proceed with the rest.
The aliases part is just like the one shown in the previous post, what is really different is the script part, shown below with minor modifications.
#!/bin/bash
HEADER=`echo -n "*$1 Alert:* "`
TIMESTAMP=`date +%Y-%m%d-%H%m.%S`
FILE="/dev/shm/mail-${TIMESTAMP}"
TELEGRAM_BOT_TOKEN=7361XXXXX:AAE0rPfUcwktDttOtfXhBgiJ91JIEBXXXXX
CHAT_ID=-3212XXXXX
sed '' > $FILE
MSG=`sed '/^From /,/^To:/d' $FILE | sed '2,/^$/d' | sed 's/^Subject.*/&\n/' | sed 's/\n/%0A/'`
MSG="${HEADER}${MSG}"
curl -s -X POST https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/sendMessage -d chat_id=${CHAT_ID} -d text="$MSG" -d parse_mode='Markdown'
rm $FILE
After the script is ready and set to executable, the same email stream shown in the previous post will result in a Telegram message like the screenshot shown below.
A sample Telegram alert sent from vCenter.
I’ll also cover how to send alerts from Fortigate or F5 Big IP in future posts.