Conduct SMS Surveys Using Python

Overview

This guide shows how to conduct an SMS survey. Surveys can help businesses with market research. Using SMS for surveys lets organizations process input quickly and efficiently.

You can conduct SMS surveys either by using our PHLO visual workflow builder or our APIs. Follow the instructions in one of the tabs below.

You can create and deploy a PHLO to conduct an SMS survey with a few clicks on the PHLO canvas and trigger it with a few lines of code.

How it works

Prerequisites

To get started, you need a Plivo account — sign up with your work email address if you don’t have one already. If this is your first time triggering a PHLO with Python, follow our instructions to set up a Python development environment.

Create the PHLO

To create a PHLO, visit the PHLO page of the Plivo console. If this is your first PHLO, the PHLO page will be empty.

  • Click Create New PHLO.

  • In the Choose your use case pop-up, click Build my own. The PHLO canvas will appear with the Start node.

    Note: The Start node is the starting point of any PHLO. It lets you trigger a PHLO to start upon one of three actions: incoming SMS message, incoming call, or API request.
  • If you plan to use a dynamic payload — passing values through parameters when you trigger the PHLO from your application — click on the Start node to open the Configuration pane. Under API Request, enter key names for the variables you want use in your payload — From, To, and Message fields.

  • Once you’ve configured the node, click Validate to save the configuration.

  • From the list of components on the left-hand side, drag and drop the Send Message component onto the canvas. When a component is placed on the canvas it becomes a node.

  • Draw a line to connect the Start node’s API Request trigger state to the Send Message node.

  • In the Configuration pane at the right of the canvas, configure the Send Message node with a sender ID in the From field. Enter the destination numbers you wish to send a message to in the To field. Put your message in the Text field.

    Note: You can define a static payload by specifying values when you create the PHLO, or define a dynamic payload by passing values through Liquid templating parameters when you trigger the PHLO from your application.
  • Once you’ve configured the node, click Validate to save the configuration.

  • From the list of components on the left-hand side, drag and drop the Branch component onto the canvas.

  • Draw a line to connect the Start node’s Incoming Message trigger state to the Branch node.

  • In the Configuration pane at the right of the canvas, configure the Branch node. Rename the node to Handle_Reply. For Variable to compare, enter two curly braces to view all available variables, then select Start.message.msg.

  • Click the pencil icon and name the first condition Satisfied. Leave the Operation “is equal to” and enter a value of 1.

  • Add a second condition. Name it Not Satisfied and enter a value of 2.

  • Once you’ve configured the node, click Validate to save the configuration.

  • Drag two Send Message nodes onto the canvas. Draw lines to connect them to the Handle_Reply node using the Satisfied and Not Satisfied trigger states.

  • In the Configuration pane for each of the Send Message nodes, specify the From and To keys you configured in the Start node. Enter two curly brackets to display a list of all available variables. In the Message field, you can enter a static message, or combine static text with a variable that includes dynamic text if you specified the variable as a key in the Start node configuration pane.

  • Rename the nodes Reply_Satisfied and Reply_NotSatisfied.

  • Once you’ve configured the nodes, click Validate to save their configurations.

  • From the list of components on the left-hand side, drag and drop the HTTP Request component onto the canvas. Draw four lines to connect the Sent and Failed trigger states of both the Reply_Satisfied and Reply_NotSatisfied nodes to the HTTP Request node.

  • In the Configuration pane for the HTTP Request node, rename the node to Handle_Callback. Enter URL to make the request to. The default method used is GET, but you can click on the box to choose POST, PUT, or DELETE instead. Specify Headers, Auth, Params, and Body values on their respective tabs as necessary.

  • Once you’ve configured the node, click Validate to save the configuration.

After you complete the configuration, give the PHLO a name by clicking in the upper left, then click Save.

Your complete PHLO should look like this:

SMS Survey

Your PHLO is now ready to test.

Trigger the PHLO

You integrate a PHLO into your application workflow by making an API request to trigger the PHLO with the required payload — the set of parameters you pass to the PHLO. You can define a static payload by specifying values when you create the PHLO, or define a dynamic payload by passing values through parameters when you trigger the PHLO from your application.

In either case, you need your Auth ID and Auth Token, which you can get from the overview page of the Plivo console.

AUTHID

You also need the PHLO ID, which you can copy from the PHLO list page.

PHLO List

With a static payload

When you configure values when creating the PHLO, they act as a static payload.

With Static Payload

Code

Create a file called trigger_phlo.py and paste into it this code.

1
2
3
4
5
6
7
8
9
import plivo

auth_id = '<auth_id>'
auth_token = '<auth_token>'
phlo_id = '<phlo_id>' 
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))

Replace the auth placeholders with your authentication credentials from the Plivo console. Replace the phlo_id placeholder with your PHLO ID from the Plivo console.

With a dynamic payload

To use dynamic values for the parameters, use Liquid templating parameters when you create the PHLO …

With Dynamic Payload

… and pass the values from your code when you trigger it.

With Dynamic Payload

Code

Create a file called trigger_phlo.py and paste into it this code.

1
2
3
4
5
6
7
8
9
10
import plivo

auth_id = '<auth_id>'
auth_token = '<auth_token>'
phlo_id = '<phlo_id>'
payload = {"From" : "<sender_id>","To" : "<destination_number>"}
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))

Replace the auth placeholders with your authentication credentials from the Plivo console. Replace the phlo_id placeholder with your PHLO ID from the Plivo console. Replace the phone number placeholders with actual phone numbers in E.164 format (for example, +12025551234).

Test

Save the file and run it.

python trigger_phlo.py
Note: If you’re using a Plivo Trial account, you can send SMS messages only to phone numbers that have been verified with Plivo. You can verify (sandbox) a number by going to the console’s Phone Numbers > Sandbox Numbers page.

Here’s how to use Plivo APIs to create surveys using SMS text messages — sending questions and collecting answers.

How it works

Outbound-SMS Flow

Prerequisites

To get started, you need a Plivo account — sign up with your work email address if you don’t have one already. To receive incoming messages, you must have a Plivo phone number that supports SMS; you can rent numbers from the Numbers page of the Plivo console or by using the Numbers API. If this is your first time using Plivo APIs, follow our instructions to set up a Python development environment.

Create the survey application

Create a file called survey.py and paste into it this 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
from flask import Flask, request, Response
import plivo
from plivo import plivoxml

app = Flask(__name__)


@app.post("/send_survey/")
def send_survey():
    client = plivo.RestClient("<auth_id>", "<auth_token>")
    response = client.messages.create(
        src="<sender_id>",
        dst="<destination_number>",
        text='Did you find out all the information you needed? Please reply "Yes" or "No"',
    )
    return Response(str(response), mimetype="application/json"), 200


@app.post("/survey_response/")
def survey_response():
    from_number = request.values.get("From")
    to_number = request.values.get("To")
    text = request.values.get("Text")
    print(f"Message received - From: {from_number}, To: {to_number}, Text: {text}")

    if text.lower() == "yes":
        message_body = "Thank you for your feedback"
    elif text.lower() == "no":
        message_body = "We apologize for the inconvenience. A representative will contact you to assist you"
    else:
        message_body = f'Response received was "{text}", which is invalid. Please reply with either "Yes" or "No"'
    
    response = plivoxml.ResponseElement()
    response.add(plivoxml.MessageElement(message_body, src=to_number, dst=from_number))
    return Response(response.to_string(), mimetype="application/xml"), 200


if __name__ == "__main__":
    app.run(host="0.0.0.0", debug=True)

Replace the auth placeholders with your authentication credentials from the Plivo console. Replace the phone number placeholders with actual phone numbers in E.164 format (for example, +12025551234). In countries other than the US and Canada you can use a sender ID for the message source. You must have a Plivo phone number to send messages to the US or Canada; you can buy a Plivo number from Phone Numbers > Buy Numbers on the Plivo console or via the Numbers API.

Note: We recommend that you store your credentials in the auth_id and auth_token environment variables to avoid the possibility of accidentally committing them to source control. If you do this, you can initialize the client with no arguments and Plivo will automatically fetch the values from the environment variables. You can use os module(os.environ) to store environment variables and fetch them when initializing the client.

Test

Save the file and run it.

$ python survey.py
Note: If you’re using a Plivo Trial account, you can send messages only to phone numbers that have been verified with Plivo. You can verify (sandbox) a number by going to the console’s Phone Numbers > Sandbox Numbers page.