Skip to content

Commit

Permalink
Use telegram Markdown v2 API; properly escape text; do not send error…
Browse files Browse the repository at this point in the history
…s using telegram
  • Loading branch information
justabaka committed Nov 22, 2020
1 parent e9f326c commit 694169b
Show file tree
Hide file tree
Showing 4 changed files with 34 additions and 14 deletions.
30 changes: 25 additions & 5 deletions flaskalert.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
from flask import render_template
from flask import current_app as app
from flask_basicauth import BasicAuth
from jinja2.runtime import Undefined

LOG_LEVEL = logging.getLevelName(os.getenv('LOG_LEVEL', 'INFO').upper())
logging.basicConfig(level=LOG_LEVEL, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
Expand Down Expand Up @@ -47,6 +48,17 @@ def get_env_var(env_variable_name='', default='', required=False):
app.logger.info('Basic Auth is disabled')


@app.template_filter()
def escape_telegram_markdown(item):
"""
Escapes characters in text as Telegram Bot API requires.
Info:
* https://core.telegram.org/bots/api#markdownv2-style
* https://python-telegram-bot.readthedocs.io/en/stable/telegram.utils.helpers.html#telegram.utils.helpers.escape_markdown
"""
return telegram.utils.helpers.escape_markdown(text=str(item), version=2)


@app.route('/', methods=['POST'])
def post_alertmanager():
"""
Expand All @@ -69,7 +81,7 @@ def post_alertmanager():
try:
content = json.loads(request.get_data())
except Exception as exc:
app.logger.error("Cannot parse JSON data: {}.\n Error message: {}".format(pformat(request.get_data()), str(exc)))
app.logger.error("Cannot parse JSON data: {}.\n Error message: {}".format(pformat(request.get_data()), pformat(str(exc))))
return "Alert FAIL", 500

try:
Expand All @@ -85,12 +97,20 @@ def post_alertmanager():
timediff = None

alert['startsAt'] = alert['startsAt'].strftime(app.time_format)
except Exception as exc:
app.logger.error("Cannot parse date/time in the message:\n message={}".format(pformat(str(exc))), pformat(alert))
return "Alert FAIL", 500

message = render_template("alert.j2", alert=alert, duration=timediff)
app.logger.debug('Rendered the message: {}'.format(pformat(message)))
try:
message = render_template("alert.j2", alert=alert, duration=timediff)
app.logger.debug('Rendered the message: {}'.format(pformat(message)))
except Exception as exc:
app.logger.error("Cannot render a message:\n message={}\n".format(pformat(alert), pformat(str(exc))))
return "Alert FAIL", 500

app.bot.sendMessage(chat_id=chat_id, text=message, parse_mode=telegram.ParseMode.MARKDOWN)
return "Alert OK", 200
try:
app.bot.sendMessage(chat_id=chat_id, text=message, parse_mode=telegram.ParseMode.MARKDOWN_V2)
return "Alert OK", 200
except Exception as exc:
app.logger.error("Cannot send the message:\n chat_id={}\n message={}".format(chat_id, pformat(str(exc))))
return "Alert FAIL", 500
Expand Down
14 changes: 7 additions & 7 deletions templates/alert.j2
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,16 @@
{% elif alert['status'] == 'resolved' -%}
*✅ RESOLVED ✅*
{% else -%}
*[{{ alert['labels']['severity']|upper }}] {{ alert['status']|upper }}*
*[{{ alert['labels']['severity']|upper|escape_telegram_markdown }}] {{ alert['status']|upper|escape_telegram_markdown }}*
{% endif -%}

*{{ alert['labels']['alertname'] }}*
{{ alert['annotations']['message']|default('') }}
*{{ alert['labels']['alertname']|escape_telegram_markdown }}*
{{ alert['annotations']['message']|default('')|escape_telegram_markdown }}

{{ alert['annotations']['description'] -}}
{{ alert['annotations']['description']|escape_telegram_markdown -}}

{% if alert['startsAt'] is defined %}*Occurred at:* {{ alert['startsAt'] }}{% endif %}
{% if alert['startsAt'] is defined %}*Occurred at:* {{ alert['startsAt']|escape_telegram_markdown }}{% endif %}
{% if alert['status'] == 'resolved' -%}
{% if alert['endsAt'] is defined %}*Resolved at:* {{ alert['endsAt'] }}{%- endif %}
{% if duration is defined %}*Duration*: {{ duration }}{%- endif %}
{% if alert['endsAt'] is defined %}*Resolved at:* {{ alert['endsAt']|escape_telegram_markdown }}{%- endif %}
{% if duration is defined %}*Duration*: {{ duration|escape_telegram_markdown }}{%- endif %}
{% endif -%}
2 changes: 1 addition & 1 deletion tests/firing.sh
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,5 @@

curl \
--request POST \
--data '{"receiver":"telegram","status":"firing","alerts":[{"status":"firing","labels":{"alertname":"Fire","severity":"critical"},"annotations":{"message":"Something is on fire"},"startsAt":"2018-11-04T22:43:58.283995108+01:00","endsAt":"2018-11-04T22:46:58.283995108+01:00","generatorURL":"http://localhost:9090/graph?g0.expr=vector%28666%29\u0026g0.tab=1"}],"groupLabels":{"alertname":"Fire"},"commonLabels":{"alertname":"Fire","severity":"critical"},"commonAnnotations":{"message":"Something is on fire"},"externalURL":"http://localhost:9093","version":"4","groupKey":"{}:{alertname=\"Fire\"}"}' \
--data '{"receiver":"telegram","status":"firing","alerts":[{"status":"firing","labels":{"alertname":"Fire detected on * host_name (escape test)","severity":"critical"},"annotations":{"message":"Something is on fire"},"startsAt":"2018-11-04T22:43:58.283995108+01:00","endsAt":"2018-11-04T22:46:58.283995108+01:00","generatorURL":"http://localhost:9090/graph?g0.expr=vector%28666%29\u0026g0.tab=1"}],"groupLabels":{"alertname":"Fire"},"commonLabels":{"alertname":"Fire","severity":"critical"},"commonAnnotations":{"message":"Something is on fire"},"externalURL":"http://localhost:9093","version":"4","groupKey":"{}:{alertname=\"Fire\"}"}' \
localhost:8080
2 changes: 1 addition & 1 deletion tests/resolved.sh
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,5 @@

curl \
--request POST \
--data '{"receiver":"telegram","status":"resolved","alerts":[{"status":"resolved","labels":{"alertname":"Fire","severity":"critical"},"annotations":{"message":"Something is on fire"},"startsAt":"2018-11-04T22:43:58.283995108+01:00","endsAt":"2018-11-04T22:48:13.283995108+01:00","generatorURL":"http://localhost:9090/graph?g0.expr=vector%28666%29\u0026g0.tab=1"}],"groupLabels":{"alertname":"Fire"},"commonLabels":{"alertname":"Fire","severity":"critical"},"commonAnnotations":{"message":"Something is on fire"},"externalURL":"http://localhost:9093","version":"4","groupKey":"{}:{alertname=\"Fire\"}"}' \
--data '{"receiver":"telegram","status":"resolved","alerts":[{"status":"resolved","labels":{"alertname":"Fire extinguished on * host_name (escape test)","severity":"critical"},"annotations":{"message":"Something is on fire"},"startsAt":"2018-11-04T22:43:58.283995108+01:00","endsAt":"2018-11-04T22:48:13.283995108+01:00","generatorURL":"http://localhost:9090/graph?g0.expr=vector%28666%29\u0026g0.tab=1"}],"groupLabels":{"alertname":"Fire"},"commonLabels":{"alertname":"Fire","severity":"critical"},"commonAnnotations":{"message":"Something is on fire"},"externalURL":"http://localhost:9093","version":"4","groupKey":"{}:{alertname=\"Fire\"}"}' \
localhost:8080

0 comments on commit 694169b

Please sign in to comment.