我正在尝试使用hook.io microservice来制作一个松弛的斜杠命令机器人。根据docs,我应该可以立即发送响应,然后再发送单独的POST。但我无法立即得到回应,后来又发布了两篇文章。如何将即时和延迟响应都返回到松弛斜线命令?
这是我的测试代码。
module['exports'] = function testbot(hook) {
var request = require('request');
// The parameters passed in via the slash command POST request.
var params = hook.params;
data = {
"response_type": "ephemeral",
"text": "Immediate Response"
}
hook.res.setHeader('Content-Type', 'application/json');
console.log("returning immediate response")
hook.res.write(JSON.stringify(data), 'utf8', delay(params));
//calling end() here sends the immediate response but the POST never happens.
// but if end() is called below instead slack gives a timeout error but the POST succeeds.
//hook.res.end()
//test with 3.5 second delay
function delay(params) {
setTimeout(function() {post_response(params)},3500);
}
function post_response(params) {
console.log("posting delayed response")
// Set up the options for the HTTP request.
var options = {
// Use the Webhook URL from the Slack Incoming Webhooks integration.
uri: params.response_url,
method: 'POST',
// Slack expects a JSON payload with a "text" property.
json: {"response_type":"in_channel", "text":"Delayed response","parse":"full"}
};
// Make the POST request to the Slack incoming webhook.
request(options, function (error, response, body) {
// Pass error back to client if request endpoint can't be reached.
if (error) {
console.log(error);
hook.res.end(error.message);
} else {
console.log("post OK");
}
// calling end() here sends the POST but the immediate response is lost to a slack timeout error.
hook.res.end()
})
};
}
如调用res.end意见详细()早期指即时响应被发送,但POST从未发生过,而延迟res.end(),直至立柱装置延迟发送响应,但它产生之后在此期间,由于松弛造成的超时错误。
我是一个javascript新手,所以希望有一个简单的解决方案,我忽略了。
为什么从3.5秒延迟开始?根据松散的文档,如果您等待超过3秒钟的响应,则松弛会引发超时错误。 – Marak
看起来您正在将'delay'函数作为参数传递给'hook.res.write'。这不正确,因为'hook.res.write'不接受回调参数。 – Marak
@ Marak- 3.5秒故意超过闲置超时。我的目标是找到一种方法来立即作出回应,然后继续在后台处理数据并将结果作为单独的事务重新发回。上面显示的代码按照描述工作(post_response在3.5秒后成功完成),所以我有点困惑于你声称hook.res.write()不接受回调。 – rw950431