Get Started with Voice Surveys Using Go

    Overview

    Plivo lets you automate voice surveys for use cases such as collecting feedback from customers and conducting polling on political issues. You can set up multiple levels of questions and walk users through different paths depending on the keys they press in response to your questions, and save the responses for analysis.

    You can implement voice surveys either by using our PHLO visual workflow builder or our APIs and XML documents. Follow the instructions in one of the tabs below.

    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 Go Dev Environment

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

    Install Go

    You can install Go from the Official Installer.

    Install Plivo Go Package

    • Create a project directory, run the following command:

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

      $ cd mygoapp
      
    • You can install the Plivo Go package using the go command.

      $ go get github.com/plivo/plivo-go
      
    • You can also install by cloning this repository into your GOPATH.

    Trigger the PHLO

    Once you have created and configured your PHLO, copy the PHLO_ID from here. 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

    Once you have created and setup your Go 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.

    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 TriggerPhlo.go and paste the following 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
    
    package main
    
    import (
    	"fmt"
    	"plivo-go"
    )
    // Initialize the following params with corresponding values to trigger resources
    const authId = "auth_id"
    const authToken = "auth_token"
    const phloId = "phlo_id"
    
    func main() {
    	testPhloRunWithoutParams()
    }
    
    func testPhloRunWithoutParams() {
    	phloClient, err := plivo.NewPhloClient(authId, authToken, &plivo.ClientOptions{})
    	if err != nil {
    		panic(err)
    	}
    	phloGet, err := phloClient.Phlos.Get(phloId)
    	if err != nil {
    		panic(err)
    	}
    	response, err := phloGet.Run(nil)
    	if err != nil {
    		panic(err)
    	}
    	fmt.Printf("Response: %#v\n", 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 TriggerPhlo.go and paste the following 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
    
    package main
    
    import (
    	"fmt"
    	"plivo-go"
    )
    // Initialize the following params with corresponding values to trigger resources
    const authId = "auth_id"
    const authToken = "auth_token"
    const phloId = "phlo_id"
    
    func main() {
    	testPhloRunWithParams()
    }
    
    func testPhloRunWithParams() {
    	phloClient, err := plivo.NewPhloClient(authId, authToken, &plivo.ClientOptions{})
    	if err != nil {
    		panic(err)
    	}
    	phloGet, err := phloClient.Phlos.Get(phloId)
    	if err != nil {
    		panic(err)
    	}
    	//pass corresponding from and to values
    	type params map[string]interface{}
    	response, err := phloGet.Run(params{
    		"from": "+14156667777",
    		"dest1":   "+14157778888",
    		"dest2":   "+14157778889",
    		"dest3":   "+14157778890",
    		"dest4":   "+14157778891",
    		"dest5":   "+14157778892"
    	})
    
    	if err != nil {
    		println(err)
    	}
    	fmt.Printf("Response: %#v\n", 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 it.

    go run TriggerPhlo.go
    
    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 Go Dev Environment

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

    Install Go

    You can install Go from the Official Installer.

    Install Plivo Go Package

    • Create a project directory, run the following command:

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

      $ cd mygoapp
      
    • You can install the Plivo Go package using the go command.

      $ go get github.com/plivo/plivo-go
      
    • You can also install by cloning this repository into your GOPATH.

    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.go and paste the following code:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    
    package main
    
    import "fmt"
    import "github.com/plivo/plivo-go"
    
    func main() {
    	client, err := plivo.NewClient("<auth_id>","<auth_token>", &plivo.ClientOptions{})
    	if err != nil {
    		panic(err)
    	}
    	response, err := client.Calls.Create(
    		plivo.CallCreateParams{
    			From: "Caller_ID",
    			To: "Destination_Number1<Destination_Number2",
    			AnswerURL: "https://s3.amazonaws.com/static.plivo.com/broadcast.xml",
    			AnswerMethod: "GET",
    		},
    	)
    	if err != nil {
    		panic(err)
    	}
    	fmt.Printf("Response: %#v\n", 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.Setenv & os.Getenv function to store environment variables and fetch them while initializing the client.
    • Replace the placeholder Caller_ID with the Phone number which you have purchased and Destination_Number with the phone number you will be making call to
    • Both Caller_ID, Destination_Number1 and Destination_Number2 should be in E.164 format
    • Destination_Number1 and Destination_Number2 can also be a SIP endpoint. In case you are calling a SIP endpoint, the Destination_Number placeholder should be a valid SIP URI. Example: sip:john1234@phone.plivo.com

    Create a Go Server 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
    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
    
    package main
    
    import (
    	"github.com/go-martini/martini"
    	"github.com/plivo/plivo-go/xml"
    	"net/http"
    )
    
    func main() {
    	m := martini.Classic()
    	const
    	(
    	// 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
      NegativeFeedback = "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
      NoinputMessage = "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.
      WronginputMessage = "Sorry, it's a wrong input."
    	)
    
    	m.Post("/survey/", func(w http.ResponseWriter, r *http.Request) string {
    		w.Header().Set("Content-Type", "application/xml")
    		response := xml.ResponseElement{
    			Contents: []interface{}{
    				new(xml.GetInputElement).
    				SetAction("https://www.foo.com/ivr/firstbranch/").
    				SetMethod("POST").
    				SetDigitEndTimeout(5).
    				SetInputType("dtmf").
    				SetRedirect(true).
    				SetContents([]interface{}{new(xml.SpeakElement).
    					AddSpeak(Question1),
    					}),
    				new(xml.SpeakElement).
    					AddSpeak(NoInputMessage),
    			},
    		}
    		return response.String()
    	})
    
    	m.Post("/survey/firstbranch/", func(w http.ResponseWriter, r *http.Request) string {
    	w.Header().Set("Content-Type", "application/xml")
    	digit := r.FormValue("Digits")
    	if digit == "1" {
    		return xml.ResponseElement{
    			Contents: []interface{}{
    				new(xml.GetInputElement).
    				SetAction("https://www.foo.com/ivr/firstbranch/").
    				SetMethod("POST").
    				SetDigitEndTimeout(5).
    				SetInputType("dtmf").
    				SetRedirect(true).
    				SetContents([]interface{}{new(xml.SpeakElement).
    					AddSpeak(Question2),
    					}),
    				new(xml.SpeakElement).
    					AddSpeak(NoInputMessage),
    			},
    		}.String()
    	} else if digit == "2" {
    		return xml.ResponseElement{
    			Contents: []interface{}{
    				new(xml.SpeakElement).
    					AddSpeak(NegativeFeedback),
    			},
    		}.String()
    	} else {
    		return xml.ResponseElement{
    			Contents: []interface{}{
    				new(xml.SpeakElement).
    					AddSpeak(WrongInputMessage),
    				},
    			}.String()
    		}
    	})
    
    	m.Post("/survey/secondbranch/", func(w http.ResponseWriter, r *http.Request) string {
    		w.Header().Set("Content-Type", "application/xml")
    		digit := r.FormValue("Digits")
    		if digit == "1" {
    			return xml.ResponseElement{
    				Contents: []interface{}{
    					new(xml.SpeakElement).
    						SetLanguage("en-GB").
    						AddSpeak("Thank you for participating in the survey!"),
    					},
    				}.String()
    		} else if digit == "2" {
    		return xml.ResponseElement{
    			Contents: []interface{}{
    				new(xml.SpeakElement).
    					AddSpeak(NegativeFeedback),
    				},
    			}.String()
    		} else {
    			return xml.ResponseElement{
    				Contents: []interface{}{
    					new(xml.SpeakElement).
    						AddSpeak(WrongInputMessage),
    					},
    			}.String()
    		}
    		})
    	m.Run()
    }
    

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

    $ go run survey.go
    

    And you should see your basic server app in action on http://localhost:8080/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 80, run the following command:

    ./ngrok http <port_on_which_your_local_server_is_running>
    

    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.

    Sample ngrok CLI

    Test and Validate

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

    go run Broadcast.go
    
    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.