Ruby Quickstart: Greet Caller by Name

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:

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' do |r|
    r.say("Hello #{name}")

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
  2. Go to localhost:4567/hello-monkey and confirm you get TwiML back.

      <?xml version="1.0" encoding="UTF-8"?>
        <Say>Hello Monkey</Say>
  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 »

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.