Given a phone number and a message:
phone <- "+254717555555"
message <- "This is a long message. It keeps going on and on. It will definitely be more than 160 characters. See, it just keeps going. It might go on forever and ever. And ever. This is so long that it will probably take 3 or 4 messages to send. Something like that. I wonder if we can make it work?"
Start by splitting the message into sentences by punctuation and counting the number of sentences in the message.
sentences <- strsplit(message, '(?<![^!?.])\\s+', perl=TRUE)
nsentences <- length(sentences[[1]])
msg <- sentences[[1]]
Then loop through counting characters per sentence and stringing together messages consisting of sentences with total characters less than 155.
s <- 1
m <- 1
while (s <= nsentences) {
sens <- msg[s:nsentences] # get subset of sentences
charPerSen <- nchar(sens)+1 # count characters per sentence
# plus 1 for space after sentence
cumChar <- cumsum(charPerSen) # get cumulative character count by sentence
i <- sum(cumChar < 155) # how many sentences from 1 cum less 155?
reply <- paste(sens[1:i], # string together these sentences
collapse=" ")
assign(paste0("r.", m), # assign to object name
reply)
s <- s + i
m <- m + 1
}
Then loop through messages to add “Respond”, phone, message count, and message.
tot <- m-1
for (r in 1:tot) {
x <- paste("Respond",
phone,
paste(r, tot, sep="/"),
get(paste0("r.", r)))
assign(paste0("r.", r), x)
print(x)
}
## [1] "Respond +254717555555 1/3 This is a long message. It keeps going on and on. It will definitely be more than 160 characters. See, it just keeps going."
## [1] "Respond +254717555555 2/3 It might go on forever and ever. And ever. This is so long that it will probably take 3 or 4 messages to send. Something like that."
## [1] "Respond +254717555555 3/3 I wonder if we can make it work?"