Now it’s the hard part on how to redirect the email alerts to Telegram or Discord. As Discord provides webhooks directly, we can format the the received email stream and then use the curl command to send the alert to Discord.
We can get the webhook from Copy Webhook URL.
As said in the previous post we can forward an email to a script, we now do this through vCenter’s built-in Sendmail server and use an email alias to do it. The aliases file is the file to do it and it is located in /etc/mail/aliases on vCenter. Add an entry like the following in aliases.
vm-alert: "| /usr/local/bin/send-alert VCenter"
The above will forward the email stream to the script file /usr/local/bin/send-alert after the command “newaliases” is run to add the entry to the aliases db.
Before we write our script to process the email stream and send to Discord, we need to know the content of a typical email. The following is an example alert from vCenter.
A typical email has extra headers that are not needed in the alert text. So our script file has to address this.
The following is my script with minor changes.
#!/bin/bash
HEADER=`echo -n "\n**$1:** \n\n"`
TIMESTAMP=`date +%Y-%m%d-%H%M.%S`
FILE="/dev/shm/mail-${TIMESTAMP}"
STATS=https://discord.com/api/webhooks/124521219726154XXXX/ht4ZiRUEFYbgQ4YDU9mUl1rtcdLsNGVFB95XW_UKIICd5Xppf-QvwzlMEqn-xxxxxxxx
WARNING=https://discord.com/api/webhooks/124556384469752XXXX/3pzyh5NuQdqnJD8zuqI8a44JR608rPAdXXQHBu7oqToNvJW4v9OzI0ubeylzXxxxxxxx
### This redirects the email stream to a file.
sed '' > $FILE
MSG=$(sed '/^From /,/^To:/d' $FILE | sed '2,/^$/d' | sed 's/^Subject.*/&\n/' | sed 's/$/\\n/' | tr -d '\n')
MSG="${HEADER}${MSG}"
###
grep MIME-Version $FILE
if [ $? -eq 0 ]
then
exit
fi
###
grep "New Status: Red" $FILE
if [ $? -eq 0 ]
then
curl -H "Content-Type: application/json" -d "{\"content\": \"$MSG\"}" $WARNING
else
curl -H "Content-Type: application/json" -d "{\"content\": \"$MSG\"}" $STATS
fi
rm $FILE
After the script is ready and set to executable, the same email stream shown in the above screenshot will result in a Discord message like the screenshot shown below.
A sample Discord alert sent from vCenter.
Access to vCenter is like the following screenshot.
As shown, type shell to get into the Linux shell.
You can find how to use curl to send Discord messages from Discord Webhooks Guide at https://birdie0.github.io/discord-webhooks-guide/tools/curl.html
The Telegram part will be covered in Part 3.
Continued on Part 3