Saturday, June 25, 2011

How To Handle Incoming Twilio Texts Larger Than 160 Characters

I've been working with Twilio for a few projects since the API is really easy to use. However, one issue that started coming up was incoming messages that were larger than 160 characters. Because of the way carriers handle multiple messages, Twilio has to break up and POST each message in 160 character limits.

For most applications, I store each incoming message in a MySQL database, and I wanted to store messages that are larger than 160 characters as one single message in the database. I work exclusively with PHP on the backend, and came across the sleep function, which pauses the execution of the script for the given number of seconds.

I create conversations based on the combination of the sender's phone number and the Twilio number the message was sent to, giving each a conversation id.
// Get the most recent message (if there is one)
$last = $this->convo->get_newest_msg($convoID);

First, I get the newest message available based on the conversation id. If this is the first message of the conversation, the get_newest_msg() method returns false.

// Calculate the how new the message is
$seconds = time() - $last['timestamp'];

Then I calculate the time between now and when the last message was received.

// See if there's a new message with in 10 seconds
if($seconds > 10) {
    $this->incoming->insert_message($convoID, $Body, $From);
    sleep(10);
    $newest = $this->convo->get_newest_msg($convoID);
    $Body = stripslashes($newest['text']);

    // Do anything else you need with the message
}
else {
    $this->incoming->add_to_message($last['msgID'], $last['text'].' '.$Body);
}

If the difference between the current message and the most recent message is greater than 10 seconds, I assume it's a text message that's longer than 160 characters. So I insert the message into the database, pause the execution for 10 seconds using 'sleep(10)'.

If there are multiple messages, each message is POST'd to my server every few seconds, but I've found 10 seconds to be a good length of time to wait for other potential messages.

If there is another message POST'd within 10 seconds that belongs to the same conversation (based on the sender's number and the Twilio number the message was sent to), the message is concatenated into one large message, and the database record is updated.

As a side note, I limit the 'text' field of the message table to 800 characters. If the text message is bigger than 800 characters, so be it. Text messages shouldn't be that long.

After 10 seconds, the script continues execution by getting the newest message once again. If there had been other messages POST'd within that 10 second time frame, I now have the full message text to do whatever I want with, such as forwarding as an email or triggering something else.

I'd welcome any questions, feedback or suggestions.

0 comments:

Post a Comment