import json import os import urllib3 bot_token = os.environ.get('SLACK_BOT_TOKEN') def send_slack_message(channel, message, blocks=[], attachments=[]): http = urllib3.PoolManager() body = { "channel": channel, } if isinstance(message, dict): body['message'] = message else: body['text'] = message if blocks: body['blocks'] = blocks if attachments: body['attachments'] = attachments response = http.request( "POST", "https://slack.com/api/chat.postMessage", body=json.dumps(body).encode('utf8'), headers={ 'Content-Type': 'application/json; charset=utf8', 'Authorization': 'Bearer ' + bot_token, } ) result = json.loads(response.data.decode('utf8')) if not result['ok']: raise Exception("Unable to post message: {}".format(result['error'])) def lambda_handler(event, context): send_slack_message( event.get('channel'), event.get('message'), event.get('blocks'), event.get('attachments') ) return { "status": "ok" }