Reply to an Incoming SMS

When an SMS is sent to an Plivo phone number, you can receive the text on your server by setting a Message URL in your Plivo app. Plivo will send the message along with other parameters to your Message URL. You can reply back using the Plivo Message XML.

Note: In order to reply to a US or Canadian phone number, the 'src' (source) phone number must be a Plivo US or Canadian phone number. You can purchase a Plivo number from the Buy Numbers tab on your Plivo account dashboard.

Prerequisites

  1. Sign up for a free Plivo trial account.
  2. Check out our Helper Libraries page and install the right helper based on the programming language you want to use.
  3. A phone number is required to receive and reply to SMS text messages. You can buy a Plivo phone number in over 19 countries through the Buy Numbers tab on your Plivo account UI. Check the SMS API coverage page for all the supported countries.
  4. Use a web hosting service to host your web application. There are many inexpensive cloud hosting providers that you can use for just a few dollars a month. Follow the instructions of your hosting provider to host your web application.
    Note: If you are using a Plivo Trial account for this example, you can only send sms to phone numbers that have been verified with Plivo. Phone numbers can be verified at the Sandbox Numbers page.

Set up a Web Server

Let’s assume your web server is located at http://example.com. Below is a snippet to set up a route on your webserver. Now when we send an HTTP request to http://example.com/reply_to_sms/ this route will be invoked.

Note: For PHP, the route will be example.com/reply_to_sms.php.

  1. Copy the relevant code below into a text file and save it. Lets call it, 'reply_to_sms'.
  2. Customize the 'body' with your reply.
  3. Next, you will now have to configure this URL in your Plivo application.

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
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 "Received SMS from: {}, to: {}, message: {}".format(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)
 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
require 'rubygems'
require 'plivo'
require 'sinatra'
include Plivo

post '/reply_to_sms/' do
    # Sender's phone number
    from_number = params[:From]
    # Receiver's phone number - Plivo number
    to_number = params[:To]
    # The text which was received
    text = params[:Text]

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

    r = Response.new()
    r.addMessage(body, params)
    # Print the XML
    puts r.to_xml()

    # Return the XML
    content_type 'text/xml'
    return r.to_s()
end
 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
var plivo = require('plivo');
var express = require('express');
var bodyParser = require('body-parser');
var app = express();

app.use(bodyParser.urlencoded({extended: true}));
app.set('port', (process.env.PORT || 5000));
app.all('/reply_to_sms/', function(request, response) {
    // Sender's phone number
    var from_number = request.body.From || request.query.From;
    // Receiver's phone number - Plivo number
    var to_number = request.body.To || request.query.To;
    // The text which was received
    var text = request.body.Text || request.query.Text;

    var params = {
        'src' : to_number, // Sender's phone number
        'dst' : from_number // Receiver's phone Number
    };
    var body = "Thanks, we've received your message.";

    var r = plivo.Response();
    r.addMessage(body, params);
    console.log (r.toXML());

    response.set({'Content-Type': 'text/xml'});
    response.end(r.toXML());
});

app.listen(app.get('port'), function() {
    console.log('Node app is running on port', app.get('port'));
});
 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
<?php
    require 'vendor/autoload.php';
    use Plivo\Response;

    // Sender's phone numer
    $from_number = $_REQUEST["From"];
    // Receiver's phone number - Plivo number
    $to_number = $_REQUEST["To"];
    // The SMS text message which was received
    $text = $_REQUEST["Text"];
    // Output the text which was received, you could
    // also store the text in a database.
    // echo("Message received from $from_number : $text");
    $params = array(
            '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 = new Response();
    $r->addMessage($body, $params);
    Header('Content-type: text/xml');
    echo($r->toXML());
?>
 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
package com.plivo.test;

import java.io.IOException;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import com.plivo.helper.exception.PlivoException;
import com.plivo.helper.xml.elements.Message;
import com.plivo.helper.xml.elements.PlivoResponse;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class replyToSms extends HttpServlet {
    private static final long serialVersionUID = 1L;
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        String from_number = req.getParameter("From");
        String to_number = req.getParameter("To");
        String text = req.getParameter("Text");
        System.out.println("From : " + from_number + " To : " + to_number + " Text : " + text);

        PlivoResponse response = new PlivoResponse();
        Message msg = new Message("Thanks, we've received your message.");
        msg.setSource(to_number);
        msg.setDestination(from_number);
        try {
            response.append(msg);
            System.out.println(response.toXML());
            resp.addHeader("Content-Type", "text/xml");
            resp.getWriter().print(response.toXML());;
        } catch (PlivoException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws Exception {
        String port = System.getenv("PORT");
        if(port==null)
            port ="8080";
        Server server = new Server(Integer.valueOf(port));
        ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
        context.setContextPath("/");
        server.setHandler(context);
        context.addServlet(new ServletHolder(new replyToSms()),"/reply_to_sms/");
        server.start();
        server.join();
    }
}
 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
using System;
using System.Collections.Generic;
using System.Reflection;
using Nancy;
using RestSharp;
using Plivo.API;

namespace Reply_To_Sms
{
    public class Program : NancyModule
    {
        public Program()
        {
            Post["/reply_to_sms/"] = x =>
            {
                String from_number = Request.Form["From"]; // Sender's phone number
                String to_number = Request.Form["To"]; // Receiver's phone number
                String text = Request.Form["Text"]; // The text which was received

                // Print the message
                Console.WriteLine("From : {0}, To : {1}, Text : {2}", from_number, to_number, text);

                Plivo.XML.Response resp = new Plivo.XML.Response();

                // Generate Message XML
                resp.AddMessage("Thanks, we've received your message.", new Dictionary<string, string>() {
                    { "src", to_number }, // Sender's phone number
                    { "dst", from_number } // receiver's phone number
                });

                // Print the XML
                Console.WriteLine(resp.ToString());

                // Return the XML
                var output = resp.ToString();
                var res = (Nancy.Response)output;
                res.ContentType = "text/xml";
                return res;
            };
        }
    }
}

Create an Application

  1. Create an Application by visiting the Application Page and click on 'New Application' or by using Plivo’s Application API.
  2. Give your application a name. Lets call it 'Reply to SMS'. Enter your server URL (e.g., http://example.com/reply_to_sms/) in the 'Message URL' field and set the method as 'POST'. See our Application API docs to learn how to modify your application through our APIs.
  3. Click on 'Create' to save your application.

Create Application

Assign a Plivo number to your app

  1. Navigate to the Numbers page and select the phone number you want to use for this app.
  2. Select 'Reply to SMS' (name of the app) from the Plivo App dropdown list.
  3. Click on 'Update' to save.

Assign Phone Number to Reply to SMS App

If you don’t have a number, head over to Buy Number page to rent a number.

SMS Phone Number Search

Test it out

Send an SMS to your Plivo number. Plivo will request the your Message URL which will generate a Message XML to reply to the received sms.

Sample XML

<Response>
    <Message dst="2222222222" src="1111111111">
        Thanks, we've received your message.
    </Message>
</Response>

Next Step

Learn how to forward an incoming SMS.

  1. Send a Single SMS
  2. Send a Long SMS
  3. Send Multiple (Bulk) SMS
  4. Send an SMS with Alphanumeric Sender ID
  5. Receive an SMS

  6. Forward an Incoming SMS
  7. Get Details of all Messages
  8. Get Details of a Single Message
  9. Handling SMS Delivery Reports
  10. Forward SMS to Email