首页 > 解决方案 > Slack 块 + 发送响应在 python 中不起作用,即使在异步时也不起作用 - 仅在 CURL 中

问题描述

当在 python 之外的 curl 中使用相同的 response_url 时,我不明白为什么 slack 会拒绝使用 404 发布的返回消息。

我的网络钩子处理器:

def slack_webhook(request):
    json_dict = json.loads(request.body.decode('utf-8'))
    token = json_dict['token'] if 'token' in json_dict else None
    message = json_dict['message'] if 'message' in json_dict else None
    trigger_id = json_dict['trigger_id'] if 'trigger_id' in json_dict else None
    response_url = json_dict['response_url'] if 'response_url' in json_dict else None
    actions = json_dict['actions'] if 'actions' in json_dict else None

    for action in actions:
        print(f"** received action {action['action_id']}")
        print(f"** response_url: {response_url}")
        print(f"** trigger_id: {trigger_id}")

        payload = {
            "replace_original": True,
            "text": "Success!",
        }

        # async via Celery...
        send_slack_interactive_response.delay(response_url, payload, trigger_id)
        
        return HttpResponse(status=200) 

发送的异步芹菜任务

@app.task(bind=True, retry_kwargs={'max_retries': 10, 'countdown': 5})
def send_slack_interactive_response(self, response_url, payload, trigger_id):

    print(f"**  -> response_url: {response_url}")
    print(f"** -> trigger_id: {trigger_id}")

    if response_url and payload and trigger_id:
        headers = {"Content-Type": "application/json"}
        payload['trigger_id'] = trigger_id
        print(json.dumps(payload))
        r = requests.post(response_url, data=payload, headers=headers)
        print(r.__dict__)

此功能因 404 而失败。但是,当我使用response_url,trigger_id并使用命令行创建完全相同的 POST 时curl- 它可以工作。

我究竟做错了什么?

标签: pythondjangoslack-api

解决方案


只需对您的代码发表评论:您可以这样做token = json_dict.get("token", None)可以节省大量代码

关于你的问题:

  1. 确保 Celery 参数没有被奇怪的编码(response_url 被发送到 messagerie 并被编码)
  2. 确保请求参数被很好地使用(比如使用json而不是data......)

推荐阅读