How do you turn a handful of isolated messages to and from the same party into a true conversation? You need some way to remember state between each message that is exchanged. This is because SMS is a stateless protocol. Building traditional web applications has this same hurdle, as HTTP is also a stateless protocol. This problem has been solved for web applications through the use of HTTP cookies and, rather than reinvent the wheel, the Twilio Messaging API uses the same solution.
This guide will show you how to use Programmable Messaging to accomplish this in your Ruby application. The code snippets in this guide are written using Ruby version 2.0.0 or higher, and make use of the following modules:
If you haven't written your own SMS webhooks with Ruby before, you may want to first check out our guide, Receive and Reply to SMS and MMS Messages in Ruby. Ready to go? Let's get started!
Twilio Conversations, a more recent product offering, is an omni-channel messaging platform that allows you to build engaging conversational, two-way messaging experiences. Be sure to check out our Conversations product to see if it's a better fit for your needs.
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.
You can store the data directly in a cookie, or you can use a session state management framework.
Let's 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.
1require 'rubygems'2require 'twilio-ruby'3require 'sinatra'45use Rack::Session::Cookie, key: 'rack.session',6path: '/',7secret: 'can-be-anything-but-keep-a-secret'89# Return the session number for each sms received.10post '/sms' do11session['counter'] ||= 012sms_count = session['counter']1314message = if sms_count.zero?15'Hello, thanks for the new message.'16else17"Hello, thanks for message number #{sms_count + 1}"18end1920twiml = Twilio::TwiML::MessagingResponse.new do |r|21r.message(body: message)22end2324session['counter'] += 12526content_type 'text/xml'2728twiml.to_s29end