Reputation: 2292
I need to respond to the event request with an HTTP 2xx. I am using the Request method in Python. How can I just return it? Please help.
My current problem is, I am using tunnelling software on my localhost. So for slack:
Your app should respond to the event request with an HTTP 2xx within three seconds. If it does not, we'll consider the event delivery attempt failed. After a failure, we'll retry three times, backing off exponentially.
I respond back to slack by this command
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)
So now since I am not ending any response back in 3 seconds, its retries 3 times, so I am getting 4 responses back.
So as soon as I receive the request I need to respond back with Http2xx.
Upvotes: 2
Views: 3343
Reputation: 32737
In order to respond to a request with HTTP 200 you need to first spawn a 2nd process or thread to continue execution of the app and then terminate the primary thread / process.
There are many ways to do it, here is a complete example with threading and Flask.
It's receiving a slash command request from Slack, responds immediately with a short message. Then waiting 7 seconds to simulate heavy processing and finally responding with a message again.
This example is working with slash commands, but the approach works for events too.
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
Upvotes: 3