Get Started

Twilio SMS and MMS Ruby Quickstart

Replying to Incoming Messages

OK, we've said "Hello" in reply to people who have sent SMS messages to us, but what if we want to customize our response in some way?

For example, we're going to make an app that greets the sender by name if they're in our contacts list and send back a general greeting if they're not:

sms-quickstart.rb
require 'rubygems'
require 'twilio-ruby'
require 'sinatra'

get '/sms-quickstart' do
  sender = params[:From]
  friends = {
    "+14153334444" => "Curious George",
    "+14158157775" => "Boots",
    "+14155551234" => "Virgil"
  }
  name = friends[sender] || "Mobile Monkey"
  twiml = Twilio::TwiML::Response.new do |r|
    r.Message "Hello, #{name}. Thanks for the message."
  end
  twiml.text
end

Save your own (non-Twilio) phone number and name in the friends array above. Then, do the following steps to make your app live:

1) Open the terminal and start your server with Sinatra:

$ ruby sms-quickstart.rb
>> Sinatra has taken the stage ...
>> Listening on 0.0.0.0:4567

2) Go to http://localhost:4567/sms-quickstart and confirm you get TwiML back.

<?xml version="1.0" encoding="UTF-8"?>
<Response>
    <Message>Hello, Mobile Monkey. Thanks for the message.</Message>
</Response>

Now, try sending your Twilio number a text. If you add your phone number and name to the friends array you will get a personalized SMS thank-you message from your app.


Next: Tracking Conversations »