0

My code can not correct read JSON input.


def lambda_handler(event, context):
    WEBHOOK_URL = "https://" + os.environ['WEBHOOK_URL']

    sns        = event['Records'][0]['Sns']
    json_msg   = json.loads(sns['Message'])

    region     = sns['TopicArn'].split(':')[3]
    status     = json_msg['NewStateValue']

    message    =  'region: ' + region + '\n' + 'status: ' + status

    payload = {
        "username": "bot",
        "attachments": [
            {
                "text": str(message)
            }
        ]
    }

    r = requests.post(WEBHOOK_URL, json=payload)
    return r.status_code

I get a region, but I don't' get status. Example JSON input: https://github.com/builtinnya/aws-sns-slack-terraform/blob/51b954ca8f736e08deccd4196670a187f7b58fe5/sns-to-slack/lambda_function.py#L278

1 Answer 1

1

use below lines:-

import json

def lambda_handler(event, context):
 WEBHOOK_URL = "https://" + os.environ['WEBHOOK_URL']

    sns        = event['Records'][0]['Sns']
    json_msg   = json.loads(sns['Message'])

    region     = sns['TopicArn'].split(':')[3]
    status     = json_msg['NewStateValue']

    message    =  'region: ' + region + '\n' + 'status: ' + status

    payload = {
        "username": "bot",
        "attachments": [
            {
                "text": str(message)
            }
        ]
    }

    r = requests.post(WEBHOOK_URL, json=payload)
    response = {
            "statusCode": r.status_code,
            "body": json.dumps("Your message")
        }
    return response 
Sign up to request clarification or add additional context in comments.

5 Comments

i use: from future import print_function import os import json import base64 import re import requests.....but nothing
Check modified answer
I got some joke because of real JSON which go to AWS topic get me the result, but test JSON work only in Lambda-manual-test. I got JSON but I have inside dict and I can parse this dict: alarm_name = out.get('AlarmName')
What are you trying to say now? @AlexanderSKyzZz
Example JSON input for AWS SNS topic's doesn't work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.