Greet Caller by Name

Calls that offer dynamic information to the caller can have a positive impact on the user experience. This tutorial will use Plivo’s <Speak> element to read out the caller’s name when the phone number is recognized. More specifically, here is what will happen behind the scenes:

  1. A call is made to the Plivo phone number assigned to your greeting application
  2. When the call is connected, Plivo detects the phone number. If the phone number is recognized, then Plivo will greet the caller with “Hello (name of caller)”. If the number is not recognized, Plivo will say “Hello Stranger!”.
  3. After the name is read, the call is automatically hung up.

Prerequisites

  1. Sign up for a free Plivo trial account.
  2. Check out our Helper Libraries page and install the right helper based on the programming language you want to use.
  3. Buy a Plivo phone number. A phone number is required to receive calls. You can buy a Plivo phone number in over 20+ countries through the Buy Numbers tab on your Plivo account UI. Check the Voice API coverage page for all the supported countries.
  4. Use a web hosting service to host your web application. There are many inexpensive cloud hosting providers that you can use for just a few dollars a month. Follow the instructions of your hosting provider to host your web application.

Set up a Web Server

Let’s assume your web server is located at myvoiceapp.com. Below is a snippet to set up a route on your webserver. Lets call it, greet_caller. Now when we send an HTTP request to myvoiceapp.com/greet_caller this route will be invoked. You will now have to configure this URL in your Plivo application.

Note: For PHP, the route will be myvoiceapp.com/greet_caller.php
  1. Copy the relevant code below into a text file and save it. Lets call it, greet_caller.
    Note: Make sure to use the appropriate file extention for your code (e.g., greet_caller.py for Python).
  2. Edit the phone numbers and names that you would like Plivo to recognize (e.g., “14152225555”: “Cathy”,). Insert each entry on a new line.
  3. Edit the greeting message (optional). You can customize the greeting message with your own. By default, recognized callers will be greeted with “Hello” and their name, while unrecognized callers will be greeted with “Hello Stranger!”.
  4. Now that you have the code, you will need to expose your server to the public Internet. This way, Plivo will know where to find your app when a particular phone number is dialed. Moving forward, we will assume that your app is available at myvoiceapp.com.

Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
from flask import Flask, Response, request
import plivo, plivoxml

app = Flask(__name__)

@app.route('/greet_caller/', methods=['GET', 'POST'])
def greet_caller():
    from_number = request.values.get('From')
    callers = {
        "1111111111": "ABCDEF",
        "2222222222": "VWXYZ",
        "3333333333": "QWERTY",
    }

    response = plivoxml.Response()
    if from_number in callers:
        body = "Hello," + callers[from_number]
    else:
        body = "Hello Stranger!"

    response.addSpeak(body)
    print response.to_xml()
    return Response(str(response), mimetype='text/xml')

if __name__ == "__main__":
    app.run(host='0.0.0.0', debug=True)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
require 'rubygems'
require 'sinatra'
require 'plivo'
include Plivo

get '/greet_caller/' do

    callers = {
        '1111111111' => 'ACDEF',
        '2222222222' => 'WVXYZ',
        '3333333333' => 'QWERTY'
    }

    from_number = params[:From]
    r = Response.new()

    if callers.include? from_number
        body = "Hello " + callers[from_number]
    else
        body = 'Hello Stranger!'
    end

    r.addSpeak(body)
    puts r.to_xml()
    content_type 'text/xml'
    return r.to_s()

end
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
var plivo = require('plivo');
var express = require('express');
var bodyParser = require('body-parser');
var app = express();

app.use(bodyParser.urlencoded({extended: true}));
app.set('port', (process.env.PORT || 5000));

app.all('/greet_caller/', function(request, response) {
    var r = plivo.Response();
    var from_number = request.body.From || request.query.From;
    var callers = {
        "1111111111": "ABCDEF",
        "2222222222": "VWXYZ",
        "3333333333": "QWERTY"
    };

    var body;
    if (callers[from_number])
        body = "Hello " + callers[from_number] ;
    else
        body = "Hello Stranger";

    r.addSpeak(body);
    console.log(r.toXML());

    response.set({'Content-Type': 'text/xml'});
    response.send(r.toXML());
});

app.listen(app.get('port'), function() {
    console.log('Node app is running on port', app.get('port'));
});
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<?php
    require 'vendor/autoload.php';
    use Plivo\Response;
    $from_number = $_REQUEST['From'];
    $callers = array(
        '1111111111' => 'ABCDEF',
        '2222222222' => 'VWXYZ',
        '3333333333' => 'QWERTY'
    );

    $r = new Response();

    if (array_key_exists($from_number, $callers))
    {
        $body = "Hello {$callers[$from_number]}" ;
        $r->addSpeak($body);
    }
    else
    {
        $body = "Hello Stranger!";
        $r->addSpeak($body);
    }

    Header('Content-type: text/xml');
    echo($r->toXML());
?>
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package plivoexample;

import java.io.IOException;
import java.util.HashMap;
import com.plivo.helper.exception.PlivoException;
import com.plivo.helper.xml.elements.PlivoResponse;
import com.plivo.helper.xml.elements.Speak;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class greetCaller extends HttpServlet {
    private static final long serialVersionUID = 1L;
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        HashMap<String, String> callers = new HashMap<String, String>();
        callers.put("1111111111", "ABCDEF");
        callers.put("2222222222", "VWXYZ");
        callers.put("3333333333", "QWERTY");

        String fromNumber = req.getParameter("From");
        String knownCaller = callers.get(fromNumber);
        String message;
        if (knownCaller == null) {
            // Use a generic message
            message = "Hello Stranger";
        } else {
            // Use the caller's name
            message = "Hello " + knownCaller;
        }

        PlivoResponse response = new PlivoResponse();
        Speak speak = new Speak(message);
        try {
            response.append(speak);
            System.out.println(response.toXML());
            resp.addHeader("Content-Type", "text/xml");
            resp.getWriter().print(response.toXML());;
        } catch (PlivoException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws Exception {
        String port = System.getenv("PORT");
        if(port==null)
            port ="8000";
        Server server = new Server(Integer.valueOf(port));
        ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
        context.setContextPath("/");
        server.setHandler(context);
        context.addServlet(new ServletHolder(new greetCaller()),"/greet_caller/");
        server.start();
        server.join();
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
using System;
using System.Collections.Generic;
using System.Diagnostics;
using RestSharp;
using Plivo.XML;
using Nancy;

namespace greetCaller
{
    public class Program : NancyModule
    {
        public Program()
        {
            Get["/greet_caller/"] = x =>
            {
                var callers = new Dictionary<string, string>() {
                    {"1111111111","ABCDEF   "},
                    {"2222222222","VWXYZ"},
                    {"3333333333","QWERTY"}
                };

                String fromNumber = Request.Query["From"];

                Plivo.XML.Response resp = new Plivo.XML.Response();

                if (callers.ContainsKey(fromNumber))
                {
                    string body = "Hello " + callers[fromNumber];
                    resp.AddSpeak(body,new Dictionary<string, string>(){});
                }
                else
                {
                    resp.AddSpeak("Hello Stranger!", new Dictionary<string, string>() { });
                }

                var output = resp.ToString();
                var res = (Nancy.Response)output;
                res.ContentType = "text/xml";
                return res;
            };
        }
    }
}

Create an Application

  1. Create an Application by visiting the Application Page and click on New Application or by using Plivo’s Application API.
  2. Give your application a name. Lets call it Greet Caller. Enter your server URL (e.g., http://myvoiceapp.com/greet_caller) in the Answer URL field and set the method as POST or GET. See our Application API docs to learn how to modify your application through our APIs.
  3. Click on Create to save your application.

Create Text to Speech Application

Assign a Plivo number to your app

  1. Navigate to the Numbers page and select the phone number you want to use for this app.
  2. Select Greet Caller (name of the app) from the Plivo App dropdown list.
  3. Click on Update to save.

Create Text to Speech Application

If you don’t have a number, go to the Buy Number page to purchase a Plivo phone number.

SMS Phone Number Search

Test it out

Now, make a call to the Plivo number that you associated with your application. Upon connecting the call, Plivo will detect the call and fetch the answer URL, which resides at myvoiceapp.com/greet_caller. Then, Plivo will execute the XML instruction from your URL and read the caller’s name.

Sample XML

Below is the XML output when the phone number is recognized.

<Response>
    <Speak>Hello,ABCDEF</Speak>
</Response>

Below is the XML output when the phone number is unrecognized.

<Response>
    <Speak>Hello, Stranger!</Speak>
</Response>

Next Step

Learn how to play a MP3 or WAV file when a call is received.

  1. Make an Outbound Call
  2. Play a Text-to-speech Message
  3. Connect Call to a Second Person
  4. Greet Caller by Name
  5. Play MP3/WAV Audio to Caller
  6. Hangup Using API
  7. Receive Incoming Call
  8. Forward Incoming Call
  9. Record Using API
  10. Screen Incoming Call
  11. Reject incoming call
  12. Get Details of all Calls
  13. Get Details of a single Call
  14. Get Details of Live Calls
  15. Build an IVR Phone Menu
  16. Conference Call
  17. Call Forward
  18. SIP Endpoint (Direct-Dial)
  19. Inbound Trunk
  20. Outbound Trunk