I have tried to send POST requests to my slack channel using webhooks to no avail.
It always returns a bad request no matter what I do.
Is there a way to send a POST request to slack without using webhooks?
EDIT: Code that I'm using
import json
import urllib.request
#import botocore.requests as requests
def lambda_handler(event, context):
webhook=event['webhook']
#response = urllib.request.urlopen(message)
#print(response)
slack_URL = 'https://hooks.slack.com/services/mywebhookurl'
# req = urllib.request.Request(SLACK_URL, json.dumps(webhook).encode('utf-8'))
json=webhook
json=json.encode('utf-8')
headers={'Content-Type': 'application/json'}
#urllib.request.add_data(data)
req = urllib.request.Request(slack_URL, json, headers)
response = urllib.request.urlopen(req)
I think the problem arises when you encode your JSON in utf-8
. Try the following script.
import json
import requests
# Generate your webhook url at https://my.slack.com/services/new/incoming-webhook/
webhook_url = "https://hooks.slack.com/services/YYYYYYYYY/XXXXXXXXXXX"
slack_data = {'text': "Hi Sarath Kaul"}
response = requests.post(webhook_url, data=json.dumps(slack_data),headers={'Content-Type': 'application/json'})
print response.status_code
If you want to use urllib
import json
import urllib.request
import urllib.parse
url = 'https://hooks.slack.com/services/YYYYYYYYY/XXXXXXXXXXX'
data = json.dumps({'text': "Sarath Kaul"}).encode('utf-8') #data should be in bytes
headers = {'Content-Type': 'application/json'}
req = urllib.request.Request(url, data, headers)
resp = urllib.request.urlopen(req)
response = resp.read()
print(response)