How to use the @slack/client.RtmClient 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 automerge / trellis / src / lib / ampl / amplnet / slack-signaler.js View on Github external
function init(config) {
  let HANDLERS = { hello: () => {}, reply: () => {}, offer: () => {}, error: () => {} }
  let CHANNEL;
  let SESSION = config.session || UUID.generate()
  let NAME = config.name || "unknown"
  let DOC_ID;
  let last_ts
  let onConnectHandler = () => {}
  let CONNECT_DISPATCH = (h) => {
    console.log("GET SLACK CONNECT HANDLER")
    onConnectHandler = h
  }

  rtm = new RtmClient(config.bot_token);
  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, (rtmStartData) => {
    console.log("CALL SLACK CONNECT HANDLER")
    onConnectHandler()
    for (const c of rtmStartData.channels) {
      if (c.is_member && c.name ==='signals') { CHANNEL = c.id }
    }
    console.log(`Logged in as ${rtmStartData.self.name} of team ${rtmStartData.team.name}`);
  });

  // you need to wait for the client to fully connect before you can send messages
  rtm.on(CLIENT_EVENTS.RTM.RTM_CONNECTION_OPENED, function () {
    let msg = JSON.stringify({ action: "hello", name:NAME, session:SESSION, doc_id:DOC_ID })
    rtm.sendMessage(msg, CHANNEL);
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
      });
github IBM / watson-discovery-news-alerting / bot / server-bot.js View on Github external
import { RtmClient, CLIENT_EVENTS } from '@slack/client'

const bot_token = process.env.SLACK_BOT_TOKEN || ''

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.')
})
github cagataycali / xss-listener / index.js View on Github external
const RTM_EVENTS = require('@slack/client').RTM_EVENTS;
let SlackWebhook;
let chatId;
let rtm;
let TelegramBot;
// Middleware usage ..
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: true
}));
app.set('port', (process.env.PORT || 5000));
if (process.env.SLACK_HOOK_URL && process.env.SLACK_RTM_TOKEN) {
  SlackWebhook = new SlackIncomingWebhook(process.env.SLACK_HOOK_URL || '');
  const bot_token = process.env.SLACK_RTM_TOKEN || '';

  rtm = new RtmClient(bot_token);

  rtm.on(RTM_EVENTS.MESSAGE, getFromSlack);

  rtm.start();
}
if (process.env.TELEGRAM_TOKEN && process.env.TELEGRAM_USER_ID) {
  chatId = process.env.TELEGRAM_USER_ID;
  TelegramBot = new Telegram(process.env.TELEGRAM_TOKEN, {
    polling: true
  });
}

// Delete row ..
TelegramBot.onText(/\/delete (.+)/, (msg, match) => {
  const resp = match[1]; // TODO @cagatay check the id is string, prevent nosql object injection.
  if (msg.text.endsWith('all')) {
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);
    });
github ChartIQ / finsemble-seed / node_fileserver / slack.js View on Github external
function newRTMConnection(socket, session, callback) {
	console.log("rtm session", session);
	var rtm = new RtmClient(session.auth.access_token);
	setupSlackRTM(socket, session, rtm);
	global.slackConnections[session.id] = rtm;
	rtm.start();
	callback();

}
github FabricLabs / doorman / lib / slack / slackSupport.js View on Github external
module.exports = Doorman => {
  console.log(chalk.magenta(`Slack Enabled... Starting.`));
  if (Doorman.Auth.slack && Doorman.Auth.slack.bot_token) {
    console.log('Logging in to Slack...');
    Doorman.Slack = new RtmClient(Doorman.Auth.slack.bot_token);
    Doorman.Slack.c_events = require('@slack/client').CLIENT_EVENTS;
    Doorman.Slack.rtm_events = require('@slack/client').RTM_EVENTS;
    Doorman.Slack.start();
    require('./onEvent/auth-and-connect')(Doorman);
    require('./onEvent/message')(Doorman);
    require('./onEvent/team-join')(Doorman);
  } else {
    console.log(chalk.red('ERROR: Doorman must have a Slack bot token...'));
  }
};
github broidHQ / integrations / broid-slack / src / core / Adapter.ts View on Github external
public connect(): Observable {
    if (this.connected) {
      return Observable.of({ type: 'connected', serviceID: this.serviceId() });
    }

    if (!this.token) {
      return Observable.throw(new Error('Credential should exist.'));
    }

    if (this.webhookServer) {
      this.webhookServer.listen();
    }

    this.session = new RtmClient(this.token, { autoReconnect: true });
    this.sessionWeb = new WebClient(this.token);
    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: any) => this.storeUsers.set(user.id, user), e.users || []);
        R.forEach(
          (channel: any) => this.storeChannels.set(channel.id, channel),
          e.channels || []);
        return Promise.resolve({ type: 'authenticated', serviceID: this.serviceId() });
      });
github SphereSoftware / RebelChat / lib / Slack.js View on Github external
constructor(options) {
    this.id = options.team_id || options.id
    this.userId = options.user_id || options.userId
    this.name = options.team_name || options.name
    this.accessToken = options.access_token || options.accessToken

    this.rtm = new RtmClient(this.accessToken, {
      logLevel: 'debug',
      dataStore: new MemoryDataStore(),
    })

    this.web = new WebClient(this.accessToken)
    this.bind()
  }
github broidHQ / integrations / broid-slack / lib / core / adapter.js View on Github external
connect() {
        if (this.connected) {
            return Rx_1.Observable.of({ type: "connected", serviceID: this.serviceId() });
        }
        if (!this.token) {
            return Rx_1.Observable.throw(new Error("Credential should exist."));
        }
        this.connected = true;
        this.webhookServer = new webHookServer_js_1.default(this.HTTPOptions, this.logLevel);
        this.webhookServer.listen();
        this.session = new client_1.RtmClient(this.token, { autoReconnect: true });
        this.sessionWeb = new client_1.WebClient(this.token);
        this.session.start();
        const connected = Rx_1.Observable
            .fromEvent(this.session, client_1.CLIENT_EVENTS.RTM.RTM_CONNECTION_OPENED)
            .map(() => Promise.resolve({ type: "connected", serviceID: this.serviceId() }));
        const authenticated = Rx_1.Observable
            .fromEvent(this.session, client_1.CLIENT_EVENTS.RTM.AUTHENTICATED)
            .map((e) => {
            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 = Rx_1.Observable
            .fromEvent(this.session, client_1.CLIENT_EVENTS.RTM.DISCONNECT)
            .map(() => Promise.resolve({ type: "connected", serviceID: this.serviceId() }));
        const rateLimited = Rx_1.Observable