Sending messages through Telegram is very useful, especially when scripting check or backup scripts, this way we can be notified about certain alarms or errors. We have previously used Telegram notifications from python here and here, but sometimes we do not have python on the server so I leave two versions, one written in bash and one in python.
The bash version would be the following:
vi sendTelegram.sh
#!/usr/bin/env bash
function sendTelegram() {
token="XXXX"
id="YYYY"
url="https://api.telegram.org/bot$token/sendMessage"
local message="$1"
if [ -z "$message" ]; then
message="$HOSTNAME trying to use sendTelegram incorrectly"
fi
curl -s -X POST "$url" -d chat_id="$id" -d parse_mode="MarkdownV2" --data-urlencode "text=$message" &> /dev/null
if [ $? -ne 0 ]; then
echo "Error with bot"
fi
}
message=$(printf "%s\\n%s" "$HOSTNAME" $'No watchdog device detected:\ngrep \\-q "blacklist softdog" \\/lib\\/modprobe\\.d\\/blacklist\\_linux\\_\\*\\.conf\ncat \\/etc\\/modules\\-load\\.d\\/softdog\\.conf\ncat /etc/udev/rules\\.d/61\\-watchdog\\.rules')
sendTelegram "$message"
chmod 700 sendTelegram.sh
./sendTelegram.sh
./sendTelegram.sh
The python version:
vi sendTelegram.py
import requests
import sys
def sendMessage(msg):
apiKey = "API_KEY"
userId = "USER_ID"
data = {"chat_id":userId,"text":msg}
url = "https://api.telegram.org/bot{}/sendMessage".format(apiKey)
r = requests.post(url,json=data)
msg = sys.argv[1]
sendMessage(msg)
python sendTelegram.py TestPython