Connect Call to a Second Person

This tutorial prompts the caller to press ‘1’ if they would like to be connected to a second person. If the caller presses ‘1’, then they will be connected to a second person. Here’s what it looks like step-by-step:

  1. A call is made to the Plivo phone number assigned to your application
  2. When the call is connected, Plivo prompts the caller to “Press 1 to connect to another caller.” and waits 5 seconds for the caller to respond. If the caller takes more than 5 seconds, the call is hung up.
  3. If the caller presses ‘1’, then Plivo will say “Connecting your call…” and dial the second phone number.
  4. If the second phone number is answered, then the first and second caller will be connected. If the second caller does not answer, or if the phone number doesn’t exist, then the second call is hung up and the current call continues.

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, connect. Now when we send an HTTP request to myvoiceapp.com/connect 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/connect.php
  1. Copy the relevant code below into a text file and save it. Lets call it, connect.
    Note: Make sure to use the appropriate file extention for your code (e.g., connect.py for Python).
  2. 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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
from flask import Flask, Response, request, url_for
import plivo, plivoxml

app = Flask(__name__)

@app.route("/connect/", methods=['GET', 'POST'])
def connect():
    r = plivoxml.Response()
    if request.method == 'GET':
        # Generate a Dial XML with the details of the number to call
        prompt = "Press 1 to connect to another caller"
        no_input = "No input received. Goodbye"
        getdigits_action_url = url_for('connect', _external=True)
        getDigits = plivoxml.GetDigits(action=getdigits_action_url,
                                       method='POST', timeout=5, numDigits=1,
                                       retries=1)
        getDigits.addSpeak(prompt)
        r.add(getDigits)
        r.addSpeak(no_input)

        return Response(str(r), mimetype='text/xml')

    elif request.method == 'POST':
        confirmation = "Connecting your call.."

        digit = request.form.get('Digits')

        if digit == "1":
            r.addSpeak(confirmation)
            number = "2222222222"
            d = r.addDial()
            d.addNumber(number)
        else
            r.addSpeak("Invalid Digit")

        print r.to_xml()
        return Response(str(r), 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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
require 'rubygems'
require 'sinatra'
require 'plivo'
include Plivo

get '/connect/' do
    # Generate a Dial XML with the details of the number to call

    r = Response.new()
    getdigits_action_url = "https://myvoiceapp.com/connect/"
    params = {
        'action' => getdigits_action_url, # The URL to which the digits are sent.
        'method' => 'POST', # Submit to action URL using GET or POST.
        'timeout' => '5', # Time in seconds to wait to receive the first digit.
        'numDigits' => '1', # Maximum number of digits to be processed in the current operation.
        'retries' => '1', # Indicates the number of retries the user is allowed to input the digits
    }
    getDigits = r.GetDigits(params)
    getDigits.addSpeak("Press 1 to connect to another caller")

    r.addSpeak("No input received. Goodbye")

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

post '/connect/' do
    digit = params[:Digits]
    r = Response.new()
    if (digit == "1")
        r.addSpeak("Connecting your call..")
        d = r.addDial()
        d.addNumber("2222222222")
        puts r.to_xml()
    else
        r.addSpeak("Invalid Digit")
        puts r.to_xml()
    end

    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
34
35
36
37
38
39
40
41
var express = require('express');
var plivo = require('plivo');
var bodyParser = require('body-parser');
var app = express();

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

app.all('/connect/', function(request, response) {
    var r = plivo.Response();
    if(request.method === "GET"){
        var getdigits_action_url = "http://myvoiceapp.com/connect/";
        var params = {
            'action' : getdigits_action_url, // The URL to which the digits are sent
            'method' : 'POST', // Submit to action URL using GET or POST
            'timeout' : '5', // Time in seconds to wait to receive the first digit
            'numDigits' : '1', // Maximum number of digits to be processed in the current operation
            'retries' : '1' // Indicates the number of retries the user is allowed to input the digits
        }   ;
        var getdigits = r.addGetDigits(params);
        getdigits.addSpeak("Press 1 to connect to another caller");
        r.addSpeak("No input received. Goodbye");
    } else {
        var digits = request.body.Digits;
        if (digits === "1"){
            r.addSpeak('Connecting your call');
            var d = r.addDial();
            d.addNumber("2222222222");
        } else {
            r.addSpeak("Invalid Digit");
        }
    }
    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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
<?php
    require 'vendor/autoload.php';
    use Plivo\Response;
    // Generate a Dial XML with the details of the number to call
    $r = new Response();
    switch($_SERVER['REQUEST_METHOD']) {
        case "GET":
            $getdigits_action_url = "https://example.com/phone_ivr.php";
            $params = array(
                'action' => $getdigits_action_url, // The URL to which the digits are sent.
                'method' => 'POST', // Submit to action URL using GET or POST.
                'timeout' => '5', // Time in seconds to wait to receive the first digit.
                'numDigits' =>  '1', // Maximum number of digits to be processed in the current operation. 
                'retries' => '1' // Indicates the number of retries the user is allowed to input the digits
            );

            $getDigits = $r->addGetDigits($params);
            $getDigits->addSpeak("Press 1 to connect to another caller");
            
            $r->addSpeak("No input received. Goodbye");
            
            Header('Content-type: text/xml');
            echo($r->toXML());
            break;
        case "POST":
            $digit = $_REQUEST['Digits'];
            if ($digit == '1'){
                // Add Speak tag
                $body = 'Connecting your call..';
                // Add speak element
                $r->addSpeak($body);
                // Add Dial tag
                $number = "2222222222";
                $d = $r->addDial();
                $d->addNumber($number);
            }
            else {
                $r->addSpeak("Invalid Digit");
            }

            Header('Content-type: text/xml');
            echo($r->toXML());
            break;
    }
?>
 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package plivoexample;

import java.io.IOException;
import com.plivo.helper.exception.PlivoException;
import com.plivo.helper.xml.elements.Dial;
import com.plivo.helper.xml.elements.Number;
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;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;

public class connectCall extends HttpServlet {
    private static final long serialVersionUID = 1L;
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

        PlivoResponse response = new PlivoResponse();
        GetDigits gd = new GetDigits();
        gd.setAction("http://myvoiceapp.com/connect/");
        gd.setMethod("POST");
        gd.setNumDigits(1);
        gd.setTimeout(5);
        gd.setRetries(1);
        Speak spk = new Speak("Press 1 to connect to another caller");
        Speak speak = new Speak("No input received. Goodbye");
        try {
            gd.append(spk);
            response.append(gd);
            response.append(speak);
            System.out.println(response.toXML());
            resp.addHeader("Content-Type", "text/xml");
            resp.getWriter().print(response.toXML());;
        } catch (PlivoException e) {
            e.printStackTrace();
        }
    }

    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

        String digit = req.getParameter("Digits");
        PlivoResponse response = new PlivoResponse();

        if (digit == "1")
        {
            Dial dial = new Dial();
            Number num = new Number("2222222222");
            Speak spk = new Speak("Connecting your call..");
            try {
                response.append(spk);
                dial.append(num);
                response.append(dial);
            } catch (PlivoException e) {
                e.printStackTrace();
            }
        }
        else
        {
            Speak speak = new Speak("Invalid Digit");
            try {
                response.append(speak);
            } catch (PlivoException e) {
                e.printStackTrace();
            }
        }

        System.out.println(response.toXML());
        resp.addHeader("Content-Type", "text/xml");
        resp.getWriter().print(response.toXML());
    }

    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 connectCall()),"/connect/");
        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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
using System;
using System.Collections.Generic;
using System.Diagnostics;
using RestSharp;
using Plivo.XML;
using Nancy;

namespace connect_call
{
    public class Program : NancyModule
    {
        public Program()
        {
            Get["/connect/"] = x =>
            {
                Plivo.XML.Response resp = new Plivo.XML.Response();
                String getdigits_action_url = "http://myvoiceapp.com/connect/";

                // Add GetDigits XML Tag
                GetDigits gd = new GetDigits("", new Dictionary<string, string>()
                {
                    {"action", getdigits_action_url},
                    {"method", "POST"},
                    {"timeout","5"},
                    {"numDigits","1"},
                    {"retries","1"}
                });

                // Add Speak XML Tag
                gd.AddSpeak("Press 1 to connect to another caller", new Dictionary<string, string>() { });
                resp.Add(gd);
                // Add Speak XML Tag
                resp.AddSpeak("No input received. Goodbye", new Dictionary<string, string>() { });

                Debug.WriteLine(resp.ToString());

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

            Post["/response/ivr"] = x =>
            {
                String digit = Request.Form["Digits"];
                Debug.WriteLine("Digit pressed : {0}", digit);

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

                if (digit == "1")
                {
                    // Add Speak XML Tag
                    resp.AddSpeak("Connecting your call..", new Dictionary<string, string>() { });

                    // Add Dial XML Tag
                    Plivo.XML.Dial dial = new Plivo.XML.Dial(new Dictionary<string, string>() { });
                    dial.AddNumber("2222222222", new Dictionary<string, string>() { });

                    resp.Add(dial);
                }
                else
                {
                    // Add Speak XML Tag
                    resp.AddSpeak("Invalid Digit", new Dictionary<string, string>() { });
                }

                Debug.WriteLine(resp.ToString());

                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 Connect Call. Enter your server URL (e.g., http://myvoiceapp.com/connect/) in the Answer URL field and set the method as 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 Connect Call (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

When you make a call to your Plivo number, you will be prompted to press ‘1’ in order to be connected to a second person.

Sample XML

<Response>
    <Speak>Connecting your call..</Speak>
    <Dial>
        <Number>2222222222</Number>
    </Dial>
</Response>

Next Steps

Learn how to have Plivo greet a recognized caller by name.

  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