LoginSignup
11

More than 5 years have passed since last update.

BotkitでHubotみたいにscriptsを読み込む

Last updated at Posted at 2016-01-21

Hubotでは, scripts/ に置いたJavaScriptやCoffeeScriptを読み込んでくれます.
でも,Botkitにこの機能が無くて,不便に思ってる人も多いかと思います.
(Twitterを見ていると,この機能が欲しいという声が結構ありました.)

そこでHubotのソースコードを基に,Botkitで scripts/ の読み込みを実装してみました.

Botkitのディレクトリ構成

Hubotに倣って,このようなディレクトリ構成にしてみました.

botkit/
  bin/
    botkit
  node_modules/
  scripts/
    hello.js
  package.json

bin/botkit が本体で,実行権限の付いたJavaScriptのコードです.
scripts/hello.js は,サンプル用のスクリプトです.
package.json の中味はこんな感じです.

package.json
{
  "dependencies": {
    "botkit": ">= 0.0.*"
  },
  "engines": {
    "node": ">= 0.12.x",
    "npm": ">= 3.5.x"
  }
}

scriptsの読み込みの実装

Hubotのソースコードを基に,JavaScriptへの変換と処理の簡略化をしてみました.
参考にしたソースコードは,以下の2つです(行のハイライトをしています).

その結果 bin/botkit はこのようになりました.
処理内容は scripts/ 以下のファイルを require して,実行しているだけです.
また,読み込んだスクリプトで使えるように controller はグローバル変数にしています.

bin/botkit
#!/usr/bin/env node

var Botkit = require('botkit');
var Fs = require('fs');
var Path = require('path');

controller = Botkit.slackbot({
  debug: false
});

controller.spawn({
  token: process.env.BOTKIT_SLACK_TOKEN
}).startRTM();

var load = function(path, file) {
  var ext = Path.extname(file);
  var full = Path.join(path, Path.basename(file, ext));

  try {
    var script = require(full);
    if (typeof script === 'function') {
      script(this);
    }
  } catch(error) {
    process.exit(1);
  }
};

var path = Path.resolve('.', 'scripts')

Fs.readdirSync(path).sort().forEach(function(file) {
  load(path, file);
});

実際に使ってみる

今回は hello.js というスクリプトを用意しました.
hello というメンションに hello と返すだけです.

scripts/hello.js
controller.hears('hello', ['direct_mention', 'mention'], function(bot, message) {
  bot.reply(message, 'hello');
});

npm install してから,bin/botkit を実行してみます.
Slackでトークンを取得する必要がありますが,Qiitaに投稿されている記事を参考にします.

$ export BOTKIT_SLACK_TOKEN='xoxb-01234567890-abcdefghijklmnopqrstuvwx'
$ bin/botkit
** No persistent storage method specified! Data may be lost when process shuts down.
** Setting up custom handlers for processing Slack messages
** API CALL: https://slack.com/api/rtm.start
** BOT ID:  botkit  ...attempting to connect to RTM!

では,実際にSlack上でBotkitに hello と話し掛けてみましょう.
こんな感じで hello と挨拶を返してくれるはずです.

botkit.png

まとめ

今回はHubotを参考にして,Botkitで scripts/ の読み込みを実装してみました.
これで,Botkitでもコマンド毎にファイルを分割できるようになりますね.
(CoffeeScriptも読み込めるようになれば,もっと便利なのですが….)

Botkitは登場したばかりのフレームワークなので,今後の発展が楽しみです.
hubot-scriptsのようにbotkit-scriptsなどが実現すれば,もっと便利になりそうですね.

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
11