My FeedDiscussionsHeadless CMS
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more
How to Receive and Respond to Incoming SMS Messages in Python with Flask and Plivo

How to Receive and Respond to Incoming SMS Messages in Python with Flask and Plivo

Nixon Samuel's photo
Nixon Samuel
·Jun 16, 2021·

4 min read

Sending an outbound message using the Plivo SMS platform is easy, but communication should be a two-way street. Customers should be able to text you, and you should acknowledge their messages and address their concerns. To do this, you can build a Python Flask application to receive and respond to incoming SMS messages on a Plivo phone number. In this post, we walk you through how to implement this.

Prerequisites

Before you get started, you’ll need:

  • A Plivo account — sign up for one for free if you don’t have one already.
  • An SMS-enabled Plivo phone number as you want to receive incoming SMS messages. To search for and buy an available number, go to Phone Numbers > Buy Numbers on the Plivo console.
  • Flask and Plivo Python packages — run pip3 install plivo flask to install them.
  • ngrok — a utility that exposes your local development server to the internet over secure tunnels.

Create a Flask application to receive SMS messages

Once you’ve installed Flask and the Plivo Python SDK, create a simple Flask application to handle incoming SMS messages on a Plivo number. Use this code:

from flask import Flask, request

app = Flask(__name__)

@app.route('/receive_sms/', methods=['GET', 'POST'])
def inbound_sms():

    from_number = request.values.get('From')
    to_number = request.values.get('To')
    text = request.values.get('Text')
    print('Message received - From: %s, To: %s, Text: %s' %(from_number, to_number, text))

    return 'Message Received'

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

Return a Message XML document to reply to incoming messages

To reply to an incoming SMS message, you need to return an XML document from the URL configured as the message_url in the application assigned to the Plivo number. The Python SDK can manage the XML document generation, and you can use the Message XML element to reply to incoming SMS messages. Use this code:

from flask import Flask, request, make_response, Response
from plivo import plivoxml

app = Flask(__name__)

@app.route('/reply_sms/', methods=['GET', 'POST'])
def reply_sms():

    from_number = request.values.get('From')
    to_number = request.values.get('To')
    text = request.values.get('Text')
    print('Message received - From: %s, To: %s, Text: %s' %(from_number, to_number, text))

    response = plivoxml.ResponseElement()
    response.add(
        plivoxml.MessageElement(
            "Thank you, we have received your request.",
            src=to_number,  
            dst=from_number))
    print(response.to_string())  # Prints the XML
    # Returns the XML
    return Response(response.to_string(), mimetype='application/xml')

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

Test the code locally

Save the code in any file — we named the file reply_sms.py. To run the code on the server, go to the folder where the file resides and use the command

$ python reply_sms.py

You should see your basic server application in action on localhost:5000/reply_sms.

Expose the local server to the internet using ngrok

Once you see the application working locally, the next step is to connect the application to the internet to receive and reply to messages. For that, we recommend using ngrok, which exposes local servers behind NATs and firewalls to the public internet over secure tunnels. Install it and run ngrok on the command line, specifying the port that hosts the application on which you want to receive messages (5000 in this case, as our local Python application is running there):

$ ./ngrok http 5000

Ngrok will display a forwarding link that you can use as a webhook to access your local server over the public network.

Ngrok CLI

Test the link by opening the ngrok URL(31123bc8f94e.ngrok.io/reply_sms/?From=14156..) in a browser. We used HTTPie to check the XML response from the ngrok URL.

XML document with Message XML element

Connect the Flask application to a Plivo number

The final step is to configure the app as a Plivo messaging application and assign it to a Plivo number on which you want to receive SMS messages.

Go to the Plivo console and navigate to Messaging > Applications > XML, then click on the Add New Application button in the upper right.

Provide a friendly name for the app — we used “App-Incoming-SMS” — and configure the ngrok URL 31123bc8f94e.ngrok.io/reply_sms as the Message URL. Select the HTTP verb as POST, then click Create Application.

Create Plivo App to handle incoming SMS messages

Now go to Phone Numbers > Your Numbers and click on the number to which you want to assign the application. From the Plivo Application drop-down choose the message application you just created. Finally, click Update Number.

Assign the Plivo App to a Plivo Number

Test the application

Send an SMS to the Plivo number you selected. You should see that the Flask application automatically sends a reply back to your mobile number.

And that’s how simple it is to receive and respond to incoming SMS messages using Plivo’s Python SDK and a Flask application.