有没有办法在不使用 Webhook 的情况下向 slack 发送 POST 请求?

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

我尝试使用网络挂钩向我的松弛频道发送 POST 请求,但无济于事。
无论我做什么,它总是 returns 一个糟糕的请求。
有没有办法在不使用 webhook 的情况下向 slack 发送 POST 请求?

编辑:我正在使用的代码

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)

我认为当您在 utf-8 中编码 JSON 时会出现问题。尝试以下脚本。

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

如果你想使用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)

不使用任何额外的库(如请求),仍然可以使用 urllib build-in python3 模块GET/POST。下面是示例代码:

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())

确保发送正确的有效载荷,从容。此代码对 AWS LAMBDA 也很有用。请看下面的例子:

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