<

Receiving and replying to incoming SMS messages

When an SMS is received on your Plivo phone number, Plivo can forward the message text and other details to your application server.

Once you’ve received the message on your application server, you could trigger workflows in your application, reply to incoming message or forward the message to another phone number.

In this guide, we’ll learn to implement all of the above.

Receiving Incoming SMS Messages

Plivo forwards incoming SMS messages to your server using webhooks. A webhook is essentially an HTTP request endpoint which is invoked every time a specific event occurs. In this case, that event is ‘an incoming SMS message on your Plivo number’.

When a message arrives on your Plivo number, Plivo looks up if the number is associated with a Plivo application, and whether a Message URL (the webhook endpoint) has been configured for the application. The message details are then forwarded to this Message URL.

Here are the steps you need to follow to start receiving incoming messages.

Setting Up A Web Server

You must have a live web server to receive incoming messages.

Let’s assume your web server is located at http://example.com.

Create a new service endpoint exclusively to receive incoming messages from Plivo. For example: /receive-sms-messages.

The sample code below is for a service endpoint that accepts the incoming request from Plivo, parses the message body, and prints the from number, to number and the message text.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import plivo
import plivoxml
from flask import Flask, request

app = Flask(__name__)


@app.route("/receive_sms/", methods=['GET', 'POST'])
def receive_sms():
    # Sender's phone numer
    from_number = request.values.get('From')
    # Receiver's phone number - Plivo number
    to_number = request.values.get('To')
    # The text which was received
    text = request.values.get('Text')

    # Print the message
    print 'Message received - From: %s, To: %s, Text: %s' % (from_number, to_number, text)

    return "Message received", 200

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=80)

Creating A Plivo Application

Now that we have our service endpoint up and running, it’s time to set up Plivo to forward incoming messages to this endpoint. This is where Plivo Applications come into the picture.

Plivo Applications help to you logically group your Plivo numbers, and configure distinct Voice/SMS related webhooks for these logical sets of numbers.

Let’s start by navigating to the Applications section of your Plivo Management Console. We shall then create a new Application by clicking on the ‘New Application’ button.

We shall call our Application - ‘Supreme SMS Receiver’ :)

For our use case of forwarding incoming messages to an external application server, we are specifically interested in the Message URL and Message Method properties of an application.

  • The ‘Message URL’ is the service endpoint to be invoked. We shall set this to the web service endpoint we created in the previous step.
  • The ‘Message Method’ is the HTTP method to be invoked on the given ‘Message URL’. The default is ‘POST’, while ‘GET’ is also supported.

Tip: If your webservice is running on your local machine, and not accessible over the internet, we suggest using ngrok to configure an HTTP tunnel from an external endpoint to your local service. Learn more about ngrok here.

Applications can be created, updated, and deleted using the Applications API as well. Click here to read more about Plivo Applications.

Associating Numbers With Plivo Application

We’re almost there! The last step is to associate your Plivo numbers with the Supreme SMS Receiver application we just created.

You can do this by navigating to the Number section of your Plivo dashboard. Once there, click on the Plivo number you wish to assign to this application.

Select ‘Supreme SMS Receiver’ from the applications dropdown and click on ‘Update’.

Test It Out

That’s it, we’re now ready to test our integration out!

Send an SMS to your Plivo number using a regular mobile phone. Plivo will send a request to your Message URL with the parameters listed in the API documentation here.

Replying To / Forwarding Incoming SMS Messages

Now that we’re receiving all incoming messages on our web service, we can trigger our own customized workflows based on the message content, from number, destination number etc.

It is possible to reply to an incoming message, or forward it to another phone number using Plivo XML.

This is essentially done by responding to the incoming HTTP request with a Plivo XML with the <Message> tag.

Let’s build on the application web-server code we wrote earlier by incorporating this workflow.

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
from flask import Flask, request, Response
import plivo, plivoxml

app = Flask(__name__)

@app.route('/reply_to_sms/',methods=['GET','POST'])
def inbound_sms():
    # Sender's phone number
    from_number = request.values.get('From')
    # Receiver's phone number - Plivo number
    to_number = request.values.get('To')
    # The text which was received
    text = request.values.get('Text')

    print 'Message received - From: %s, To: %s, Text: %s' % (from_number, to_number, text)

    params = {
      "src": to_number,
      "dst": from_number,
    }
    body = "Thanks, we've received your message."

    # Generate a Message XML with the details of
    # the reply to be sent.
    r = plivoxml.Response()
    r.addMessage(body, **params)
    print r.to_xml()
    return Response(str(r),mimetype='text/xml')

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=80)

As we can see, we could reply to the SMS sender by simply setting the from number received in the request as the dst number in the Message XML we return.

To forward the message to another number, we would simply set it as dst number in the Message XML.

The features we discussed above can be used to build powerful applications like ‘Number Masking’, where conversations between entities are anonymized by a mediator in the middle. Ride hailing apps do this to protect the identities of drivers and passengers.