29 окт. 2019 г.

Zabbix notifications to Telegram

Send notification from Zabbix to Telegram messenger

Create new media type
script with name telebot in /usr/lib/zabbix/alertscripts
Add notifications of all levels (or some) to user Admin and enable it.
Enable action
Send only to Telegram
Check message sending
Python script taken from tproger.ru
Bash script taken from zabbix.com
#---------------- telebot bash script -----------------------------
#!/bin/bash
to=$1 
subject=$2
body=$3
python /usr/lib/zabbix/alertscripts/telebot.py $to $subject $body

#---------------- telebot python script ---------------------------
import requests
import sys

class BotHandler:

    def __init__(self, token):
        self.token = token
        self.api_url = "https://api.telegram.org/bot{}/".format(token)

    def get_updates(self, timeout=30):
        method = 'getUpdates'
        params = {'timeout': timeout}
        resp = requests.get(self.api_url + method, params)
        result_json = resp.json()['result']
        return result_json

    def send_message(self, chat_id, text):
        params = {'chat_id': chat_id, 'text': text}
        method = 'sendMessage'
        resp = requests.post(self.api_url + method, params)
        return resp

    def get_last_update(self):
        get_result = self.get_updates()
        if len(get_result) > 0:
            last_update = get_result[-1]
        else:
            last_update = get_result[len(get_result)]
        return last_update

greet_bot = BotHandler("123456789:AA321321323terjgj59jg;j6gjrejg45gg45g54f")

def main():  
        message=''
        i=2
        while i<len(sys.argv):
            message+=sys.argv[i]+' '
            i+=1
        greet_bot.send_message(sys.argv[1], message)

if __name__ == '__main__':
        main()