|
| 1 | +// This is a simple example of how to use the slack-client module. It creates a |
| 2 | +// bot that responds to all messages in all channels it is in with a reversed |
| 3 | +// string of the text received. |
| 4 | +// |
| 5 | +// To run, copy your token below, then: |
| 6 | +// npm install |
| 7 | +// cd examples |
| 8 | +// node simple.js |
| 9 | + |
| 10 | +var Slack = require('..'); |
| 11 | + |
| 12 | +var token = 'xoxb-YOUR-TOKEN-HERE', // Add a bot at https://my.slack.com/services/new/bot and copy the token here. |
| 13 | + autoReconnect = true, |
| 14 | + autoMark = true; |
| 15 | + |
| 16 | +var slack = new Slack(token, autoReconnect, autoMark); |
| 17 | + |
| 18 | +slack.on('open', function() { |
| 19 | + |
| 20 | + var channels = [], |
| 21 | + groups = [], |
| 22 | + unreads = slack.getUnreadCount(), |
| 23 | + key; |
| 24 | + |
| 25 | + for (key in slack.channels) { |
| 26 | + if (slack.channels[key].is_member) { |
| 27 | + channels.push('#' + slack.channels[key].name); |
| 28 | + } |
| 29 | + } |
| 30 | + |
| 31 | + for (key in slack.groups) { |
| 32 | + if (slack.groups[key].is_open && !slack.groups[key].is_archived) { |
| 33 | + groups.push(slack.groups[key].name); |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + console.log('Welcome to Slack. You are @%s of %s', slack.self.name, slack.team.name); |
| 38 | + console.log('You are in: %s', channels.join(', ')); |
| 39 | + console.log('As well as: %s', groups.join(', ')); |
| 40 | + console.log('You have %s unread ' + (unreads === 1 ? 'message' : 'messages'), unreads); |
| 41 | +}); |
| 42 | + |
| 43 | +slack.on('message', function(message) { |
| 44 | + |
| 45 | + var type = message.type, |
| 46 | + channel = slack.getChannelGroupOrDMByID(message.channel), |
| 47 | + user = slack.getUserByID(message.user), |
| 48 | + time = message.ts, |
| 49 | + text = message.text, |
| 50 | + response = ''; |
| 51 | + |
| 52 | + console.log('Received: %s %s @%s %s "%s"', type, (channel.is_channel ? '#' : '') + channel.name, user.name, time, text); |
| 53 | + |
| 54 | + // Respond to messages with the reverse of the text received. |
| 55 | + |
| 56 | + if (type === 'message') { |
| 57 | + |
| 58 | + response = text.split('').reverse().join(''); |
| 59 | + channel.send(response); |
| 60 | + console.log('@%s responded with "%s"', slack.self.name, response); |
| 61 | + } |
| 62 | +}); |
| 63 | + |
| 64 | +slack.on('error', function(error) { |
| 65 | + |
| 66 | + console.error('Error: %s', error); |
| 67 | +}); |
| 68 | + |
| 69 | +slack.login(); |
0 commit comments