Skip to content

Instantly share code, notes, and snippets.

@sandromello
Created March 2, 2015 18:36
Show Gist options
  • Save sandromello/29ef533753e945562fe7 to your computer and use it in GitHub Desktop.
Save sandromello/29ef533753e945562fe7 to your computer and use it in GitHub Desktop.
Telegram - sysnotify
#!/usr/bin/env python
import pika, logging, socket, yaml, marshal
from time import sleep
ACCEPTED_KEYS = ['message', 'sla_service', 'site', 'host', 'service']
def send_telegram(data, config):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('localhost', 2391))
if data['sla_service']:
sock.send('msg %s "%s"\n' % (config['groups_inova']['sla_group'], data['message']))
else:
sock.send('msg %s "%s"\n' % (config['groups_inova']['plantao_group'], data['message']))
sock.close()
if __name__ == '__main__':
config_file = '/etc/inova/sysnotify.yaml'
with open(config_file) as f:
config = yaml.load(f)
logger = logging.getLogger('sysnotify')
logger.setLevel(logging.DEBUG)
# create a file handler
handler = logging.FileHandler(config['log_file'])
handler.setLevel(logging.DEBUG)
# create a logging format
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
# add the handlers to the logger
logger.addHandler(handler)
connection = pika.BlockingConnection(pika.ConnectionParameters(
host='localhost'))
channel = connection.channel()
channel.queue_declare(queue=config['queue_name'])
for method, properties, body in channel.consume(config['queue_name']):
# dict with following keys: message, sla_service, site
try:
data = marshal.loads(body)
if False in [False for key in data if key not in ACCEPTED_KEYS]:
logger.warning('Wrong data received: %s' % ', '.join(data.keys()))
continue
if data['site'] not in config['sites']:
logger.warning('Find is not authorized: %s' % data['site'])
continue
logger.info('SLA Service: %s Site: %s' % (data['sla_service'], data['site']))
# Prevent sending too many messages at the same time
logger.debug('Sending msg: %s' % data['message'])
send_telegram(data, config)
channel.basic_ack(method.delivery_tag)
except Exception, e:
logger.exception(e)
logger.info('Sleeping for %s seconds...' % config['sleep_time'])
sleep(config['sleep_time'])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment