Использование Slack API dialog_open из облачных функций Firebase
Цель
Событие Slack Event-Subscription поражает мою конечную точку Firebase, а затем облачная функция Firebase использует dialog_open
конечная точка, чтобы открыть диалог в Slack с некоторыми значениями из Firebase.
вопрос
Когда функция Firebase Cloud попадает в Slack dialog_open
конечная точка, я получаю ошибки в журнале консоли.
я получаю body: { ok: false, error: 'trigger_expired' }
Тем не менее, журналы в Firebase показывают, что круговая передача составляет менее 500 миллисекунд. Но я не вижу идентификатора триггера, который будет регистрироваться в trigger_id с первого запроса (см. Код ниже).
4:57:12.443 PM | info | helloWorld | body: { ok: false, error: 'trigger_expired' }
4:57:04.163 PM | outlined_flag | helloWorld | Function execution took 254 ms, finished with status code: 200
4:57:03.910 PM | outlined_flag | helloWorld | Function execution started
Когда я запускаю событие Slack во второй, третий или четвертый раз после нового развертывания, я получаю body: { ok: false, error: 'invalid_trigger' }
5:31:29.757 PM helloWorld body: { ok: false, error: 'invalid_trigger' }
5:31:28.744 PM helloWorld Function execution took 9 ms, finished with status code: 200
5:31:28.740 PM helloWorld json.trigger_id: "405615464868.7467239747.e706f2732257c541c445ad3938a29fd3"
5:31:28.735 PM helloWorld Function execution started
Это также происходит достаточно быстро (9 мс), но другая ошибка триггера, И на этот раз я вижу json.trigger_id
из события Slack Event-Subscription.
Последнее, что я пробовал JSON.stringify:
trigger_id: JSON.stringify(json.trigger_id),
Теперь логи и ошибки разные:
5:33:24.512 PM | info | helloWorld | body: { ok: false, error: 'internal_error' }
5:33:23.565 PM | outlined_flag | helloWorld | Function execution took 13 ms, finished with status code: 200
5:33:23.559 PM | info | helloWorld | json.trigger_id: "406895248231.7467239747.7490e460213b3d65a44eef9f2e30c168"
5:33:23.553 PM | outlined_flag | helloWorld | Function execution started
Вопрос
Я должен делать что-то глупое. Любые догадки, что не так с моим trigger_id
?
Код
Вот Облачная Функция Firebase:
import * as rp from "request-promise";
import * as functions from "firebase-functions";
export const helloWorld = functions.https.onRequest((request, response) => {
return new Promise((_resolve, _reject) => {
let json = JSON.parse(request.body.payload);
console.log("json.trigger_id:", json.trigger_id);
const options = {
method: "POST",
uri: "https://slack.com/api/dialog.open",
body: {
trigger_id: json.trigger_id,
dialog: {
callback_id: json.callback_id,
title: "Request a Ride",
submit_label: "Request",
elements: [
{ type: "text", label: "Pickup Location", name: "loc_origin" },
{ type: "text", label: "Dropoff Location", name: "loc_destination" }
]
}
},
json: true,
headers: {
"Content-type": "application/json; charset=utf-8",
Authorization:
"Bearer xoxp-secret"
}
};
rp(options)
.then(function(body) {
console.log("body:", body);
})
.catch(function(err) {
console.log("err:", err);
});
return response.status(200).json({ message: "Hello from Firebase" });
}).catch(err => response.status(500).send(err));
});
1 ответ
Ответ
Нарушенные обещания: в моем примере обещания просто неверны.
Сообщение против диалога: диалоги не нужны или не подходят для этой цели.
Кодовый запах: web.chat.postMessage
не нужно отправлять обратно сообщение. Сообщение может быть отправлено обратно в Slack с помощью функции Firebase Cloud. res
,
Вот улучшенный пример.
...
exports.eventsSlackBot = functions.https.onRequest((req, res) => {
return new Promise((resolve, reject) => {
// asyc things happening
})
.then(() => {
resolve.status(200).send({
"text": "I am a test message http://slack.com",
"attachments": [{
"text": "And here’s an attachment!"
}]
});
})
.catch(console.error);
});
...