Get Started

Twilio Ruby Quickstart

Greeting Callers by Name

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

This tutorial assumes you have a Ruby development environment with Sinatra and the twilio-ruby helper library. If you don't have these yet, please see our post on setting up your environment.

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

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

get '/hello-monkey' do
  people = {
    '+14158675309' => 'Curious George',
    '+14158675310' => 'Boots',
    '+14158675311' => 'Virgil',
    '+14158675312' => 'Marcel',
  }
  name = people[params['From']] || 'Monkey'
  Twilio::TwiML::Response.new do |r|
    r.Say "Hello #{name}"
  end.text
end

Save your own (non-Twilio) phone number and name in this "people" array. Then, do the following steps to take your app live:

  1. Start your server with Sinatra:

    $ ruby twiml-quickstart.rb
    >> Sinatra has taken the stage ...
    >> Listening on 0.0.0.0:4567
    
  2. Go to localhost:4567/hello-monkey and confirm you get TwiML back.

    <?xml version="1.0" encoding="UTF-8"?>
    <Response>
        <Say>Hello Monkey</Say>
    </Response>
    
  3. Save your app in a publicly-available URL

  4. Lastly, configure the Voice URL of your Twilio number to point to the TwiML XML above.

When Twilio makes a request to your URL, information about the call is included along with the request, such as the number the call is coming from and the time of the call. We then check to see if the caller is known looking up the number in the callers dictionary to extract their name. We then <Say> their name, or the word 'Monkey' if their Caller ID isn't known.

If you add your phone number and name to the callers dictionary, you can listen to Twilio greet you by name.

Note that the phone numbers in the callers dictionary have +1 prepended to them. '1' is the international country code for the US and Canada and the '+' formats the number in E.164 format, which is used by Twilio when passing you phone numbers.


Next: Play mp3 for Caller »