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