ロボタマ

風景写真中心の写真ブログです。コードも書くかも。

hubotベースのdaabのボット間でgRPCを使う

Hubotベースのdaabでも難なくgRPCを使うことができるのか、PORTもどうなるか、どうすべきか知っておきたくてコードを書きました。

まずは.protoファイルを書きます。

syntax = "proto3";

package hello;

service World {
  rpc Ping (stream TextMessage) returns (stream TextMessage) {}
}

message TextMessage {
  string msg = 1;
  string roomId = 2;
}

msgに送信メッセージの内容、roomIdにclient側のメッセージを受けたトークのidを渡します。

クライアント側のボットのコード

PINGというメッセージを受信すると、サーバ側のボットにメッセージを渡します。

// Description:
//   gRPC bot client
'use strict';

const PROTO_PATH = '../hello.proto';
const grpc = require('grpc');
const helloStream = grpc.load(PROTO_PATH).hello;
const client = new helloStream.World('localhost:50051', grpc.credentials.createInsecure());
const call = client.ping();

module.exports = (robot) => {
  robot.respond(/PING$/i, (res) => {
    call.write({ msg: 'Hello, Human!', roomId: res.message.room });
  });

  call.on('data', (res) => {
    robot.send({ room: res.roomId }, { text: res.msg });
  });

  call.on('end', () => call.end());
};

サーバ側のボットのコード

ボットを起動させた後、ペアトークCACHEとメッセージ送信して、トークのidをキャッシュしておく必要があります。
クライアント側からメッセージが送られて来た場合、そのトークにメッセージを送信します。

// Description:
//   gRPC bot server
'use strict';

const PROTO_PATH = '../hello.proto';
const grpc = require('grpc');
const helloStream = grpc.load(PROTO_PATH).hello;
const cache = {};

module.exports = (robot) => {
  robot.respond(/CACHE$/i, (res) => {
    cache.room = res.message.room;
    res.send('cache.');
  });

  const ping = (call) => {
    call.on('data', (req) => {
      if (!cache.room) {
        call.write({ msg: 'not found room.' });
        return;
      }

      const text = `receive message: ${ req.msg }`;

      robot.send(cache, {
        text,
        onsend: () => call.write({ msg: 'done.', roomId: req.roomId }),
      });
    });

    call.on('end', () => call.end());
  };

  const server = new grpc.Server();
  server.addService(helloStream.World.service, { ping });
  server.bind('0.0.0.0:50051', grpc.ServerCredentials.createInsecure());
  server.start();
};

実行

それぞれのボットを、daab run -dで実行します。 ボット自身のPORTは閉じて実行しています。

結果

f:id:yoshhiide:20180428003735j:plain

サンプルコードレポジトリ

github.com