SlackのInteractive messagesでボタンの入力を受け付ける
node.jsまずはサーバーを用意する。コードはここにあって、 Interactive messagesのハンドリングはSlack公式のnode-slack-interactive-messagesを使っている。
app.use('/slack', slackMessages.expressMiddleware());
slackMessages.action('question_button', (payload) => {
let replacement = payload.original_message;
replacement.text =`${payload.user.name} likes ${payload.actions[0].value}`;
delete replacement.attachments[0].actions;
return replacement;
});
ボタンの表示はattachmentsを使う。
web.chat.postMessage(channelId, 'Question', {
attachments: [
{
text: "Which buttons do you like?",
color: "#f9a41b",
callback_id: "question_button",
actions: [
{
name: "primary_button",
type: "button",
style: "primary",
text: "Primary",
value: "Primary Button",
},
{
name: "normal_button",
type: "button",
text: "Normal",
value: "Normal Button"
},
{
name: "danger_button",
type: "button",
style: "danger",
text: "Danger",
value: "Danger Button",
confirm: {
title: "Really?",
text: "This is danger",
ok_text: "Yes",
dismiss_text: "No"
}
},
]
}
]
})
外に公開する必要があるので、メッセージの送信のエンドポイントはBasic認証をかけてみた。 Interactive messagesのエンドポイントはVerification tokenが一致することを確認している。
app.use(bodyParser.urlencoded({ extended: false }));
app.all('/auth/*', (req, res, next) => {
const credentials = auth(req);
if (!credentials || !check(credentials.name, credentials.pass)) {
res.status(401).send('Unauthorized');
} else {
next();
}
});
$ curl https://*****.ngrok.com/auth/message -H "Authorization: Basic $(echo -n 'foobar:dolphins' | base64)"
BuildからWorkspaceを選択してAppを作成し、 Appに紐づくBot Userを追加後、Install Appすると Bot User OAuth Access Token が表示されるので、これでpostMessage()し、Basic InformationのApp Credentialsにある Verification Token をInteractive messagesのチェックに使う。
参考
GolangでSlack Interactive Messageを使ったBotを書く - Mercari Engineering Blog