This page looks best with JavaScript enabled

Sending Telegram messages from bash/python

 ·  🎃 kr0m

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 {
    message=${@:1}
    curl -s -X POST https://api.telegram.org/botAPI_KEY/sendMessage -d chat_id=CHAT_ID -d text="$message"
}

sendTelegram $1
chmod 700 sendTelegram.sh
./sendTelegram.sh TestBash

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
If you liked the article, you can treat me to a RedBull here