cookiecrumbler
cookiecrumbler

Reputation: 15

Is it possible to make a POST request to Slack with AWS Lambda using only native libraries?

I am trying to make a POST request to Slack using webhooks. I can send a curl to my Slack instance locally but when trying to do so in lambda I run into trouble trying to send the payload.

Everything I've seen says I must use and zip custom libraries but for the purposes of what I'm doing I need to use native python code. Is there a way to send this POST request?

import json
import urllib.request
#import botocore.requests as requests

def lambda_handler(event, context):
  message=event['message']
  response = urllib.request.urlopen(message) 
  print(response) 

This code gives me a 400 error which is how I know I'm hitting the URL I want (URL is in the message variable) but every attempt at sending a payload by adding headers and a text body seems to fail.

Upvotes: 0

Views: 1848

Answers (2)

amittn
amittn

Reputation: 2355

  • Please find attached lambda_handler code, hope this helps you.
  • All the messages to be posted on slack are put on a SNS topic which in turn is read by a lambda and posted to the slack channel using the slack webhook url.
import os
import json
from urllib2 import Request, urlopen, URLError, HTTPError

# Get the environment variables
SLACK_WEBHOOK_URL = os.environ['SLACK_WEBHOOK_URL']
SLACK_CHANNEL = os.environ['SLACK_CHANNEL']
SLACK_USER = os.environ['SLACK_USER']

def lambda_handler(event, context):
    # Read message posted on SNS Topic
    message = json.loads(event['Records'][0]['Sns']['Message'])

# New slack message is created
    slack_message = {
        'channel': SLACK_CHANNEL,
        'username': SLACK_USER,
        'text': "%s" % (message)
    }
# Post message on SLACK_WEBHOOK_URL
    req = Request(SLACK_WEBHOOK_URL, json.dumps(slack_message))
    try:
        response = urlopen(req)
        response.read()
        print(slack_message['channel'])
    except HTTPError as e:
        print(e)
    except URLError as e:
        print(e)

Upvotes: 0

Pubudu Jayawardana
Pubudu Jayawardana

Reputation: 2365

You may try as below:

SLACK_URL = 'https://hooks.slack.com/services/....'

req = urllib.request.Request(SLACK_URL, json.dumps(message).encode('utf-8'))
response = urllib.request.urlopen(req)

Upvotes: 0

Related Questions