Ruby Quickstart: Tracking SMS Conversations

Twilio offers a simple way to keep track of conversations between two phone numbers by using HTTP cookies.

Just like in web applications, a cookie is a small file that your application can store on Twilio's servers to keep track of information, such as a username or account. For Twilio SMS, cookies are scoped to the "conversation" between two parties -- you can have a unique cookie for each To/From phone number pair. For example, you can store a unique cookie for any messages sent between 415-555-2222 and 415-555-1111, which will be different than the cookie used between 415-555-3333 and 415-555-1111.

Why cookies?

In web apps, you write a cookie to keep "statefulness" between separate requests from the same browser. Similarly, SMS messages are independent communications between two parties, so Twilio allows you to tie them together as a logical session via cookies. This means you can use server-side sessions to keep track of application state between requests. How cool! Twilio will expire the cookies for that conversation after four hours of inactivity, as if the user "closed the browser."

Storing Conversation Data

The cookies let you share state across multiple messages allowing you to treat separate messages as a conversation, and store data about the conversation in the cookies for future reference.

Lets try using session counters to see if a particular user has messaged us before. If they're a new sender, we'll thank them for the new message. If they've sent us messages before, we'll specify how many messages we've gotten from them.

require 'rubygems'
require 'twilio-ruby'
require 'sinatra'

enable :sessions

get '/sms-quickstart' do
  session["counter"] ||= 0
  sms_count = session["counter"]
  if sms_count == 0
    message = "Hello, thanks for the new message."
    message = "Hello, thanks for message number #{sms_count + 1}"
  twiml = do |r|
    r.Message message
  session["counter"] += 1

Go ahead and send a few messages to your Twilio application, and watch your counter grow.

Next: Sending SMS Messages During a Phone Call »

Need some help?

We all do sometimes; code is hard. Get help now from our support team, or lean on the wisdom of the crowd browsing the Twilio tag on Stack Overflow.