How to use the @slack/client.RTM_EVENTS.MESSAGE 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 jnummelin / kontena-slack-bot / index.js View on Github external
if(allowedUsers.lastIndexOf(user.name) != -1) {
      return true;
    }
    return false;
  }
}

// The client will emit an RTM.AUTHENTICATED event on successful connection, with the `rtm.start` payload if you want to cache it
rtm.on(CLIENT_EVENTS.RTM.AUTHENTICATED, function (rtmStartData) {
  console.log(`Logged in as ${rtmStartData.self.name} of team ${rtmStartData.team.name}, but not yet connected to a channel`);
});

var pty = require('node-pty');

// Emitted when there's a message on a channel where the bot is participating
rtm.on(RTM_EVENTS.MESSAGE, function handleRtmMessage(message) {
  try {
    if(message.text.lastIndexOf(botKeyword, 0) === 0) {
      if (allowChecker(message.user)) {
        cmd = "kontena " + message.text.substring(botKeyword.length);
        var term = pty.spawn('kontena', message.text.substring(botKeyword.length).trim().split(' '), {
          name: 'xterm-color',
          cols: 200,
          rows: 50,
          cwd: process.env.HOME,
          env: process.env
        });
        // Send typing notification to indicate that the work is ongoing
        const intervalObj = setInterval(() => {
          rtm.sendTyping(message.channel);
        }, 2000);
        // Collect all output data to an array
github novoda / spikes / slacker / app.js View on Github external
// getBiggestSlacker(oldest, latest, result => {
//   console.log(result);
// });


var rtm = new RtmClient(token, {logLevel: 'debug'});
rtm.start();

var messages = [];
var index = 0;

rtm.on(RTM_CLIENT_EVENTS.RTM_CONNECTION_OPENED, function () {
  test();
});

rtm.on(RTM_EVENTS.MESSAGE, function (message) {
  console.log(message);

  if (message.type === 'message' && !message.bot_id) {
    if (index === 100) {
      index = 0;
    }
    messages.splice(index, 0 , message);
    index++;
  }

  // Listens to all `message` events from the team
});

function test() {
  setTimeout(test, 30 * 60);
github slackapi / node-slack-sdk / examples / example-rtm-client.js View on Github external
/**
 * Example for creating and working with the Slack RTM API.
 */

/* eslint no-console:0 */

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

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

var rtm = new RtmClient(token, { logLevel: 'debug' });
rtm.start();

rtm.on(RTM_EVENTS.MESSAGE, function handleRtmMessage(message) {
  console.log('Message:', message);
});

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

rtm.on(RTM_EVENTS.REACTION_REMOVED, function handleRtmReactionRemoved(reaction) {
  console.log('Reaction removed:', reaction);
});
github denouche / virtual-assistant / src / interface / slack-service.js View on Github external
debug('Welcome to Slack. You are ' + rtmStartData.self.name + ' of ' + rtmStartData.team.name);
         
            if (channels.length > 0) {
                debug('You are in: ' + channels.join(', '));
            }
            else {
                debug('You are not in any channels.');
            }
         
            if (groups.length > 0) {
               debug('As well as: ' + groups.join(', '));
            }
        });


        this.slack.on(RTM_EVENTS.MESSAGE, (event) => {
            var channel = this.slack.dataStore.getChannelGroupOrDMById(event.channel);
            if(channel && event.type === 'message') {
                var message;
                switch(event.subtype) {
                    case undefined:
                        // new message
                        message = event;
                        break;
                    case 'message_changed':
                        message = event.message;
                        break;
                    default:
                        console.warn('event, RTM_EVENTS.MESSAGE with unmanaged event subtype ', event.subtype, JSON.stringify(event));
                        break;
                }
                if(message && message.text) {
github automerge / trellis / src / lib / ampl / amplnet / slack-signaler.js View on Github external
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);
  });

  //rtm.on(CLIENT_EVENTS.RTM.MESSAGE, function handleRtmMessage(message) {
  rtm.on(RTM_EVENTS.MESSAGE, function handleRtmMessage(message) {
    let ts = parseFloat(message.ts)
    if (last_ts && last_ts > ts) console.log("WARNING - TS OUT OF ORDER")
    console.log('Message:', message);
    try {
      let msg = JSON.parse(message.text)
      if (msg.session != SESSION) {
        if (msg.doc_id == DOC_ID) {
          if (msg.action == "hello") { // "hello" doesn't have a msg.body, so pass undefined
            HANDLERS['hello'](msg, undefined, (reply) => {
                let msgJSON = JSON.stringify({ action: "offer", name: NAME, session:SESSION, doc_id:DOC_ID, to:msg.session, body:reply})
                rtm.sendMessage(msgJSON, CHANNEL);
            })
          }
          if (msg.action == "offer" && msg.to == SESSION) {
            HANDLERS['offer'](msg, msg.body, (reply) => {
                let msgJSON = JSON.stringify({ action: "reply", name: NAME, session:SESSION, doc_id:DOC_ID, to:msg.session, body:reply})
github nlaz / monkbot / monkbot.js View on Github external
/* 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':
        rtm.sendMessage(usage, data['channel']);
        break;
      case 'add me':
        fetchGitHub(data['user'], rtm, data['channel']);
        break;
      case 'remove me':
github lvn / botstrap / lib / constants.js View on Github external
'raw_message': ['message'],
  'presenceChange': ['user', 'presence'],
  'statusChange': ['user', 'status'],
  'message': ['message'],
  'channelMarked': ['channel', 'ts'],
  'userTyping': ['user', 'channel'],
  'userChange': ['user'],
  'botRemoved': ['bot'],
  'messageSent': ['message'],
  'throw': ['error']
};

// new style events
eventArgs[RTM_EVENTS.REACTION_ADDED] = ['reaction'];
eventArgs[RTM_EVENTS.REACTION_REMOVED] = ['reaction'];
eventArgs[RTM_EVENTS.MESSAGE] = ['message'];

exports.eventArgs = eventArgs;

exports.errMsgs = {
  'err_plugin_type': 'Plugin type {{type}} does not exist!',
  'err_token': 'No token found!'
};

exports.NotImplementedError = new Error('Not implemented');
github ChartIQ / finsemble-seed / node_fileserver / slack.js View on Github external
console.log('CHANNEL_CREATED:', message);

	});
	rtm.on(RTM_EVENTS.CHANNEL_DELETED, function handleRtmMessage(message) {
		console.log('CHANNEL_DELETED:', message);

	});
	rtm.on(RTM_EVENTS.CHANNEL_MARKED, function handleRtmMessage(message) {
		console.log('CHANNEL_MARKED:', message);

	});




	rtm.on(RTM_EVENTS.MESSAGE, function handleRtmMessage(message) {
		console.log('Message:', message);
		/*Object
			channel:"D3J5SLQ77"
			team:"T3JNM7M9C"
			text:"aaaaaaaaaaaaaay"
			ts:"1488999990.000003"
			type:"message"
			user:"U3HB9D1HN"*/
		socket.emit("msgReceived", message);
	});
}
github FoundersFounders / door-services / door-open-service / node-backend / src / DoorSlackBot.js View on Github external
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));
        }
      }
    });

    this.rtm.on(CLIENT_EVENTS.RTM.ATTEMPTING_RECONNECT, () => {
      console.log("Attempting to reconnect to Slack...");
    });
github SphereSoftware / RebelChat / lib / Slack.js View on Github external
}
    })

    rtm.on(RTM_EVENTS.CHANNEL_LEFT, (obj) => {
      const { channel } = obj
      if (channel) {
        const chObj = new ChannelObject({
          id: channel,
          teamId: this.id,
          type: 'group',
        })
        store.dispatch(removeChannel(chObj))
      }
    })

    rtm.on(RTM_EVENTS.MESSAGE, (msg) => {
      if (msg.type !== 'message' || msg.subtype) {
        return
      }

      const message = new MessageObject({
        id: msg.ts,
        senderId: msg.user,
        channelId: msg.channel,
        teamId: this.id,
        text: msg.text,
        createdAt: msg.ts * 1000,
        state: 'received',
      })

      store.dispatch(receiveMessage(message))
      if (this.getDisplayedChannel().id !== message.channelId) {