【问题标题】:How to send a http 200 for an event request for Slack API in Python request如何在 Python 请求中为 Slack API 的事件请求发送 http 200
【发布时间】:2019-08-08 17:42:54
【问题描述】:

我需要使用 HTTP 2xx 响应事件请求。我在 Python 中使用 Request 方法。我怎么能退货呢?请帮忙。

我目前的问题是,我在本地主机上使用隧道软件。所以对于松弛:

您的应用应使用 HTTP 2xx 响应事件请求 三秒钟。如果没有,我们将考虑事件交付 尝试失败。失败后,我们将重试 3 次,然后退出 成倍增长。

我通过这个命令回复 slack

resp = requests.post(url,json=payload, headers=headers, cookies=cookies)
data = resp.json()
status = data['status']
send_message = status
slack_client.api_call("chat.postMessage", channel=channel, text=send_message)

所以现在因为我没有在 3 秒内结束任何响应,它重试了 3 次,所以我得到了 4 个响应。

所以一旦我收到请求,我需要用 Http2xx 回复。

【问题讨论】:

  • 请在此处添加您的代码,以便我们提供帮助。到目前为止你做了什么?您是否有运行 API/服务器来接收请求并返回某些内容?
  • @LucaBezerra,是的,我正在使用 ngrok 为我的本地主机建立隧道。问题是由于我没有立即回复,延迟超过 3 秒,因此 Slack 重试三次。所以我得到了 3 个响应。
  • 请将代码的相关部分添加到问题中。你在用烧瓶吗?如果是,请添加标签。
  • 添加了@ErikKalkoken
  • 是的,这行不通。您需要终止当前脚本才能发回 http 200 并打开一个新线程或进程以继续您的应用程序

标签: python slack slack-api


【解决方案1】:

为了使用 HTTP 200 响应请求,您需要首先生成第二个进程或线程以继续执行应用程序,然后终止主线程/进程。

有很多方法可以做到,这里有一个完整的线程和 Flask 示例。

它正在接收来自 Slack 的斜杠命令请求,立即以一条短消息响应。然后等待 7 秒模拟繁重的处理,最后再次以消息响应。

此示例使用斜杠命令,但该方法也适用于事件。

import threading
from time import sleep
from flask import Flask, json, request
import requests

app = Flask(__name__) #create the Flask app

@app.route('/slash', methods=['POST'])
def slash_response():                
    """endpoint for receiving all slash command requests from Slack"""

    # get the full request from Slack
    slack_request = request.form

    # starting a new thread for doing the actual processing    
    x = threading.Thread(
            target=some_processing,
            args=(slack_request,)
        )
    x.start()

    ## respond to Slack with quick message
    # and end the main thread for this request
    return "Processing information.... please wait"

def some_processing(slack_request):
    """function for doing the actual work in a thread"""

    # lets simulate heavy processing by waiting 7 seconds
    sleep(7)

    # response to Slack after processing is finished
    response_url = slack_request["response_url"]    
    message = {        
        "text": "We found a result!"
    }
    res = requests.post(response_url, json=message)

if __name__ == '__main__':
    app.run(debug=True, port=8000) #run app in debug mode on port 8000

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-11
    相关资源
    最近更新 更多