'Is there a way to send a POST request to slack without using Webhook?

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)


Solution 1:[1]

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)

Solution 2:[2]

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'})
    }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 SilentEntity