Skip to content

Commit

Permalink
Refactor and reorganize message splitting
Browse files Browse the repository at this point in the history
  • Loading branch information
redhotvengeance committed Dec 10, 2014
1 parent 5f8ba72 commit 218012d
Showing 1 changed file with 11 additions and 8 deletions.
19 changes: 11 additions & 8 deletions src/slack.coffee
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
SlackClient = require 'slack-client'
Util = require 'util'

MAX_MESSAGE_LENGTH = 4000

class SlackBot extends Adapter
constructor: (robot) ->
@robot = robot
Expand Down Expand Up @@ -107,27 +109,28 @@ class SlackBot extends Adapter
for msg in messages
@robot.logger.debug "Sending to #{envelope.room}: #{msg}"

# If message is greater than 4000 chars, split it into multiple msessages
if msg.length > 4000
if msg.length <= MAX_MESSAGE_LENGTH
channel.send msg

# If message is greater than MAX_MESSAGE_LENGTH, split it into multiple messages
else
submessages = []

while msg.length > 0
# Split message at last line break, if it exists
chunk = msg.substring(0, 4000)
breakIndex = if chunk.lastIndexOf('\n') isnt -1 then chunk.lastIndexOf('\n') else 4000
chunk = msg.substring(0, MAX_MESSAGE_LENGTH)
breakIndex = chunk.lastIndexOf('\n')
breakIndex = MAX_MESSAGE_LENGTH if breakIndex is -1

submessages.push msg.substring(0, breakIndex)

# Skip char if split on line break
breakIndex++ if breakIndex isnt 4000
breakIndex++ if breakIndex isnt MAX_MESSAGE_LENGTH

msg = msg.substring(breakIndex, msg.length)

channel.send m for m in submessages

else
channel.send msg

reply: (envelope, messages...) ->
@robot.logger.debug "Sending reply"

Expand Down

0 comments on commit 218012d

Please sign in to comment.