Botkit触ってみた
botkitを触ってみたのでメモ。
botkitはSlack上のbotを作るためのフレームワーク。いままで、HUBOTやnode-slack-clientでbotを作ってたのですが、より簡単にbotを作れるようになりました。
メッセージの受信が多彩
botは受信したメッセージによってなにか動作させるというのがオーソドックスな機能ですが、botkitを使うとその受信方法が色んな条件で書くことができます。
例えば、Hubotだと robot.hear
と robot.respond
でメンションされたかされてないかの判定のみでした。
robot.hear /badger/i, (res) -> res.send "Badgers? BADGERS? WE DON'T NEED NO STINKIN BADGERS" robot.respond /open the pod bay doors/i, (res) -> res.reply "I'm afraid I can't let you do that."
それに対してbotkitは引数に文字列を渡すことで5種類の判定が可能です。
controller.hears(['keyword', '^pattern$'],['direct_message','direct_mention','mention','ambient'], (bot, message) => { bot.reply(message,'You used a keyword!'); });
- message_received : 全てのメッセージ
- ambient : メンション以外のメッセージ
- direct_mention : 名前で始まるメッセージ(例:
@bot hello
) - mention : 名前を含むメッセージ(例:
hello @bot
) - direct_message : ダイレクトメッセージ
対話の実装が楽ちん
対話形式でbotに何かやらせようと思うと今まで実装がそこそこ大変だったのですが、botkitなら簡単にできます。例えばこんな対話も簡単に実装できます。
コードはこれだけです。pattern
を変えれば、はい
とかいいえ
にもできます。
controller.hears(['start'], ['ambient'], (bot, message) => { bot.startConversation(message, (err, convo) => { convo.ask('Are you sure?(yes/no)', [ { pattern: bot.utterances.yes, callback: (response, convo) => { convo.say('Start!'); convo.next(); } }, { pattern: bot.utterances.no, callback: (response, convo) => { convo.say('Quit!'); convo.next(); } }, { default: true, callback: (response, convo) => { convo.say("Please type of 'yes' or 'no'."); convo.repeat(); convo.next(); } } ]) }); });
Webサーバーを起動できる
Slash CommandやOutgoing Webhooks、またHerokuで動作させるためにはWebサーバーを起動させておく必要があるのですが、botkitには外部のライブラリを使わなくてもWebサーバーを起動できます。(内部でExpressを使用してる模様) やることによって色々前準備が必要だったりするので、詳しくはWorking with Slack Integrationsを参照してください
const port = 3000; controller.setupWebserver(port, (err, webserver) => { webserver.get('/ping', (req, res) => { controller.log("pong!"); res.send('pong!'); }); // [POST] /slack/receiveの追加 // Outgoing Webhooks や Slash commands の時に使う controller.createWebhookEndpoints(webserver); });