LoginSignup
7
3

More than 5 years have passed since last update.

Botkitのスクラッチ構築テンプレ

Last updated at Posted at 2018-09-15

スクラッチでBotkitの構築するテンプレを毎回忘れるので記録しておく

Slack Botを用意

Customize Slack > Configure apps > Custom Integrations > Bots

スクリーンショット_2018-09-15_18_01_47.png

今回の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!と返事がくるはず

スクリーンショット 2018-09-15 18.17.25.png

参考リンク

7
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
3