RxJS
Rx
Slack

Slack Realtime Message APIをRx.Observableにする

以下のコードの大部分は https://github.com/slackapi/node-slack-sdk から。

var  Rx = require('rx');

var RtmClient = require('@slack/client').RtmClient;

var CLIENT_EVENTS = require('@slack/client').CLIENT_EVENTS;

var botToken = process.env.SLACK_BOT_TOKEN;

var rtm = new RtmClient(botToken);

var channel;

rtm.on(CLIENT_EVENTS.RTM.AUTHENTICATED, (rtmStartData) => {
  for (const c of rtmStartData.channels) {
    if (c.is_member && c.name ==='general') { channel = c.id }
  }
  console.log(`Logged in as ${rtmStartData.self.name} of team ${rtmStartData.team.name}, but not yet connected to a channel`);
});

var source = Rx.Observable.create((observer) => {
  rtm.on(CLIENT_EVENTS.RTM.RAW_MESSAGE, x =>observer.onNext(x))
});

source.filter(msg => msg.match(/Banana/).subscribe(() => {
  rtm.sendMessage("Banana!", channel)
});

rtm.start();

実際必要なのはこの部分

var source = Rx.Observable.create((observer) => {
  rtm.on(CLIENT_EVENTS.RTM.RAW_MESSAGE, x =>observer.onNext(x))
});

var source = Rx.Observable.create((observer) => {
  rtm.on(CLIENT_EVENTS.RTM.RAW_MESSAGE, x =>observer.onNext(x))
});