Skip to content

Instantly share code, notes, and snippets.

@freeseacher
Created January 19, 2017 16:52
Show Gist options
  • Save freeseacher/e4ced9db25821b363ad06216af3bf595 to your computer and use it in GitHub Desktop.
Save freeseacher/e4ced9db25821b363ad06216af3bf595 to your computer and use it in GitHub Desktop.
telegram.py for alerta
import os
from alerta.app import app
from alerta.plugins import PluginBase
from jinja2 import Template
import telebot
import logging
logger = telebot.logger
telebot.logger.setLevel(logging.DEBUG) # Outputs debug messages to console.
LOG = app.logger
tmpl="""
{% if customer %}Customer: `{{customer}}` {% endif %}
*[{{ status.capitalize() }}] {{ environment }} {{ severity.capitalize() }}*
{{ event | replace("_","\_") }} {{ resource.capitalize() }}
```
{{ text }}
```
{% if value and value != "n/a"%}Value: `{{value}}`{% endif %}
{%- if rawData %}
{%- if rawData.generatorURL %}[Graph]({{rawData.generatorURL}})
{%else%}
[Details](https://xxxxx/#/alert/{{ alert.id }})
{% endif %}
{% endif %}
"""
LOG.debug(tmpl)
TELEGRAM_TOKEN = os.environ.get('TELEGRAM_TOKEN') or app.config['TELEGRAM_TOKEN']
TELEGRAM_CHATID = os.environ.get('TELEGRAM_CHATID') or app.config['TELEGRAM_CHATID']
ALERTA_UI_URL = os.environ.get('ALERTA_UI_URL', 'http://try.alerta.io')
bot = telebot.TeleBot(TELEGRAM_TOKEN)
class TelegramIntegration(PluginBase):
def pre_receive(self, alert):
return alert
def post_receive(self, alert):
if alert.repeat:
return
template = Template(tmpl)
text = template.render(alert.__dict__)
LOG.debug('Telegram text: %s', text)
try:
r = bot.send_message(TELEGRAM_CHATID,
text,
parse_mode="Markdown",
disable_web_page_preview=True)
except Exception as e:
raise RuntimeError("Telegram connection error: %s", e)
LOG.debug('Telegram response: %s', r)
def status_change(self, alert, status, summary):
return
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment