Acknowledge problem via notification. possibly via telegram

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