Method: Discordrb.split_message
- Defined in:
- lib/discordrb.rb
.split_message(msg) ⇒ Array<String>
Splits a message into chunks of 2000 characters. Attempts to split by lines if possible.
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 |
# File 'lib/discordrb.rb', line 76 def self.(msg) # If the messages is empty, return an empty array return [] if msg.empty? # Split the message into lines lines = msg.lines # Turn the message into a "triangle" of consecutively longer slices, for example the array [1,2,3,4] would become # [ # [1], # [1, 2], # [1, 2, 3], # [1, 2, 3, 4] # ] tri = (0...lines.length).map { |i| lines.combination(i + 1).first } # Join the individual elements together to get an array of strings with consecutively more lines joined = tri.map(&:join) # Find the largest element that is still below the character limit, or if none such element exists return the first ideal = joined.max_by { |e| e.length > CHARACTER_LIMIT ? -1 : e.length } # If it's still larger than the character limit (none was smaller than it) split it into the largest chunk without # cutting words apart, breaking on the nearest space within character limit, otherwise just return an array with one element ideal_ary = ideal.length > CHARACTER_LIMIT ? ideal.split(/(.{1,#{CHARACTER_LIMIT}}\b|.{1,#{CHARACTER_LIMIT}})/o).reject(&:empty?) : [ideal] # Slice off the ideal part and strip newlines rest = msg[ideal.length..].strip # If none remains, return an empty array -> we're done return [] unless rest # Otherwise, call the method recursively to split the rest of the string and add it onto the ideal array ideal_ary + (rest) end |