Screen Incoming Calls

    When you receive a call on your Plivo number, you can screen it using Plivo XML. In this example, when an incoming call is received, we will check if that number has been blacklisted. And if it has, then we will hangup immediately using the Hangup XML. If the phone number hasn’t been blacklisted, then we will return a Speak XML that will say “Hello, how are you today!”.

    Prerequisites

    1. Sign up for a free Plivo trial account.
    2. Check out our server-side SDKs page and install the right helper based on the programming language you want to use.
    3. 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. Let’s call it, screen_call. Now when we send an HTTP request to myvoiceapp.com/screen_call 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/screen_call.php`
    1. Copy the relevant code below into a text file and save it. Let’s call it, screen_call.
      Note: Make sure to use the appropriate file extention for your code (e.g., screen_call.py for Python).
    2. Add phone numbers to your black list that you want to reject.
    3. 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
    
    from flask import Flask, Response
    from flask import request
    from plivo import plivoxml
    
    app = Flask(__name__)
    
    @app.route('/screen_call/', methods=['GET', 'POST'])
    def screen_call():
    
        blacklist = ['14151234567','15671234567','15671234863']
        from_number = request.values.get('From')
        response = plivoxml.ResponseElement()
        
        if from_number in blacklist:
            params = {'reason': 'rejected'}
            response.add(plivoxml.HangupElement(**params))
        else:
            response.add(plivoxml.SpeakElement('Hello, how are you today'))
        return Response(response.to_string(), mimetype='application/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
    include Plivo::XML
    
    get '/screencall' do
        blacklist = ['14151234567', '15671234567', '15671234863']
    
        from_number = params[:From]
        r = Response.new()
    
        if blacklist.include? from_number
            # Specify the reason for hangup
            params = {
                reason: 'rejected'
            }
            r.addHangup(params)
        else
            r.addSpeak('Hello, how are you today')
        end
        xml = PlivoXML.new(r)
        puts xml.to_xml()
        content_type "application/xml"
        return xml.to_s() # Returns the XML
    
    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
    
    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('/screen_call/', function(request, response) {
        var blacklist = [ '14151234567', '15671234567', '15671234863'];
        // Get the caller's phone number from the 'From' parameter
        var from_number = request.query.From || request.body.From;
        var r = plivo.Response();
        if (blacklist.indexOf(from_number) === -1){
            var body = "Hello, how are you today";
            r.addSpeak(body);
        } else {
            //Specify the reason for hangup
    
            var params = {'reason': "rejected"};
            r.addHangup(params);
        }
        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
    
    <?php
        require 'vendor/autoload.php';
        use Plivo\XML\Response;
        $from_number = $_REQUEST['From'];
        $blacklist = array('14151234567', '15671234567', '15671234863');
        $r = new Response();
        if (in_array($from_number, $blacklist)) {
            $params = array('reason' => 'rejected');
            $r->addHangup($params);
        } else {
            $body = "Hello, how are you today!";
            $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
    
    import java.util.Arrays;
    import com.plivo.api.xml.Hangup;
    import com.plivo.api.xml.Response;
    import com.plivo.api.xml.Speak;
    import static spark.Spark.*;
    
    public class screencalls {
        public static void main(String[] args) {
            post("/forward", (request, response) -> {
                response.type("application/xml");
                String fromNumber = request.queryParams("From");
                String[] blacklist = { "14151234567","15671234567", "15671234863"};
            if (Arrays.asList(blacklist).contains(fromNumber)) {
                return new Response()
                        .children(
                                new Hangup()
                                        .reason("rejected")
                        ).toXmlString();
            } else {
                return new Response()
                        .children(
                                new Speak("Hello, how are you today!")
                        ).toXmlString();
            }
            });
        }
    }
    
    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
    
    package main
    
    import (
    	"github.com/go-martini/martini"
    	"github.com/plivo/plivo-go/xml"
    	"net/http"
    )
    
    func main() {
    	m := martini.Classic()
    	m.Get("/screen_call", func(w http.ResponseWriter, r *http.Request) string {
    		w.Header().Set("Content-Type", "application/xml")
    		fromNumber := r.FormValue("From")                                  
    		blacklist := []string{"14151234567", "15671234567", "15671234863"}
    
    		for _, num := range blacklist {
    			if num == fromNumber {
    				return xml.ResponseElement{
    					Contents: []interface{}{
    						new(xml.HangupElement).
    							SetReason("rejected"),
    					},
    				}.String()
    			}
    		}
    		return xml.ResponseElement{Contents: []interface{}{
    			new(xml.SpeakElement).
    				SetLoop(0).
    				SetContents("Hello, how are you today!"),
    		}}.String()
    	})
    	m.Run()
    }
    
    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
    
    using System;
    using System.Collections.Generic;
    using Plivo.XML;
    using Microsoft.AspNetCore.Mvc;
    
    namespace Screencall.Controllers
    {
        public class ScreencallController : Controller
        {
            // GET: /<controller>/
            public IActionResult Index()
            {
                string[] blacklist = { "14151234567", "15671234567", "15671234863" };
                string fromNumber = Request.Query["From"];
                Plivo.XML.Response resp = new Plivo.XML.Response();
    
                if (blacklist.Equals(fromNumber))
                {
                    resp.AddHangup(new Dictionary<string, string>()
                {
                    {"reason","rejected"}, // Specify the reason for hangup
                });
                }
                else
                {
                    resp.AddSpeak("Hello, how are you today!", new Dictionary<string, string>() { });
                }
                var output = resp.ToString();
                return this.Content(output, "text/xml");
            }
        }
    }
    

    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. Let’s call it “Screen Call”. Enter your server URL (e.g., http://myvoiceapp.com/screen_caller) in the “Answer URL” field and set the method as POST. See our Application API docs to learn how to modify your application through our APIs.
    3. Click on “Create” to save your application.

    Create Screencall 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 “Screen Call” (name of the app) from the Plivo App dropdown list.
    3. Click on “Update” to save.

    Assign Screen call Application

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

    Voice Phone Number Search

    Test and validate

    Call the Plivo phone number assigned to your app. If your phone number is on the blacklist, then your call will be rejected. If your phone number is not blacklisted, then the call will go through and you will be greated with “Hello, how are you today!”.

    Sample XML

    Sample output when From number is in blacklist
    <Response>
        <Hangup reason="rejected"/>
    </Response>
    
    Sample Output when From number is not in blacklist
    <Response>
        <Speak>Hello, how are you today!</Speak>
    </Response>