""" Transcoding job slack notification lambda Can be used with show or hide filters which can be specified using environment variables MESSAGE_SHOW_FILTER or MESSAGE_HIDE_FILTER Show filter specifies what kind of messages should be only sent to slack Example: MESSAGE_SHOW_FILTER = {"status": "error"} In this case only messages which contain key "status" with value "error" will be sent to slack and other messages will never be sent Hide filter specifies what kind of messages should not be sent to slack Example: MESSAGE_HIDE_FILTER = {"status": "success"} In this case only messages which contain key "status" with value "success" will never be sent to slack, but others will be sent """ import json from urllib import request from urllib.error import URLError, HTTPError import common_config # noqa from common_config import logger # noqa from constants import errors # noqa import config # noqa def handler(event, context): try: message = json.loads(event['Records'][0]['Sns']['Message']) if config.MESSAGE_SHOW_FILTER: filters = json.loads(config.MESSAGE_SHOW_FILTER) logger.info("Filters: " + str(filters)) for key, value in filters.items(): if key not in message or message[key] != value: logger.info( "Message " + str(message) + " does not satisfy show filter conditions") return True elif config.MESSAGE_HIDE_FILTER: filters = json.loads(config.MESSAGE_HIDE_FILTER) logger.info('Filters: ' + str(filters)) for key, value in filters.items(): if key in message and message[key] == value: logger.info( "Message " + str(message) + " satisfies hide filter conditions") return True slack_message_data = { 'channel': config.SLACK_CHANNEL, 'username': 'ALERT', 'text': event['Records'][0]['Sns']['TopicArn'], 'icon_emoji': ':aws:', 'attachments': [{ 'text': json.dumps(message), 'color': config.SLACK_MESSAGE_COLOR }] } req = request.Request( config.SLACK_HOOK_URL, json.dumps(slack_message_data).encode('utf-8')) response = request.urlopen(req) response.read() logger.info("Message posted to %s", slack_message_data['channel']) return True except HTTPError as e: logger.error(errors.SLACK_HTTP_ERROR_MESSAGE.format( code=e.code, reason=e.reason)) raise except URLError as e: logger.error(errors.SLACK_URL_ERROR_MESSAGE.format( reason=e.reason)) raise except Exception as e: logger.exception(str(e)) raise