スクラッチでBotkitの構築するテンプレを毎回忘れるので記録しておく
Slack Botを用意
Customize Slack > Configure apps > Custom Integrations > Bots
今回のbot名はbotkit
としておいた
Botkitをインストール
npm i -S botkit
スクリプト
index.js
var Botkit = require('botkit');
const controller = Botkit.slackbot({
debug: false,
retry: Infinity //https://botkit.ai/docs/readme-slack.html#botkitslackbot
});
controller.spawn({
token: "xoxb-から始まるトークン"
}).startRTM(function (err) {
if (err) {
throw new Error(err);
}
});
/**
* RTM APIのイベント
* これがないと「Error: Stale RTM connection, closing RTM」というエラーになる
*/
controller.on('rtm_open', (bot, message) => {
console.info('** The RTM api just connected!')
})
controller.on('rtm_close', (bot, message) => {
console.info('** The RTM api just closed')
})
// メッセージ反応処理 helloというダイレクトメッセージに応答する
controller.hears('hello', 'direct_message', function (bot, message) {
console.log(message.text)
bot.reply(message, 'Hello yourself!');
});
今回はダイレクトメッセージにしか反応しないが、以下のイベントを登録しておけば会話にも反応するようになる。
https://botkit.ai/docs/readme-slack.html#event-list
起動
node index.js
動作確認
SlackからDirect Messagesで「hello」と話しかけてみる
もしくはSlackコマンド /dm @botkit hello
Hello yourself!
と返事がくるはず
参考リンク
- howdyai/botkit: Botkit is the leading developer tool for building chat bots, apps and custom integrations for major messaging platforms. https://github.com/howdyai/botkit
- Botkit and Slack | Botkit Documentation https://botkit.ai/docs/readme-slack.html