Slack 交互式消息:POST 响应不是 json 格式

Slack interactive message: POST response is not in json format

@csrf_exempt
def slack(request):
print("Testing slack")
if request.method == 'POST':
    print('request', str(request.body))
    webhook_url = 'xxxxxxxx'
    text = "Would you recommend it to customers?"
    request = unquote(unquote(request.body.decode(encoding='ascii')))
    print('url', request)
    slack_data = {
        "attachments": [
            {
                "fallback": "Would you recommend it to customers?",
                "title": request,
                "callback_id": "comic_1234_xyz",
                "color": "#3AA3E3",
                "attachment_type": "default",
                "actions": [
                    {
                        "name": "recommend",
                        "text": "Recommend",
                        "type": "button",
                        "value": "recommended"
                         }
                ],
            }
        ]
    }
    test = slack_data
    print('slack_data', type(slack_data))
    response = requests.post(
        webhook_url, data=json.dumps(test),
        headers={'Content-Type': 'application/json'}
    )
return HttpResponse("New comic book alert!")

在这个 str(request.body) 中,我得到如下输出: b'payload=%7B%22type%22%3A%22交互消息%22%2C%

所以我使用 unquote(unquote(request.body.decode(encoding='ascii'))) 对其进行了编码,并且我能够以这种格式获取有效负载:

payload={ "here I got all details of POST message" }

如何在 Json 中解析它?

没有必要一开始就得到 request.body。看起来您正在发布标准表单数据,其中 payload 字段包含 JSON 数据。所以就这样吧:

data = json.loads(request.POST['payload'])