UNPKG

2.92 kBtext/coffeescriptView Raw
1{EventEmitter} = require 'events'
2SlackClient = require 'slack-client'
3Log = require 'log'
4
5class RemoteSlack extends EventEmitter
6 @MAX_MESSAGE_LENGTH: 4000
7 @MIN_MESSAGE_LENGTH: 1
8
9 constructor: (token) ->
10 @logger = new Log process.env.SLACK_LOG_LEVEL or 'info'
11 @token = token
12
13 options =
14 token: @token
15 autoReconnect: false
16 autoMark: true
17
18 @client = new SlackClient options.token, options.autoReconnect, options.autoMark
19
20 @client.on 'error', @.error
21 @client.on 'loggedIn', @.loggedIn
22 @client.on 'open', @.open
23
24
25 login: =>
26 @client.login()
27
28
29 error: (error) =>
30 return @logger.warning "Received rate limiting error #{JSON.stringify error}" if error.code == -1
31
32 @logger.error "Received error #{JSON.stringify error}"
33
34 @emit "remote.error", error
35
36 loggedIn: (self, team) =>
37 @logger.info "Logged in as #{self.name} of #{team.name}, but not yet connected"
38
39 open: =>
40 @logger.info 'Slack client now connected'
41
42 @emit "remote.connected", @
43
44 send: (envelope, messages...) ->
45
46 if not @client.connected or not @client.authenticated then @client.reconnect()
47
48 channel = @client.getChannelGroupOrDMByName envelope.room
49 if not channel and @client.getUserByName(envelope.room)
50 user_id = @client.getUserByName(envelope.room).id
51 @client.openDM user_id, =>
52 this.send envelope, messages...
53 return
54
55 if not channel or (@client.self.id not in channel.members and not channel.is_im) then return false
56
57 for msg in messages
58 continue if msg.length < RemoteSlack.MIN_MESSAGE_LENGTH
59
60 @logger.debug "Sending to #{envelope.room}: #{msg}"
61
62 if msg.length <= RemoteSlack.MAX_MESSAGE_LENGTH
63 channel.send msg
64
65 # If message is greater than MAX_MESSAGE_LENGTH, split it into multiple messages
66 else
67 submessages = []
68
69 while msg.length > 0
70 if msg.length <= RemoteSlack.MAX_MESSAGE_LENGTH
71 submessages.push msg
72 msg = ''
73
74 else
75 # Split message at last line break, if it exists
76 maxSizeChunk = msg.substring(0, RemoteSlack.MAX_MESSAGE_LENGTH)
77
78 lastLineBreak = maxSizeChunk.lastIndexOf('\n')
79 lastWordBreak = maxSizeChunk.match(/\W\w+$/)?.index
80
81 breakIndex = if lastLineBreak > -1
82 lastLineBreak
83 else if lastWordBreak
84 lastWordBreak
85 else
86 RemoteSlack.MAX_MESSAGE_LENGTH
87
88 submessages.push msg.substring(0, breakIndex)
89
90 # Skip char if split on line or word break
91 breakIndex++ if breakIndex isnt RemoteSlack.MAX_MESSAGE_LENGTH
92
93 msg = msg.substring(breakIndex, msg.length)
94
95 channel.send m for m in submessages
96
97module.exports = RemoteSlack
\No newline at end of file