Phone IVR

An IVR (Interactive Voice Response) system is also known as phone menu system. It is an automated phone system that interacts with a caller via pre-recorded or dynamic text-to-speech messages and inputs, via the keypad.

IVR systems are popular as they can handle large call volumes and help reduce the costs associated with customer service. With our app, you can build an entire phone menu system on the Plivo platform (in any computer language), without relying on expensive physical infrastructure.

The instructions below will teach you how to build your own IVR system that can:

  • Read a pre recorded text in different languages if ‘1’ is pressed.
  • Play a song if ‘2’ is pressed.
  • Say “Sorry, I didn’t catch that. Please hang up and try again later.” if nothing is pressed.

The app will operate in the following sequence:

  1. The user dials the Plivo IVR phone number.
  2. The user is prompted with the message “Welcome to the Plivo IVR Demo App. Press 1 to listen to a pre recorded text in different languages. Press 2 to listen to a song.”
  3. During the call, if the user presses ‘1’, then Plivo reads aother message “Press 1 for English. Press 2 for French. Press 3 for Russian” . If the user presses ‘2’, then Plivo plays a song.
  4. If anything else is pressed or if the user does nothing, then Plivo says “Sorry, I didn’t catch that. Please hang up and try again later.” and hangs 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 (optional).
  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 example.com. Below is a snippet to set up a route on your webserver. Lets call it, response/ivr. Now when we send an HTTP request to example.com/response/ivr this route will be invoked. You will now have to configure this URL in your Plivo application.

Note: For PHP, the route will be `example.com/ivr.php`.
  1. Copy the relevant code below into a text file and save it. Lets call it, ivr.

  2. Next, you will now have to configure this URL in your Plivo application.

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
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
91
92
93
# -*- coding: utf-8 -*-
from flask import Flask, Response, request, url_for
import plivoxml

# This file will be played when a caller presses 2.
PLIVO_SONG = "https://s3.amazonaws.com/plivocloud/music.mp3"

# This is the message that Plivo reads when the caller dials in
IVR_MESSAGE1 = "Welcome to the Plivo IVR Demo App. Press 1 to listen to a pre recorded text in different languages.  \
                Press 2 to listen to a song."

IVR_MESSAGE2 = "Press 1 for English. Press 2 for French. Press 3 for Russian"
# This is the message that Plivo reads when the caller does nothing at all
NO_INPUT_MESSAGE = "Sorry, I didn't catch that. Please hangup and try again \
                    later."

# This is the message that Plivo reads when the caller inputs a wrong number.
WRONG_INPUT_MESSAGE = "Sorry, it's wrong input."

app = Flask(__name__)

@app.route('/response/ivr/', methods=['GET','POST'])
def ivr():
    response = plivoxml.Response()
    if request.method == 'GET':
        getdigits_action_url = url_for('ivr', _external=True)
        getDigits = plivoxml.GetDigits(action=getdigits_action_url,
        method='POST', timeout=7, numDigits=1,
        retries=1)

        getDigits.addSpeak(IVR_MESSAGE1)
        response.add(getDigits)
        response.addSpeak(NO_INPUT_MESSAGE)
        print response.to_xml()
        return Response(str(response), mimetype='text/xml')

    elif request.method == 'POST':
        digit = request.form.get('Digits')
        print digit
        if digit == "1":
            # Read out a text.
            getdigits_action_url1 = url_for('tree', _external=True)
            getDigits1 = plivoxml.GetDigits(action=getdigits_action_url1,
            method='POST', timeout=7, numDigits=1,
            retries=1)
            getDigits1.addSpeak(IVR_MESSAGE2)
            response.add(getDigits1)
            response.addSpeak(NO_INPUT_MESSAGE)

        elif digit == "2":
            # Listen to a song
            response.addPlay(PLIVO_SONG)

        else:
            response.addSpeak(WRONG_INPUT_MESSAGE)

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

@app.route('/response/tree/', methods=['GET','POST'])
def tree():
    response = plivoxml.Response()
    digit = request.form.get('Digits')

    if digit == "1":
        text = u"This message is being read out in English"
        params = {
            'language': "en-GB",
        }
        response.addSpeak(text,**params)

    elif digit == "2":
        text = u"Ce message est lu en français"
        params = {
            'language': "fr-FR",
        }
        response.addSpeak(text,**params)

    elif digit == "3":
        text = u"Это сообщение было прочитано в России"
        params = {
            'language': "ru-RU",
        }
        response.addSpeak(text,**params)

    else:
        response.addSpeak(WRONG_INPUT_MESSAGE)

    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
 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
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
# encoding: utf-8
require 'rubygems'
require 'sinatra'
require 'plivo'
include Plivo

# This file will be played when a caller presses 2.
$PLIVO_SONG = "https://s3.amazonaws.com/plivocloud/music.mp3"

# This is the message that Plivo reads when the caller dials in
$IVR_MESSAGE1 = "Welcome to the Plivo IVR Demo App. Press 1 to listen to a pre recorded text in different languages. Press 2 to listen to a song."

$IVR_MESSAGE2 = "Press 1 for English. Press 2 for French. Press 3 for Russian"
# This is the message that Plivo reads when the caller does nothing at all
$NO_INPUT_MESSAGE = "Sorry, I didn't catch that. Please hangup and try again later."

# This is the message that Plivo reads when the caller inputs a wrong number.
$WRONG_INPUT_MESSAGE = "Sorry, it's wrong input."

get '/response/ivr/' do
    r = Response.new()

    getdigits_action_url = "https://example.com/response/ivr/"
    params = {
        'action' => getdigits_action_url,
        'method' => 'POST',
        'timeout' => '7',
        'numDigits' => '1',
        'retries' => '1'
    }
    getDigits = r.GetDigits(params)

    getDigits.addSpeak($IVR_MESSAGE1)
    r.addSpeak($NO_INPUT_MESSAGE)

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

end

post '/response/ivr/' do
    digit = params[:Digits]

    r = Response.new()

    if (digit == "1")
        getdigits_action_url = "https://example.com/response/tree/"
        params = {
            'action' => getdigits_action_url,
            'method' => 'GET',
            'timeout' => '7',
            'numDigits' => '1',
            'retries' => '1'
        }
        getDigits = r.GetDigits(params)

        getDigits.addSpeak($IVR_MESSAGE2)
        r.addSpeak($NO_INPUT_MESSAGE)

    elsif (digit == "2")
        r.addPlay($PLIVO_SONG)
    else
        r.addSpeak($WRONG_INPUT_MESSAGE)
    end

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

end

get '/response/tree/' do
    digit = params[:Digits]

    r = Response.new()

    if (digit == "1")
        body = "This message is being read out in English"
        params = {
            'language'=> "en-GB"
        }

        r.addSpeak(body,params)
    elsif (digit == "2")
        body = "Ce message est lu en français"
        params = {
            'language'=> "fr-FR"
        }

        r.addSpeak(body,params)
    elsif (digit == "3")
        body = "Это сообщение было прочитано в России"
        params = {
            'language'=> "ru-RU"
        }

        r.addSpeak(body,params)
    else
        r.addSpeak($WRONG_INPUT_MESSAGE)
    end

    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
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
91
92
93
94
95
96
97
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));

// This file will be played when a caller presses 2.
var PLIVO_SONG = "https://s3.amazonaws.com/plivocloud/music.mp3";

// This is the message that Plivo reads when the caller dials in
var IVR_MESSAGE1 = "Welcome to the Plivo IVR Demo App. Press 1 to listen to a pre recorded text in different languages. Press 2 to listen to a song.";

var IVR_MESSAGE2 = "Press 1 for English. Press 2 for French. Press 3 for Russian";
// This is the message that Plivo reads when the caller does nothing at all
var NO_INPUT_MESSAGE = "Sorry, I didn't catch that. Please hangup and try again later.";

// This is the message that Plivo reads when the caller inputs a wrong number.
var WRONG_INPUT_MESSAGE = "Sorry, you've entered an invalid input.";

app.get('/response/ivr/', function(request, response) {
  var r = plivo.Response();
  var getdigits_action_url, params, getDigits;
  getdigits_action_url = request.protocol + '://' + request.headers.host + '/response/ivr/';
  params = {
    'action': getdigits_action_url,
    'method': 'POST',
    'timeout': '7',
    'numDigits': '1',
    'retries': '1'
  };
  getDigits = r.addGetDigits(params);
  getDigits.addSpeak(IVR_MESSAGE1);
  r.addSpeak(NO_INPUT_MESSAGE);

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

app.post('/response/ivr/', function(request, response) {
  var r = plivo.Response();
  var getdigits_action_url, params, getDigits;
  var digit = request.body.Digits;
  console.log(digit);
  if (digit === '1') {
    getdigits_action_url = request.protocol + '://' + request.headers.host + '/response/tree/';
    params = {
      'action': getdigits_action_url,
      'method': 'POST',
      'timeout': '7',
      'numDigits': '1',
      'retries': '1'
    };
    getDigits = r.addGetDigits(params);
    getDigits.addSpeak(IVR_MESSAGE2);
    r.addSpeak(NO_INPUT_MESSAGE);
  } else if (digit === '2') {
    r.addPlay(PLIVO_SONG);
  } else {
    r.addSpeak(WRONG_INPUT_MESSAGE);
  }

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

app.all('/response/tree/', function(request, response) {
  var r = plivo.Response();
  var text, params;
  var digit = request.body.Digits || request.query.Digits;
  if (digit === "1") {
    text = "This message is being read out in English";
    params = {'language': 'en-US'};
    r.addSpeak(text, params);
  } else if (digit === "2") {
    text = "Ce message est lu en français";
    params = {'language': 'fr-FR'};
    r.addSpeak(text, params);
  } else if (digit === "3") {
    text = "Это сообщение было прочитано в России";
    params = {'language': 'ru-RU'};
    r.addSpeak(text, params);
  } else {
    r.addSpeak(WRONG_INPUT_MESSAGE);
  }

  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
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
91
92
<?php
    require 'vendor/autoload.php';
    use Plivo\Response;
    # This file will be played when a caller presses 2.
    $PLIVO_SONG = "https://s3.amazonaws.com/plivocloud/music.mp3";
    # This is the message that Plivo reads when the caller dials in
    $IVR_MESSAGE1 = "Welcome to the Plivo IVR Demo App. Press 1 to listen to a pre recorded text in different languages. Press 2 to listen to a song.";
    $IVR_MESSAGE2 = "Press 1 for English. Press 2 for French. Press 3 for Russian";
    # This is the message that Plivo reads when the caller does nothing at all
    $NO_INPUT_MESSAGE = "Sorry, I didn't catch that. Please hangup and try again later.";
    # This is the message that Plivo reads when the caller inputs a wrong number.
    $WRONG_INPUT_MESSAGE = "Sorry, wrong input.";
    $r = new Response();
    switch($_SERVER['REQUEST_METHOD']) {
        case "GET":
            $getdigits_action_url = "https://example.com/phone_ivr.php";
            $params = array(
            'action' => $getdigits_action_url,
            'method' => 'POST',
            'timeout' => '7',
            'numDigits' =>  '1',
            'retries' => '1'
            );
            $getDigits = $r->addGetDigits($params);
            $getDigits->addSpeak($IVR_MESSAGE1);
            $r->addSpeak($NO_INPUT_MESSAGE);
            Header('Content-type: text/xml');
            echo($r->toXML());
            break;
        case "POST":
            $digit = $_REQUEST['Digits'];
            if ($digit == '1'){
                $getdigits_action_url = "https://example.com/phone_tree.php";
                $params = array(
                    'action' => $getdigits_action_url,
                    'method' => 'GET',
                    'timeout' => '7',
                    'numDigits' =>  '1',
                    'retries' => '1'
                );
            $getDigits = $r->addGetDigits($params);
            $getDigits->addSpeak($IVR_MESSAGE2);
            $r->addSpeak($NO_INPUT_MESSAGE);
            }
            else if ($digit == '2'){
                $r->addPlay($PLIVO_SONG);
            }
            else {
                $r->addSpeak($WRONG_INPUT_MESSAGE);
            }
            Header('Content-type: text/xml');
            echo($r->toXML());
            break;
    }
?>

<!--phone_tree.php-->

<?php
    require 'vendor/autoload.php';
    use Plivo\Response;

    $WRONG_INPUT_MESSAGE = "Sorry, it's a wrong input." ;
    $r = new Response();
    $digit = $_REQUEST['Digits'];
    if ($digit == '1'){
        $body = "This message is being read out in English";
        $params = array(
            'language' => "en-GB"
          );
        $r->addSpeak($body,$params);
    }
    else if ($digit == '2'){
        $body = "Ce message est lu en français";
        $params = array(
            'language' => "fr-FR"
          );
        $r->addSpeak($body,$params);
    }
    else if ($digit == '3'){
        $body = "Это сообщение было прочитано в России";
        $params = array(
            'language' => "ru-RU"
          );
        $r->addSpeak($body,$params);
    }
    else {
        $r->addSpeak($WRONG_INPUT_MESSAGE);
    }
    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
 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
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
// phoneIvr.java
package plivoexample;

import java.io.IOException;

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;

import com.plivo.helper.exception.PlivoException;
import com.plivo.helper.xml.elements.GetDigits;
import com.plivo.helper.xml.elements.Play;
import com.plivo.helper.xml.elements.PlivoResponse;
import com.plivo.helper.xml.elements.Speak;

public class phoneIvr extends HttpServlet {

    private static final long serialVersionUID = 1L;
    // This file will be played when a caller presses 2.
    String PLIVO_SONG = "https://s3.amazonaws.com/plivocloud/music.mp3";

    // This is the message that Plivo reads when the caller dials in
    String IVR_MESSAGE1 = "Welcome to the Plivo IVR Demo App. Press 1 to listen to a "
            + "pre recorded text in different languages. Press 2 to listen to a song.";
    String IVR_MESSAGE2 = "Press 1 for English. Press 2 for French. Press 3 for Russian";

    // This is the message that Plivo reads when the caller does nothing at all
    String NO_INPUT_MESSAGE = "Sorry, I didn't catch that. Please hangup and try again later.";

    // This is the message that Plivo reads when the caller inputs a wrong number.
    String WRONG_INPUT_MESSAGE = "Sorry, it's wrong input.";

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

        PlivoResponse response = new PlivoResponse();
        GetDigits gd = new GetDigits();
        gd.setAction("http://example/response/ivr/");
        gd.setMethod("POST");
        gd.setNumDigits(1);
        gd.setTimeout(7);
        gd.setRetries(1);
        Speak spk = new Speak(IVR_MESSAGE1);
        Speak speak = new Speak(NO_INPUT_MESSAGE);
        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.equals("1")
        {
            // Read out a text
            GetDigits gd = new GetDigits();
            gd.setAction("http://example.com/response/tree/");
            gd.setMethod("POST");
            gd.setNumDigits(1);
            gd.setTimeout(7);
            gd.setRetries(1);
            Speak spk = new Speak(IVR_MESSAGE2);
            try {
                gd.append(spk);
                response.append(gd);
            } catch (PlivoException e) {
                e.printStackTrace();
            }
        }
        else if (digit.equals("2"))
        {
            // Listen to a song
            Play play = new Play(PLIVO_SONG);
            try {
                response.append(play);
            } catch (PlivoException e) {
                e.printStackTrace();
            }
        }
        else
        {
            // Wrong input
            Speak speak = new Speak(WRONG_INPUT_MESSAGE);
            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 phoneIvr()),"/response/ivr/");
        context.addServlet(new ServletHolder(new ivrTree()),"/response/tree/");
        server.start();
        server.join();
    }
}

// ivrTree.java

package plivoexample;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.plivo.helper.exception.PlivoException;
import com.plivo.helper.xml.elements.PlivoResponse;
import com.plivo.helper.xml.elements.Speak;

public class ivrTree extends HttpServlet{
    private static final long serialVersionUID = 1L;

    // This is the message that Plivo reads when the caller inputs a wrong number.
    String WRONG_INPUT_MESSAGE = "Sorry, it's wrong input.";

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        String digit = req.getParameter("Digits");
        PlivoResponse response = new PlivoResponse();

        if (digit.equals("1"))
        {
            // Read out text in English
            Speak speak = new Speak("This message is being read out in English");
            speak.setLanguage("en-GB");
            try{
                response.append(speak);
            } catch (PlivoException e) {
                e.printStackTrace();
            }
        }
        else if (digit.equals("2"))
        {
            // Read out text in French
            Speak speak = new Speak("Ce message est lu en français");
            speak.setLanguage("fr-FR");
            try{
                response.append(speak);
            } catch (PlivoException e) {
                e.printStackTrace();
            }
        }
        else if(digit.equals("3"))
        {
            // Read out text in Russian
            Speak speak = new Speak("Это сообщение было прочитано в России");
            speak.setLanguage("ru-RU");
            try{
                response.append(speak);
            } catch (PlivoException e) {
                e.printStackTrace();
            }
        }
        else
        {
            // Wrong input
            Speak speak = new Speak(WRONG_INPUT_MESSAGE);
            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());
    }
}
  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
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
using System;
using System.Collections.Generic;
using System.Diagnostics;
using RestSharp;
using Plivo.XML;
using Nancy;

namespace phone_ivr
{
    public class Program : NancyModule
    {
        public Program()
        {
            //  This file will be played when a caller presses 2.
            String PLIVO_SONG = "https://s3.amazonaws.com/plivocloud/music.mp3";
            // This is the message that Plivo reads when the caller dials in
            String IVR_MESSAGE1 = "Welcome to the Plivo IVR Demo App. Press 1 to listen to a pre recorded text in different languages. Press 2 to listen to a song.";

            String IVR_MESSAGE2 = "Press 1 for English. Press 2 for French. Press 3 for Russian";
            // This is the message that Plivo reads when the caller does nothing at all
            String NO_INPUT_MESSAGE = "Sorry, I didn't catch that. Please hangup and try again later.";
            // This is the message that Plivo reads when the caller inputs a wrong number.
            String WRONG_INPUT_MESSAGE = "Sorry, it's a wrong input.";

            Get["/response/ivr/"] = x =>
            {
                Plivo.XML.Response resp = new Plivo.XML.Response();
                String getdigits_action_url = "http://example.com/response/ivr/";

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

                // Add Speak XML Tag
                gd.AddSpeak(IVR_MESSAGE1, new Dictionary<string, string>() { });
                resp.Add(gd);
                // Add Speak XML Tag
                resp.AddSpeak(NO_INPUT_MESSAGE, 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")
                {
                    String getdigits_action_url = "http://example.com/response/tree/";

                    // Add GetDigits XML Tag
                    GetDigits gd = new GetDigits("", new Dictionary<string, string>()
                {
                    {"action", getdigits_action_url}, // The URL to which the digits are sent.
                    {"method", "GET"}, // Submit to action URL using GET or POST.
                    {"timeout","7"}, // 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
                });

                    // Add Speak XML Tag
                    gd.AddSpeak(IVR_MESSAGE2, new Dictionary<string, string>() { });
                    resp.Add(gd);
                    // Add Speak XML Tag
                    resp.AddSpeak(NO_INPUT_MESSAGE, new Dictionary<string, string>() { });
                }
                else if (digit == "2")
                {
                    // Add Play XML Tag
                    resp.AddPlay(PLIVO_SONG, new Dictionary<string, string>() { });
                }
                else
                {
                    // Add Speak XML Tag
                    resp.AddSpeak(WRONG_INPUT_MESSAGE, new Dictionary<string, string>() { });
                }

                Debug.WriteLine(resp.ToString());

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

            Get["/response/tree/"] = x =>
            {
                Plivo.XML.Response resp = new Plivo.XML.Response();
                String digit = Request.Query["Digits"];

                // Add Speak XMLTag
                if (digit == "1")
                {
                    resp.AddSpeak("This message is being read out in English", new Dictionary<string, string>()
                    {
                        {"language","en-GB"}
                    });
                }
                else if (digit == "2")
                {
                    resp.AddSpeak("Ce message est lu en français", new Dictionary<string, string>()
                    {
                        {"language","fr-FR"}
                    });
                }
                else if (digit == "3")
                {
                    resp.AddSpeak("Это сообщение было прочитано в России", new Dictionary<string, string>()
                    {
                        {"language","ru-RU"}
                    });
                }
                else
                {
                    resp.AddSpeak(WRONG_INPUT_MESSAGE, 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 Phone IVR. Enter your server URL (e.g., http://www.example.com/response/ivr) 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 Record Call 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 Phone IVR (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, the call will be answered by Plivo and Phone menu will be played.

Sample Output

<Response>
    <GetDigits action="http://dotnettest.apphb.com/response/ivr" method="POST" timeout="7" numDigits="1" retries="1">
        <Speak>
            Welcome to the Plivo IVR Demo App. Press 1 to listen to a pre recorded text in different languages. Press 2 to listen to a song.
        </Speak>
    </GetDigits>
    <Speak>
        Sorry, I didn't catch that. Please hangup and try again later.
    </Speak>
</Response>

If 1 is pressed, another menu is read out. Following is the generated Speak XML.

<Response>
    <GetDigits action="http://www.example.com/response/tree/" method="POST" numDigits="1" retries="1" timeout="7">
        <Speak>Press 1 for English. Press 2 for French. Press 3 for Russian</Speak>
    </GetDigits>
    <Speak>Sorry, I didn't catch that. Please hangup and try again later.</Speak>
</Response>

If 1 is pressed, the English text is read out. Following is the generated Speak XML.

<Response>
   <Speak language="en-US">This message is being read out in English</Speak>
</Response>

If 2 is pressed, the French text is read out. Following is the generated Speak XML.

<Response>
    <Speak language="fr-FR">Ce message est lu en français</Speak>
</Response>

If 3 is pressed, the Russian text is read out. Following is the generated Speak XML.

<Response>
    <Speak language="ru-RU">Это сообщение было прочитано в России</Speak>
</Response>

If 2 is pressed, a music is played. Following is the generated Play XML.

<Response>
   <Play>https://s3.amazonaws.com/plivocloud/music.mp3</Play>
</Response>

Next Step

Learn how to Forward Incoming Calls to a Plivo SIP Endpoint

  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