Without using any extra lib(like requests), one can still do GET/POST using urllib build-in python3 module. Below is the example code:
def sendSlack(message):
req_param= {"From":"","Time":"","message":message}
slack_data = {
"blocks": [
{
"type": "header",
"text": {
"type": "plain_text",
"text": "Message",
}
},
{
"type": "section",
"fields": [
{
"type": "mrkdwn",
"text": "*From:*\n{}".format(req_param['From'])
},
{
"type": "mrkdwn",
"text": "*Time:*\n{}".format(req_param['Time'])
}
]
},
{
"type": "section",
"fields": [
{
"type": "mrkdwn",
"text": "*Message:*\n{}".format(req_param['message'])
}
]
}
]}
req = request.Request("https://hooks.slack.com/services/<COMPLETE THE URL>", data=json.dumps(slack_data).encode('utf-8')) # this will make the method "POST"
resp = request.urlopen(req)
print(resp.read())
Make sure to send the right payload, on slack. This code will work like a charm for AWS LAMBDA too. Please see the example below:
import json
from urllib import request
def sendSlack(message):
req_param= {"From":"","StartTime":"now","DialWhomNumber":message}
slack_data = {
"blocks": [
{
"type": "header",
"text": {
"type": "plain_text",
"text": "Message",
}
},
{
"type": "section",
"fields": [
{
"type": "mrkdwn",
"text": "*From:*\n{}".format(req_param['From'])
},
{
"type": "mrkdwn",
"text": "*Time:*\n{}".format(req_param['Time'])
}
]
},
{
"type": "section",
"fields": [
{
"type": "mrkdwn",
"text": "*Message:*\n{}".format(req_param['message'])
}
]
}
]}
req = request.Request("https://hooks.slack.com/services/<COMPLETE THE URL>", data=json.dumps(slack_data).encode('utf-8')) # this will make the method "POST"
resp = request.urlopen(req)
print(resp.read())
def lambda_handler(event, context):
# TODO implement
try:
print("-->GOT A REQUEST",event['queryStringParameters'])
sendSlack(event['queryStringParameters']['message'])
return {'body':json.dumps({'status':200,'event':'accepted'})}
except Exception as e:
print("Exception happenned",e)
return {
'statusCode': 400,
'body': json.dumps({'status':400,'event':'Something went wrong'})
}