0
votes

I'm trying to create a SNS topic in AWS and subscribe a lambda function to it that will send notifications to Slack apps/users.

I did read this article - https://aws.amazon.com/premiumsupport/knowledge-center/sns-lambda-webhooks-chime-slack-teams/

that describes how to do it using this lambda code:

#!/usr/bin/python3.6
import urllib3
import json
http = urllib3.PoolManager()
def lambda_handler(event, context):
    url = "https://hooks.slack.com/services/xxxxxxx"
    msg = {
        "channel": "#CHANNEL_NAME",
        "username": "WEBHOOK_USERNAME",
        "text": event['Records'][0]['Sns']['Message'],
        "icon_emoji": ""
    }
    
    encoded_msg = json.dumps(msg).encode('utf-8')
    resp = http.request('POST',url, body=encoded_msg)
    print({
        "message": event['Records'][0]['Sns']['Message'], 
        "status_code": resp.status, 
        "response": resp.data
    })

but the problem is, that in that implementation I have to create a lambda function for every user.

I want to subscribe multiple Slack apps/users to one SNS topic. Is there a way of doing that without creating a lambda function for each one?

1
How can the Lambda function identify the Slack user that should receive the message? - John Rotenstein

1 Answers

0
votes

Hi i would say you should go for a for loop and make a list of all the users. Either manually state them in the lambda or get them with api call from slack e.g. this one here: https://api.slack.com/methods/users.list

#!/usr/bin/python3.6
import urllib3
import json
http = urllib3.PoolManager()
def lambda_handler(event, context):
    userlist = ["name1", "name2"]
    for user in userlist:
        url = "https://hooks.slack.com/services/xxxxxxx"
        msg = {
            "channel": "#" + user, # not sure if the hash has to be here
            "username": "WEBHOOK_USERNAME",
            "text": event['Records'][0]['Sns']['Message'],
            "icon_emoji": ""
        }
        
        encoded_msg = json.dumps(msg).encode('utf-8')
        resp = http.request('POST',url, body=encoded_msg)
        print({
            "message": event['Records'][0]['Sns']['Message'], 
            "status_code": resp.status, 
            "response": resp.data
        })

Another solution you can do is set up email for the slack users, see link: https://slack.com/help/articles/206819278-Send-emails-to-Slack When you can just add the emails as subscribers to the sns topic. You can fileter the msg that the receiver gets with Subscription filter policy.