Acknowledge problem via notification. possibly via telegram

Hi all, is there the possibility to do the Acknowledgment via notification link?
It would be very nice to be able to do it especially from the notifications that come from the telegram bot.
In the various telegram scripts that I have found, no one supports this function, so perhaps the system itself does not allow you to do it easily from notifications.

We do the same with SMS. Maybe following code give you an idea:

#!/usr/bin/env python

import os, sys
import time
import json

event_type, filename = sys.argv[1:]
if event_type != 'RECEIVED':
    sys.exit(2)

spool_dir = '/var/spool/sms'
content = []
with open(filename) as sms:
    content = sms.readlines()

sender = ''
ID = ''

for line in content:
    if line.lower().startswith('from:'):
        sender = ' '.join(line.split(' ')[1:])
    elif line[0].isdigit():
        ID = line[0:5]

sent_file = os.path.join(spool_dir, 'sent', 'cmk_sms_%s' % ID)
content = []
recipient = ''
try:
    with open(sent_file) as sent_sms:
        content = sent_sms.readlines()

        for line in content:
            if line.lower().startswith('to:'):
                recipient = ' '.join(line.split(' ')[1:])
except IOError:
    sys.stderr.write('ID does not match notifications')
    sys.exit(2)

except:
    raise

if not recipient == sender:
    sys.stderr.write('User did not receive notification')
    sys.exit(2)

root_dir = os.environ['HOME']
lookup_table = os.path.join(root_dir, 'var', 'check_mk', 'notify', 'lookup_table')

with open(lookup_table, 'r') as lookup_file:
    notification_ids = json.load(lookup_file)

    hostname = ''
    servicedesc = ''
    try:
        notification = notification_ids[ID]
        hostname = notification.get('HOSTNAME')
        servicedesc = notification.get('SERVICEDESC')
    except:
        sys.stderr.write('Cannot lookup notification details. Available details: %s' % notification_ids)
        sys.exit(2)

    command_file = os.path.join(root_dir, 'tmp', 'run', 'nagios.cmd')

    if not os.path.exists(command_file):
        sys.stderr.write('Cannot acknowledge. Nagios command file not found at %s' % command_file)
        sys.exit(2)

with open(lookup_table, 'w') as lookup_file:
    del notification_ids[ID]
    json.dump(notification_ids, lookup_file)

with open(command_file, 'w') as cmd:
    if servicedesc:
        what = 'SVC'
        obj = '%s;%s' % (hostname, servicedesc)

    else:
        what = 'HOST'
        obj = '%s' % hostname
    command = '[%d] ACKNOWLEDGE_%s_PROBLEM;%s;2;1;0;CMK;Acknowledged by SMS received from %s\n' % \
              (time.time(), what, obj, sender)
    cmd.write(command.encode('utf-8', errors='ignore'))

2 Likes

Good job, I’ll try to study it. The tricky part is that the telegram script is written in bash

#!/bin/bash
# Push Notification (using Telegram)
#
# Script Name   : check_mk_telegram-notify.sh
# Description   : Send Check_MK notifications by Telegram
# Author        : https://github.com/filipnet/checkmk-telegram-notify
# License       : BSD 3-Clause "New" or "Revised" License
# ======================================================================================

# Telegram API Token
# Find telegram bot named "@botfather", type /mybots, select your bot and select "API Token" to see your current token
if [ -z ${NOTIFY_PARAMETER_1} ]; then
        echo "No Telegram token ID provided. Exiting" >&2
        exit 2
else
        TOKEN="${NOTIFY_PARAMETER_1}"
fi

# Telegram Chat-ID or Group-ID
# Open "https://api.telegram.org/bot<YOUR_TOKEN>/getUpdates" inside your Browser and send a HELLO to your bot, refresh side
if [ -z ${NOTIFY_PARAMETER_2} ]; then
        echo "No Telegram Chat-ID or Group-ID provided. Exiting" >&2
        exit 2
else
        CHAT_ID="${NOTIFY_PARAMETER_2}"
fi

# Privacy settings to anonymize/masking IP addresses
if [[ ${NOTIFY_PARAMETER_3} == "privacy" ]]; then
        # IPv4 IP addresses
        if [ ${NOTIFY_HOST_ADDRESS_4} ]; then
                slice="${NOTIFY_HOST_ADDRESS_4}"
                count=1
                while [ "$count" -le 4 ]
                do
                        declare sec"$count"="${slice%%.*}"
                        slice="${slice#*.}"
                        count=$((count+1))
                done
                # Adjust the output to your privacy needs here (Details in the readme.md)
                NOTIFY_HOST_ADDRESS_4="${sec1}.${sec2}.2.${sec4}"
        fi

        # IPv6 IP addresses
        if [ ${NOTIFY_HOST_ADDRESS_6} ]; then
                slice="${NOTIFY_HOST_ADDRESS_6}"
                count=1
                while [ "$count" -le 8 ]
                do
                        declare sec"$count"="${slice%%:*}"
                        slice="${slice#*:}"
                        count=$((count+1))
                done
                # Adjust the output to your privacy needs here (Details in the readme.md)
                NOTIFY_HOST_ADDRESS_6="${sec1}:${sec2}:${sec3}:${sec4}:ffff:ffff:ffff:${sec8}"
        fi
else
        echo "Invalid privacy parameter, check your Check_MK settings." >&2
fi

# Set an appropriate emoji for the current state
# Feel free to change the emoji to your own taste. This is done by customizing the UTF8 code. Examples here: https://apps.timwhitlock.info/emoji/tables/unicode
if [[ ${NOTIFY_WHAT} == "SERVICE" ]]; then
        STATE="${NOTIFY_SERVICESHORTSTATE}"
else
        STATE="${NOTIFY_HOSTSHORTSTATE}"
fi
case "${STATE}" in
    OK|UP)
        EMOJI=$'\xE2\x9C\x85' # white heavy check mark
        ;;
    WARN)
        EMOJI=$'\xE2\x9A\xA0' # warning sign
        ;;
    CRIT|DOWN)
        EMOJI=$'\xF0\x9F\x86\x98' # squared sos
        ;;
    UNKN)
        EMOJI=$'\xF0\x9F\x94\x84' # anticlockwise downwards and upwards open circle arrows
        ;;
esac

# Create a MESSAGE variable to send to your Telegram bot
MESSAGE="${NOTIFY_HOSTNAME} (${NOTIFY_HOSTALIAS})%0A"
MESSAGE+="${EMOJI} ${NOTIFY_WHAT} ${NOTIFY_NOTIFICATIONTYPE}%0A%0A"
if [[ ${NOTIFY_WHAT} == "SERVICE" ]]; then
        MESSAGE+="${NOTIFY_SERVICEDESC}%0A"
        MESSAGE+="State changed from ${NOTIFY_PREVIOUSSERVICEHARDSHORTSTATE} to ${NOTIFY_SERVICESHORTSTATE}%0A"
        MESSAGE+="${NOTIFY_SERVICEOUTPUT}%0A"
else
        MESSAGE+="State changed from ${NOTIFY_PREVIOUSHOSTHARDSHORTSTATE} to ${NOTIFY_HOSTSHORTSTATE}%0A"
        MESSAGE+="${NOTIFY_HOSTOUTPUT}%0A"
fi
MESSAGE+="%0AIPv4: ${NOTIFY_HOST_ADDRESS_4} %0AIPv6: ${NOTIFY_HOST_ADDRESS_6}%0A"
MESSAGE+="${NOTIFY_SHORTDATETIME} | ${OMD_SITE}"

# Send message to Telegram bot
curl -S -X POST "https://api.telegram.org/bot${TOKEN}/sendMessage" -d chat_id="${CHAT_ID}" -d text="${MESSAGE}"
if [ $? -ne 0 ]; then
        echo "Not able to send Telegram message" >&2
        exit 2
else
        exit 0
fi

You even can call python scripts from a bash script. The event handler script for smstools is also a bash script calling above python script

If you are looking for a alerting with a back channel for acknowledgements and comments you might want to check our SIGNL4: Improve the communication of alerts with SIGNL4 | Checkmk

This topic was automatically closed 365 days after the last reply. New replies are no longer allowed. Contact an admin if you think this should be re-opened.