Get Started with Voice Survey using Python

    Overview

    We use voice surveys for collecting information from customers, like satisfaction scores of a service provided. Plivo allows you to create and configure a voice survey system for your business. You can set up a PHLO app or an API/XML app with multi-level survey questions based on the key pressed. You can also configure and receive the responses on your app server for consolidation.

    Start your Voice Survey implementation with Plivo using PHLO or the traditional API/XML way. PHLO allows you to create and deploy the call flows using its intuitive canvas in few clicks. Refer to the instructions from the respective tabs below to start your integration with PHLO or XML as you wish.

    To implement Voice Broadcasting use-case, you can create and deploy a PHLO with a few clicks on the PHLO canvas. PHLO also lets you visually construct your entire use-case. With PHLO, you only pay for calls you make/receive, and building with PHLO is free. You can refer to the below instructions in the Using PHLO tab to begin your implementation.

    Outline

    Broadcasting- Call Flow

    Implementation

    In this section, we will guide you to create a PHLO to implement Voice Broadcasting use-case.

    Prerequisites

    1. Create a Plivo Account(if you don’t have one already): You can sign up with your work email address and complete the phone verification step using your mobile number.
    2. Set up your Dotnet dev environment: To set up your dev environment in your .NET(C#) programming language, please refer to the instructions available in the Set up Your Dotnet Dev Environment section.
    3. Buy a Plivo number(optional): You must have a voice-enabled Plivo phone number if you are willing to receive incoming calls. You can purchase numbers from the Numbers section of your Plivo Console. It is also possible to purchase numbers using the Numbers API.

    Create the PHLO

    You can create a PHLO by referring to the below instructions to implement Voice Broadcasting use-case:

    Create a PHLO for Voice Broadcasting

    • On the side navigation bar, click PHLO. The PHLO page will appear and display your existing PHLOs, if any. If this is your first PHLO, then the PHLO page will be empty.
    • Click Create New PHLO to build a new PHLO.
    • On the Choose your use-case window, click Build my own. The PHLO canvas will appear with the Start node.
      Note: The Start node is the starting point of any PHLO. You can choose between the four available trigger states of the Start node; Incoming SMS, Incoming Call, and API Request. For this PHLO, we will use the API Request trigger state.
    • From the list of components, on the left hand side, drag and drop the Initiate Call component onto the canvas. This will add a Initial Call node onto the canvas.
    • Connect the Start node with the Initiate Call node, using the API Request trigger state.
    • Configure the Initiate Call node with the caller ID using the From field. Enter all the numbers you wish to call in the To field.
    • Once you have configured a node, click Validate to save the configurations.
    • Similarly, create a node for the Play Audio component and connect it to the Initiate Call node using the Answered trigger state.
    • Next, configure the Play Audio node to play a specific message to the user. For example, in this case, “Congratulations! You are offered a promotion and press 1 now to take advantage of this offer before it expires.”.
    • Connect the Initiate Call node with the Play Audio node, using the Answered trigger state.
    • After you complete the configurations, provide a friendly name for your PHLO and click Save. Your PHLO is now ready. You can trigger the PHLO and test it out. For more information, refer to the below section.

    Set up Your Python Dev Environment

    You must set up and install Python and Plivo’s Python SDK to implement Voice Broadcasting use-case. Here’s how.

    Install Python

    Operating SystemInstructions
    OS X & LinuxYou would already have Python installed, you can check this by running the command python --version in the terminal
    WindowsTo install Python on Windows you can follow the instructions from here.

    Install Plivo Python Package

    • Create a project directory, run the following command:

      $ mkdir mypythonapp
      
    • Change the directory to our project directory in the command line:

      $ cd mypythonapp
      
    • Install the SDK using pip

      pip install plivo
      
    • Alternatively, you can download the source code from this repo and run

      python setup.py install
      

    We recommend that you use virtualenv to manage and segregate your Python environments, instead of using sudo with your commands and overwriting dependencies.

    Trigger the PHLO

    Once you have created and setup your Python dev envrironment, you can go to your Plivo Consolse and copy the PHLO_ID. You can integrate a PHLO into your application workflow by making an API request to trigger the PHLO with the required payload.

    With Static Payload

    You can choose to either configure the mandatory params required for a PHLO while creating the PHLO itself or, you can pass the params as payload while triggering the PHLO from your app.

    Note: When you configure the params while creating the PHLO, the values are hardcoded, and they act as static payload.

    With Static Payload

    Code

    Now, create a file called trigger_phlo.py and paste the below code.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    
    import plivo
    
    auth_id = 'Your AUTH ID'
    auth_token = 'Your AUTH Token'
    phlo_id = 'Your PHLO ID' # https://console.plivo.com/phlo/list/
    phlo_client = plivo.phlo.RestClient(auth_id=auth_id, auth_token=auth_token)
    phlo = phlo_client.phlo.get(phlo_id)
    response = phlo.run()
    print str(response)
    

    With Dynamic Payload

    To use dynamic values for the parameters, you can use the liquid templating params while creating the PHLO and pass the values while triggering the PHLO.

    With Dynamic Payload

    Code

    Now, create a file called trigger_phlo.py and paste the below code.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    
    import plivo
    
    auth_id = 'Your AUTH ID'
    auth_token = 'Your AUTH Token'
    phlo_id = 'Your PHLO ID' # https://console.plivo.com/phlo/list/
    payload = {"from": "+14156667777", "dest1":   "+14157778888", "dest2":   "+14157778889", "dest3":   "+14157778890", "dest4":   "+14157778891", "dest5":   "+14157778892"}
    phlo_client = plivo.phlo.RestClient(auth_id=auth_id, auth_token=auth_token)
    phlo = phlo_client.phlo.get(phlo_id)
    response = phlo.run(**payload)
    print str(response)
    

    You can get your Auth_ID and Auth_token from your dashboard AUTHID

    You can find the PHLO_ID on the PHLO Listing page. PHLO Listing

    Test and Validate

    You can save the file and use the below command to run your code.

    $ python trigger_phlo.py
    
    Note: If you are using a Plivo Trial account for this example, you can only make calls to phone numbers that have been verified with Plivo. Phone numbers can be verified at the Sandbox Numbers page.

    To implement Voice Survey use-case in the traditional API/XML way, you can refer to the instructions in the below section to begin your implementation.

    Outline

    Outbound- Call Flow

    Implementation

    In this section, we will guide you in setting up an app using Plivo’s API/XML to implement Voice Survey use-case. First, let’s make sure you meet these prerequisites before we dive into the code.

    Prequisites

    1. Create a Plivo Account(if you don’t have one already): You can sign up with your work email address and complete the phone verification step using your mobile number.
    2. Set up your dev environment: To set up your dev environment in your preferred programming language, please refer to the instructions available in the Setting up the Dev Environment Guides.
    3. Buy a Plivo number(optional): You must have a voice-enabled Plivo phone number if you are willing to receive incoming calls. You can purchase numbers from the Numbers section of your Plivo Console. It is also possible to purchase numbers using the Numbers API.

    Prerequisites

    This section will guide you through how to use Plivo APIs to make voice calls from your application. First, let’s make sure you meet these prerequisites before we dive into the code.

    • Plivo Auth Id and Auth Token: You will find your Plivo Auth Id and Auth Token on the home screen of your Plivo Console. Click here to sign-up for a Plivo account if you haven’t already!

      Find Your Auth Credentials on Plivo Console

    • Plivo Phone Number(Optional): You can purchase numbers from the Numbers section of your Plivo Console and use the same as the caller ID for the outbound call. This number will also help you receive incoming calls as you must have a voice-enabled Plivo phone number to do the same. Please note that you can also purchase numbers using the Numbers API.

      Buy a New Plivo Number

    • Answer Url: When a call is answered by the destination_number, you can control the call flow with the help of the answer_url set in the API request. Plivo will invoke the answer_url specified as soon as the call is answered and expect a valid XML response with instructions to handle the call. In addition to requests to the answer URL, Plivo initiates HTTP requests to your application server through the course of a call based on the specific XML elements in your answer XML. Such requests can be broadly classified into two categories:

      Action URL requests: XML instructions to carry forward the call are expected in response to these requests. These requests are typically invoked at the end of an XML element’s execution. For example: when an IVR input is received from the caller during a GetInput XML execution.

      Callback URL requests: No XML instructions are expected in response to these requests. Such requests serve as webhooks to notify your application server of important events through the course of an XML element’s execution. For example: when a conference participant is muted or unmuted.

    Set up Your Python Dev Environment

    You must set up and install Python and Plivo’s Python SDK implement Voice Survey use-case. Here’s how.

    Install Python

    Operating SystemInstructions
    OS X & LinuxYou would already have Python installed, you can check this by running the command python --version in the terminal
    WindowsTo install Python on Windows you can follow the instructions from here.

    Install Plivo Python Package

    • Create a project directory, run the following command:

      $ mkdir mypythonapp
      
    • Change the directory to our project directory in the command line:

      $ cd mypythonapp
      
    • Install the SDK using pip

      pip install plivo
      
    • Alternatively, you can download the source code from this repo and run

      python setup.py install
      

    We recommend that you use virtualenv to manage and segregate your Python environments, instead of using sudo with your commands and overwriting dependencies.

    Create the Outbound Call App

    Once you have the above prerequisites set, You can follow the below instructions to create an app to implement Voice Survey use-case and redirect the call to an Automated Voice Survey IVR using a GetInput XML once the call recipients answer the call.

    Now, create a file called broadcast.py and paste the below code.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    
    import plivo
    
    client = plivo.RestClient()
    response = client.calls.create(
        from='+14151234567',
        to='+14157654321<+14157654321',
        answer_url='https://s3.amazonaws.com/static.plivo.com/broadcast.xml',
        answer_method='GET', )
    print(response)
    
    Note:
    • Replace the placeholders auth_id & auth_token with your credentials from Plivo Console.
    • We recommend that you store your credentials in the auth_id & auth_token environment variables, so as to avoid the possibility of accidentally committing them to source control. If you do this, you can initialize the client with no arguments and it will automatically fetch them from the environment variables
    • You can use os module(os.environ) to store environment variables and fetch them while initializing the client.
    • Replace the placeholder +14151234567 with the Phone number which you have purchased, +14157654321 and +14157654322 with the phone number you will be making calls to.
    • Both +14151234567, +14157654321 and +14157654322 should be in E.164 format

    Create a Flask App to Implement Phone System IVR

    Use the following code snippet to start a local server.

    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
    
    # -*- coding: utf-8 -*-
    from flask import Flask, Response, request, url_for
    from plivo import plivoxml
    
    # This is the message that Plivo reads when the call recipient answers the call.
    question1 = "Hi, this is a call from Plivo, How would you rate your overall satisfaction with our services? Press 1 if you are satisfied or Press 2 if you would like to suggest any improvements."
    question2 = "How would you rate your satisfaction with our customer service. Press 1 for English. Press 1 if you are satisfied or Press 2 if you would like to suggest any improvements. Thanks!"
    # This is the message that Plivo reads when the recipient provides negative feedback
    negative_feedback = "We are sorry about your bad experience, One of our representatives will get in touch with you shortly."
    # This is the message that Plivo reads when the caller does nothing at all
    noinput_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.
    wronginput_message = "Sorry, it's wrong input."
    
    app = Flask(__name__)
    
    @app.route('/survey/', methods=['GET','POST'])
    def ivr():
        response = plivoxml.ResponseElement()
        getinput_action_url = "http://www.foo.com/firstbranch/"
        response.add(plivoxml.GetInputElement().
            set_action(getinput_action_url).
            set_method('POST').
            set_input_type('dtmf').
            set_digit_end_timeout(5).
            set_redirect(True).add(
                plivoxml.SpeakElement(question1)))
        response.add(plivoxml.SpeakElement(noinput_message))
        return Response(response.to_string(), mimetype='application/xml')
    
    @app.route('/survey/firstbranch/', methods=['GET','POST'])
    def firstbranch():
        response = plivoxml.ResponseElement()
        digit = request.values.get('Digits')
        if digit == "1":
            # Read out a text.
            getinput_action_url = "http://www.foo.com/secondbranch/"
            response.add(plivoxml.GetInputElement().
                set_action(getinput_action_url).
                set_method('POST').
                set_input_type('dtmf').
                set_digit_end_timeout(5).
                set_redirect(True).add(
                    plivoxml.SpeakElement(question2)))
            response.add(plivoxml.SpeakElement(noinput_message))
    
        elif digit == "2":
            response.add_speak(negative_feedback)
    
        else:
            response.add_speak(wronginput_message)
        return Response(response.to_string(), mimetype='application/xml')
    
    @app.route('/ivr/secondbranch/', methods=['GET','POST'])
    def secondbranch():
        response = plivoxml.ResponseElement()
        digit = request.values.get('Digits')
    
        if digit == "1":
            text = u"Thank you for participating in the survey!"
            params = {
                'language': "en-GB",
            }
            response.add_speak(text,**params)
    
        elif digit == "2":
            response.add_speak(negative_feedback)
    
        else:
            response.add_speak(wronginput_message)
        return Response(response.to_string(), mimetype='application/xml')
    
    if __name__ == '__main__':
        app.run(host='0.0.0.0', debug=True)
    

    Save this code in any file (name the file something like survey.py). To run this file on the server, go to the folder where this file resides and use the following command:

    $ python survey.py
    

    And you should see your basic server app in action on http://localhost:5000/survey/

    Exposing your local server to the internet

    To receive Incoming Calls and to handle callbacks, your local server should be able to connect with Plivo API service, Ngrok is a tunneling software used to expose a web server running on your local machine to the internet. Using Ngrok you can set webhooks which can talk to Plivo server.

    ngrok block diagram

    You can download and install ngrok from here. Follow the detailed configuration instructions to get started.

    Run ngrok on the port which currently hosts your application. For example, if your port number is 8000, run the following command:

    ./ngrok http 8000
    

    This will give you a UI with links that look like ngrok.io/* which you can use to access your local server using the public network.

    Ngrok CLI

    You can check the app in action on https://6ea358b0f703.ngrok.io/survey/.

    Test and Validate

    Once you have created the Outbound Call App, save the file and use the below command to run your code.

    $ python broadcast.py
    
    Note: If you are using a Plivo Trial account for this example, you can only make calls to phone numbers that have been verified with Plivo. Phone numbers can be verified at the Sandbox Numbers page.

    Common Use Cases for Voice Alerts

    You can also use this implementation for other use cases, like:

    • Automated Surveys and Feedback
    • Customer Satisfaction Survey