Created
September 1, 2020 19:18
-
-
Save stibi/569dc23d618d49fef2eb6b9244a65298 to your computer and use it in GitHub Desktop.
barebone code for posting slack messages with AWS Lambda
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3.7 | |
import os | |
import json | |
import logging | |
from botocore.vendored import requests | |
import ec2 | |
logger = logging.getLogger() | |
logger.setLevel(logging.INFO) | |
SLACK_WEBHOOK_URL = os.environ.get("slack_webhook_url") | |
SLACK_CHANNEL = os.environ.get("slack_channel") | |
def handle_custom_notification(message): | |
text = message.get("text", "Error: missing text in the custom notification message") | |
channel = message.get("channel", SLACK_CHANNEL) | |
username = message.get("username", "Slack lambda") | |
icon_emoji = message.get("icon_emoji", ":black_circle:") | |
slack_message = dict( | |
text=text, | |
channel=channel, | |
username=username, | |
icon_emoji=icon_emoji | |
) | |
return slack_message | |
def post_slack_message(message): | |
"""Makes a http POST request to slack webhook url, posting a notification message. | |
Args: | |
message (dict): a payload with slack message data | |
Returns: | |
boolean: message has been sent successfully or not | |
""" | |
response = requests.post(SLACK_WEBHOOK_URL, | |
data=json.dumps(message), | |
headers={'Content-Type': 'application/json'} | |
) | |
if response.status_code != 200: | |
raise ValueError('Request to slack returned an error: %s, the response is: %s' % | |
(response.status_code, response.text)) | |
return True | |
def main(event, context): | |
"""Main function handler. | |
Args: | |
event (?):? | |
context (?): ? | |
Returns: | |
boolean: a function invocation succeeded or not | |
""" | |
message = json.loads(event['Records'][0]['Sns']['Message']) | |
slack_message = handle_custom_notification(message) | |
post_slack_message(slack_message) | |
return True |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment