How to use the @slack/client.CLIENT_EVENTS.RTM function in @slack/client

To help you get started, we’ve selected a few @slack/client examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github LeanKit-Labs / cowpoke / src / slack.js View on Github external
send() {}
		};
	}

	const rtm = new RtmClient( token, {
		// Sets the level of logging we require
		logLevel: "warn",
		// Initialise a data store for our client, this will load additional helper functions for the storing and retrieval of data
		dataStore: new MemoryDataStore(),
		// Boolean indicating whether Slack should automatically reconnect after an error response
		autoReconnect: false,
		// Boolean indicating whether each message should be marked as read or not after it is processed
		autoMark: true
	} );

	rtm.on( CLIENT_EVENTS.RTM.AUTHENTICATED, rtmStartData => {
		console.log( `Logged in as ${ rtmStartData.self.name } of team ${ rtmStartData.team.name }, but not yet connected to a channel` );
	} );
	rtm.on( CLIENT_EVENTS.RTM.DISCONNECT, () => {
		console.warn( "Disconnected from slack" );
		rtm.reconnect();
	} );
	rtm.on( CLIENT_EVENTS.RTM.ATTEMPTING_RECONNECT, () => {
		console.warn( "Attempting reconnect to slack" );
	} );
	rtm.on( CLIENT_EVENTS.RTM.WS_ERROR, () => {
		console.error( "Slack Error" );
	} );
	rtm.on( CLIENT_EVENTS.RTM.RTM_CONNECTION_OPENED, () => {
		console.log( "Ready to send messages" );
	} );
github slackapi / node-slack-sdk / examples / example-rtm-client-datastore.js View on Github external
var RtmClient = require('@slack/client').RtmClient;
var CLIENT_EVENTS = require('@slack/client').CLIENT_EVENTS;
var RTM_EVENTS = require('@slack/client').RTM_EVENTS;
var MemoryDataStore = require('@slack/client').MemoryDataStore;

var token = process.env.SLACK_API_TOKEN || '';

var rtm = new RtmClient(token, {
  logLevel: 'error', // check this out for more on logger: https://github.com/winstonjs/winston
  dataStore: new MemoryDataStore() // pass a new MemoryDataStore instance to cache information
});

rtm.start();

rtm.on(CLIENT_EVENTS.RTM.AUTHENTICATED, function handleRTMAuthenticated() {
  console.log('RTM client authenticated!');
});

rtm.on(RTM_EVENTS.MESSAGE, function handleRtmMessage(message) {
  console.log(
    'User %s posted a message in %s channel',
    rtm.dataStore.getUserById(message.user).name,
    rtm.dataStore.getChannelGroupOrDMById(message.channel).name
  );
});

rtm.on(RTM_EVENTS.REACTION_ADDED, function handleRtmReactionAdded(reaction) {
  console.log('Reaction added:', reaction);
});

rtm.on(RTM_EVENTS.REACTION_REMOVED, function handleRtmReactionRemoved(reaction) {
github matrix-hacks / matrix-puppet-slack / client.js View on Github external
return new Promise((resolve, reject) => {
      this.rtm = new RtmClient(this.token);

      // reject on any unrecoverable error
      this.rtm.on(CLIENT_EVENTS.RTM.UNABLE_TO_RTM_START, (err) => {
        this.emit('unable-to-start', err);
        reject(err);
      });

      // disconnect is called only when there is no chance of reconnection,
      // either due to unrecoverable errors or the disabling of reconnect
      // so it's the best way to know to act towards reconnecting
      // the issue here is that at this point we dont know if
      // its an "unrecoverable error" or not, so if we were to implement
      // reconnect ourself in respones to this event, we may start looping
      this.rtm.on(CLIENT_EVENTS.RTM.DISCONNECT, () => {
        this.emit('disconnected'); // can use this to announce status and issue a reconnect
      });

      this.rtm.on(CLIENT_EVENTS.RTM.AUTHENTICATED, (rtmStartData) => {
        this.web = new WebClient(this.token);
github nlaz / monkbot / monkbot.js View on Github external
"`@monkbot report` - Report daily commiters.\n" +
            "`@monkbot add me` - Add your name to monkbot's list of committers.\n" +
            "`@monkbot remove me` - Remove your name from monkbot's list of committers.";

var rtm = new RtmClient(token, {logLevel: DEBUG_LEVEL});
var web = new WebClient(token);

/* Event Handlers */

// Connection Opened
rtm.on(CLIENT_EVENTS.RTM.RTM_CONNECTION_OPENED, function () {
  console.log('Connection opened');
});

// Connection Closed
rtm.on(CLIENT_EVENTS.RTM.DISCONNECT, function () {
  console.log('Connection closed');
  closeDb();
});

// Message Event Handler
rtm.on(RTM_EVENTS.MESSAGE, function handleRtmMessage(data) {
  // Parse string and check commands
  var command = data['text'];
  var client_id = '<@' + rtm.activeUserId + '>';

  if (command.substring(0, client_id.length) == client_id) {
    // Bot has been summoned
    command = command.substring(client_id.length + 1).trim();

    switch (command) {
      case 'help':
github IBM / watson-discovery-news-alerting / bot / server-bot.js View on Github external
const rtm = new RtmClient(bot_token)

let channel

// The client will emit an RTM.AUTHENTICATED event on successful connection, with the `rtm.start` payload
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`)
})

rtm.on(CLIENT_EVENTS.RTM.RTM_CONNECTION_OPENED, () => {
  console.log('Connection opened.')
})

rtm.on(CLIENT_EVENTS.RTM.RAW_MESSAGE, (message) => {
  console.log(message)
})

rtm.start()
github matrix-hacks / matrix-puppet-slack / client.js View on Github external
this.emit('disconnected'); // can use this to announce status and issue a reconnect
      });

      this.rtm.on(CLIENT_EVENTS.RTM.AUTHENTICATED, (rtmStartData) => {
        this.web = new WebClient(this.token);
        debug(`Logged in as ${rtmStartData.self.name} of team ${rtmStartData.team.name}`);
        if (process.env.DEBUG) {
          const f = `data-${rtmStartData.team.name}.json`;
          debug(`DEBUG environment variable is on. writing data dump file for your perusal: ${f}`);
          require('fs').writeFileSync(f, JSON.stringify(rtmStartData, null, 2));
        }
        this.data = rtmStartData;
      });

      // you need to wait for the client to fully connect before you can send messages
      this.rtm.on(CLIENT_EVENTS.RTM.RTM_CONNECTION_OPENED, () => {
        this.emit('connected'); // can use this to announce status
        resolve();
      });

      this.rtm.on(CLIENT_EVENTS.RTM.RAW_MESSAGE, (payload) => {
        let data = JSON.parse(payload);
        if ( data.type === "message" ) {
          debug('emitting message:', data);
          this.emit('message', data);
        } else if (data.type === 'channel_joined') {
          this.data.channels.push(data.channel);
        } else if (data.type === 'reconnect_url') {
          // ignore
        } else if (data.type === 'pong') {
          // ignore
        } else {
github automerge / mpl / lib / ampl / amplnet / slack-signaler.js View on Github external
var SESSION = config.session || uuidv4();
  var NAME = config.name || "unknown";
  var DOC_ID = void 0;
  var last_ts = void 0;
  var onConnectHandler = function onConnectHandler() {};
  var CONNECT_DISPATCH = function CONNECT_DISPATCH(h) {
    onConnectHandler = h;
  };
  var opts = { retryConfig: { forever: true, maxTimeout: 30 * 1000 } };
  var connected = true;

  rtm = new RtmClient(config.bot_token, opts);
  DOC_ID = config.doc_id;

  // The client will emit an RTM.AUTHENTICATED event on successful connection, with the `rtm.start` payload
  rtm.on(CLIENT_EVENTS.RTM.AUTHENTICATED, function (rtmStartData) {
    if (connected) {
      // race condition
      onConnectHandler();
      HANDLERS['connect']();
      var _iteratorNormalCompletion = true;
      var _didIteratorError = false;
      var _iteratorError = undefined;

      try {
        for (var _iterator = rtmStartData.channels[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
          var c = _step.value;

          if (c.is_member && c.name === 'signals') {
            CHANNEL = c.id;
          }
        }
github FoundersFounders / door-services / door-open-service / node-backend / src / DoorSlackBot.js View on Github external
constructor(config) {
    this.rtm = new RtmClient(config.botToken, {
      dataStore: new MemoryDataStore(),
      autoReconnect: true
    });

    this.doorTimes = JSON.parse(JSON.stringify(config.doorTimes));
    this.msgCallbacks = [];

    this.rtm.on(CLIENT_EVENTS.RTM.AUTHENTICATED, rtmStartData => {
      console.log(`Logged in as ${rtmStartData.self.name}`);
    });

    this.rtm.on(CLIENT_EVENTS.RTM.RTM_CONNECTION_OPENED, () => {
      console.log("Opened RTM connection");
      this.channelInfo = this.rtm.dataStore.getChannelOrGroupByName(config.channel);
    });

    this.rtm.on(RTM_EVENTS.MESSAGE, rawData => {
      console.log(`Slack: ${JSON.stringify(rawData)}`);

      let { type, text, channel } = rawData;
      if (type !== "message" || !text || !channel) return;

      if (channel === this.channelInfo.id && text.indexOf(this.rtm.activeUserId) !== -1) {
        const match = _.find(this.msgCallbacks, cb => text.match(cb.regex));
        if (match) {
          this.getUserInfo(rawData.user).then(user => match.callback(user, text));
        }
      }
github ggauravr / slack-terminalize / index.js View on Github external
var _login = function () {
	
	if (!rtmClient) {
		throw new Error('Slack RTM client not initialized');
	}

	logger.info('Initiating RTM client authentication');
	rtmClient.start();

	rtmClient.on(CLIENT_EVENTS.RTM.AUTHENTICATED, function (rtmStartData) {
		if (!dispatcher.isInitialized()) {
			logger.info('RTM client authenticated.');
			_listen();
		}
	});
};
github broidHQ / integrations / broid-slack / src / core / adapter.ts View on Github external
this.session.start();

    const connected = Observable
      .fromEvent(this.session, CLIENT_EVENTS.RTM.RTM_CONNECTION_OPENED)
      .map(() =>
        Promise.resolve({ type: "connected", serviceID: this.serviceId() }));
    const authenticated = Observable
      .fromEvent(this.session, CLIENT_EVENTS.RTM.AUTHENTICATED)
      .map((e: any) => {
        R.forEach((user) => this.storeUsers.set(user.id, user), e.users || []);
        R.forEach((channel) => this.storeChannels.set(channel.id, channel),
          e.channels || []);
        return Promise.resolve({ type: "authenticated", serviceID: this.serviceId() });
      });
    const disconnected = Observable
      .fromEvent(this.session, CLIENT_EVENTS.RTM.DISCONNECT)
      .map(() =>
        Promise.resolve({ type: "connected", serviceID: this.serviceId() }));
    const rateLimited = Observable
      .fromEvent(this.session, CLIENT_EVENTS.WEB.RATE_LIMITED)
      .map(() =>
        Promise.resolve({ type: "rate_limited", serviceID: this.serviceId() }));

    return Observable.merge(connected, authenticated, disconnected, rateLimited)
      .mergeAll();
  }