Alertas Telegram en Zabbix

Lo primero que necesitamos es crear un bot de Telegram si aún no lo tenemos. Para crear un bot, basta con iniciar la app en cualquier dispositivo. En la barra de búsqueda de telegram escribimos:

@BotFather

Para crear nuestro bot debemos interactuar antes con BotFather. Le mandamos un mensaje:

/start

Nos devolverá comandos que nos posibilita la creación de nuestro bot

Como podemos ver, el comando que hay que enviarle es el siguiente:

/newbot

BotFather nos preguntará por el nombre y un subnombreque queremos darle al bot. Éste tiene que acabar con la palabra bot. En nuestro caso hemos elegido zabbixmerkatu_bot

zabbixmerkatu_bot

Cuando registre el nuevo bot, nos devolverá el token que utilizaremos para añadirlo a nuestro script de python que haremos en el servidor más tarde. (ejemplo el token que nos han dado para zabbixmerkatu_bot):

Use this token to access the HTTP API: 348816857:AAFnvD017g6PhfbIkHkaNbSi1bCjstXTEFo

Podemos salir de la conversación con GodFather, ya tenemos el token.

Otros comandos de BotFather:

/newbot – Create a new bot.
/token – Generate authorization token.
/revoke – Revoke bot access token.
/setname – Change a bot’s name.
/setdescription – Change bot description.
/setabouttext – Change bot about info.
/setuserpic – Change bot profile photo.
/setcommands – Change bot commands list.
/setjoingroups – Can your bot be added to groups?
/setprivacy – What messages does your bot see in groups?
/deletebot – Delete a bot.
/cancel – Cancel the current operation.

IMPORTANTE: Hay que añadir al bot al grupo de chat y enviarle un mensaje

Primero debemos saber la version de python que tenemos instalada en el servidor y donde

whereis python

En nuestro caso, tenemos la v3.4 en el directorio /usr/bin/python3.4

Instalamos la herramienta python pip:

apt-get install python-pip

Instalamos la API de Telegram:

pip install pyTelegramBotAPI

***En caso de que no funcione pip, bajar del repositorio git:

cd /usr/src
git clone --recursive https://github.com/eternnoir/pyTelegramBotAPI.git
cd pyTelegramBotAPI
python3.4 setup.py install

Revisamos la configuración de Zabbix para saber cual es el path de los alertscripts. Si es necesario, lo cambiamos por la ruta donde dejemos el script:

vim /etc/zabbix/zabbix-server.conf

Supongamos que tenemos definida la ruta: /var/lib/zabbix.

En esta carpeta creamos el fichero por ejemplo que se llame telegram-bot.py

vim telegram-bot.py

Pegamos el siguiente contenido, cambiando nuestro token:

#!/usr/bin/python3.4  #Le indicamos donde se encuentra el interprete de python
import telebot,sys
BOT_TOKEN='348816857:AAFnvD017g6PhfbIkHkaNbSi1bCjstXTEFo'  #cambiamos por el nuestro
DESTINATION=sys.argv[1]  #Este argumento lo programamos en el front como {ALERT.SENDTO}
SUBJECT=sys.argv[2]   #Este argumento lo programamos en el front como {ALERT.SUBJECT}
MESSAGE=sys.argv[3]   #Este argumento lo programamos en el front como {ALERT.MESSAGE}
MESSAGE = MESSAGE.replace('/n','\n')
tb = telebot.TeleBot(BOT_TOKEN)
tb.send_message(DESTINATION,SUBJECT + '\n' + MESSAGE)

Le damos permisos de ejecución y cambiamos de propietario para que lo ejecute el usuario zabbix

chmod +x telegram-bot.py
chown zabbix:zabbix telegram-bot.py

Listo

Accedemos a la GUI del server:

http://zabbix.merkatu.info:8888/zabbix

Vamos a la pestaña de Administración » Media Types » Create Media-type

Name → Le damos un nombre descriptivo

Type → Le decimos que sea un script

Script name → Le indicamos exactamente el nombre que hemos puesto al script (telegram-bot.py)

Añadimos los siguientes parámetros: {ALERT.SENDTO} {ALERT.SUBJECT} {ALERT.MESSAGE}

Marcamos la casilla de enable, damos en update y salimos.

Ahora nos vamos a Users » Admin » Media » Add

Type → Desplegamos y seleccionamos nuestro script

Sendto → El id de nuestro grupo en telegram (-139912990)

When enable → Programacion de alertas

Use it severity → Que tipo de alertas queremos que lleguen al chat

Marcamos casilla enable y le damos a update.

UserID

If you want to get a user id, send a message from this user to the bot. Reload the page and the user id will be shown.

Example:

"message":{"message_id":59,"from":{"id":9083329,"first_name":"Gabriel","last_name":"R F","username":"GabrielRF"},"chat":{"id":9083329,"first_name":"Gabriel","last_name":"R F","username":"GabrielRF","type":"private"},"date":1446911853,"text":"\/start"}}]}

In this case, the user id is 9083329. So, on the step Users, the field Send to would be 9083329.

GroupID

If you prefer to have your bot working on a group, then create the group and add the bot to it. Reload the page and you will see a message like:

"message":{"message_id":60,"from":{"id":9083329,"first_name":"Gabriel","last_name":"R F","username":"GabrielRF"},"chat":{"id":-57169325,"title":"q31231","type":"group"},"date":1446912067,"group_chat_created":true}},{"update_id":727527785,

In this case, the group id is -57169325. So, on the step Users, the field Send to would be -57169325.

Note that a group id is always negative. Only user's id are positive.