TypeScriptでHubotを書いてみた

TypeScript Advent Calendar 2018 11日目の記事です。

ChatOpsの導入として、何かしらのbotをNode.jsで書いてみたいなあと思いまして、 社内向けにHubot(もう古い?)を導入してみました。

Node.jsでの開発は初めてだったのですが、せっかくならTypeScriptで書いてみようということになり、 TypeScriptでHubotを書いてみました。

導入編

まずHomebrewを使ってNVMとYarnをインストールします。

 $ brew install nvm
 $ nvm install --lts
 $ nvm use --lts
 $ brew install yarn --without-node

設定ファイルを用意したり、TypeScriptをインストールします。

 $ yarn init // 適当に答える
 $ yarn add  webpack webpack-cli ts-loader typescript tslint tslint-config-airbnb @types/node

Hubotをインストールします。

 $ yarn add generator-hubot yo hubot @types/hubot

ここら辺まで来ると、HubotをTSで書けるようになります。

import hubot = require("hubot");

module.exports = (robot: hubot.Robot<any>): void => {
  robot.respond(/hello/i, (msg: hubot.Response<hubot.Robot<any>>)=>{
    msg.reply("world!");
  });
};

プログラムを書いたので、テストを書きます。(TDDっぽく先に書いてもいいですね。)

まずは必要なライブラリをインストールします。

 $ yarn add --dev chai co hubot-test-helper mocha
const Helper = require('hubot-test-helper');
const helper = new Helper('../scripts/hello.js');

const co = require('co');
const expect = require('chai').expect;

describe('hello world', function() {
  beforeEach(function() {
    this.room = helper.createRoom();
  });
  afterEach(function() {
    this.room.destroy();
  });

  context('user says hello to hubot', function() {
    beforeEach(function() {
      return co(function*() {
        yield this.room.user.say('alice', '@hubot hello');
      }.bind(this));
    });

    it ('should reply to user', function() {
      expect(this.room.messages).to.eql([
        ['alice', '@hubot hello'],
        ['hubot', '@alice world!']
      ]);
    })
  });
});

これでひとまずプログラムとテストをTSで書くことができました!

運用編

Herokuにデプロイしています。 (Herokuへのデプロイで詰まった話はココ

その他

Hubotがメンテされていなくて辛い。

github.com