Create an SMS Conversation

How do you turn a handful of isolated messages to and from the same party into a true conversation? You need some way to remember state between each message that is exchanged. This guide will show you how Programmable SMS makes this easy for you.

Choose a language and let's get started!

Loading Code Samples...
Language
SDK Version:
  • 4.x
  • 5.x
SDK Version:
  • 6.x
  • 7.x
SDK Version:
  • 2.x
  • 3.x
SDK Version:
  • 5.x
  • 6.x
SDK Version:
  • 4.x
  • 5.x
var http = require('http'),
    express = require('express'),
    session = require('express-session'),
    twilio = require('twilio');

var app = express();
app.use(session({ secret: 'anything-you-want-but-keep-secret' }));

app.post('/sms', function(req, res) {
  var smsCount = req.session.counter || 0;

  var message = 'Hello, thanks for the new message.';
  if(smsCount > 0) {
    message = 'Hello, thanks for message number ' + (smsCount + 1);
  }
  
  req.session.counter = smsCount + 1;

  var twiml = new twilio.TwimlResponse();
  twiml.message(message);
  res.writeHead(200, {'Content-Type': 'text/xml'});
  res.end(twiml.toString());
});

http.createServer(app).listen(1337, function () {
  console.log("Express server listening on port 1337");
});
const http = require('http');
const express = require('express');
const session = require('express-session');
const MessagingResponse = require('twilio').twiml.MessagingResponse;

const app = express();

app.use(session({secret: 'anything-you-want-but-keep-secret'}));

app.post('/sms', (req, res) => {
  const smsCount = req.session.counter || 0;

  const message = 'Hello, thanks for the new message.';

  if(smsCount > 0) {
    message = 'Hello, thanks for message number ' + (smsCount + 1);
  }

  req.session.counter = smsCount + 1;

  const twiml = new MessagingResponse();
  twiml.message(message);

  res.writeHead(200, {'Content-Type': 'text/xml'});
  res.end(twiml.toString());
});

http.createServer(app).listen(1337, () => {
  console.log('Express server listening on port 1337');
});
// In Package Manager, run:
// Install-Package Twilio.Mvc -DependencyVersion HighestMinor

using System.Collections.Generic;
using System.Web.Mvc;
using Twilio.Mvc;
using Twilio.TwiML;
using Twilio.TwiML.Mvc;

public class SmsController : TwilioController
{
    [HttpPost]
    public ActionResult Index(SmsRequest request)
    {
        var counter = 0;

        // get the session varible if it exists    
        if (Session["counter"] != null)
        {
            counter = (int) Session["counter"];
        }

        // increment it
        counter++;

        // save it
        Session["counter"] = counter;

        // make an associative array of senders we know, indexed by phone number
        var people = new Dictionary<string, string>()
        {
            {"+14158675309", "Rey"},
            {"+14158675310", "Finn"},
            {"+14158675311", "Chewy"}
        };

        // if the sender is known, then greet them by name
        var name = "Friend";
        if (people.ContainsKey(request.From))
        {
            name = people[request.From];
        }

        var response = new TwilioResponse();
        response.Message($"{name} has messaged {request.To} {counter} times");
        return TwiML(response);
    }
}
require 'rubygems'
require 'twilio-ruby'
require 'sinatra'

use Rack::Session::Cookie, :key => 'rack.session',
                           :path => '/',
                           :secret => 'can-be-anything-but-keep-a-secret'

post '/sms' do
  session["counter"] ||= 0
  sms_count = session["counter"]
  if sms_count == 0
    message = "Hello, thanks for the new message."
  else
    message = "Hello, thanks for message number #{sms_count + 1}"
  end
  twiml = Twilio::TwiML::Response.new do |r|
    r.Message message
  end
  session["counter"] += 1

  content_type 'text/xml'
  twiml.text
end
// In Package Manager, run:
// Install-Package Twilio.AspNet.Mvc -DependencyVersion HighestMinor

using System.Collections.Generic;
using System.Web.Mvc;
using Twilio.AspNet.Mvc;
using Twilio.TwiML;

public class SmsController : TwilioController
{
    [HttpPost]
    public ActionResult Index()
    {
        var counter = 0;

        // get the session varible if it exists
        if (Session["counter"] != null)
        {
            counter = (int) Session["counter"];
        }

        // increment it
        counter++;

        // save it
        Session["counter"] = counter;

        // make an associative array of senders we know, indexed by phone number
        var people = new Dictionary<string, string>()
        {
            {"+14158675309", "Rey"},
            {"+14158675310", "Finn"},
            {"+14158675311", "Chewy"}
        };

        // if the sender is known, then greet them by name
        var name = "Friend";
        var from = Request.Form["From"];
        var to = Request.Form["To"];
        if (people.ContainsKey(from))
        {
            name = people[from];
        }

        var response = new MessagingResponse();
        response.Message($"{name} has messaged {to} {counter} times");

        return TwiML(response);
    }
}
from flask import Flask, request, session
from twilio import twiml

# The session object makes use of a secret key.
SECRET_KEY = 'a secret key'
app = Flask(__name__)
app.config.from_object(__name__)

# Try adding your own number to this list!
callers = {
    "+14158675309": "Rey",
    "+14158675310": "Finn",
    "+14158675311": "Chewy",
}

@app.route("/", methods=['GET', 'POST'])
def hello():
    """Respond with the number of text messages sent between two parties."""
    # Increment the counter
    counter = session.get('counter', 0)
    counter += 1

    # Save the new counter value in the session
    session['counter'] = counter

    from_number = request.values.get('From')
    if from_number in callers:
        name = callers[from_number]
    else:
        name = "Friend"

    # Build our reply
    message = '{} has messaged {} {} times.' \
        .format(name, request.values.get('To'), counter)

    # Put it in a TwiML response
    resp = twiml.Response()
    resp.message(message)

    return str(resp)

if __name__ == "__main__":
    app.run(debug=True)
require 'rubygems'
require 'twilio-ruby'
require 'sinatra'

use Rack::Session::Cookie, key: 'rack.session',
                           path: '/',
                           secret: 'can-be-anything-but-keep-a-secret'

# Return the session number for each sms received.
post '/sms' do
  session['counter'] ||= 0
  sms_count = session['counter']

  message = if sms_count.zero?
              'Hello, thanks for the new message.'
            else
              "Hello, thanks for message number #{sms_count + 1}"
            end

  twiml = Twilio::TwiML::MessagingResponse.new do |r|
    r.message(body: message)
  end

  session['counter'] += 1

  content_type 'text/xml'

  twiml.to_s
end
package com.twilio;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.io.IOException;
import java.util.HashMap;

import com.twilio.sdk.verbs.TwiMLResponse;
import com.twilio.sdk.verbs.TwiMLException;
import com.twilio.sdk.verbs.Message;

public class TwilioServlet extends HttpServlet {

    public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {

        HttpSession session = request.getSession(true);
        Integer counter = (Integer)session.getAttribute("counter");
        if (counter == null) {
            counter = new Integer(0);
        }

        /* Increment the counter by one, and store the count in the session. */
        int count = counter.intValue();
        count++;
        session.setAttribute("counter", new Integer(count));

        // Create a dict of people we know.
        HashMap<String, String> callers = new HashMap<String, String>();
        callers.put("+14158675309", "Rey");
        callers.put("+14158675310", "Finn");
        callers.put("+14158675311", "Chewy");

        String fromNumber = request.getParameter("From");
        String toNumber = request.getParameter("To");
        String fromName = callers.get(fromNumber);
        if (fromName == null) {
            // Use the caller's name
            fromName = "Friend";
        }

        String message = fromName + " has messaged " + toNumber + 
            " " + String.valueOf(count) + " times.";

        // Create a TwiML response and add our friendly message.
        TwiMLResponse twiml = new TwiMLResponse();
        Message sms = new Message(message);
        try {
            twiml.append(sms);
        } catch (TwiMLException e) {
            e.printStackTrace();
        }

        response.setContentType("application/xml");
        response.getWriter().print(twiml.toXML());
    }
}
from flask import Flask, request, session
from twilio.twiml.messaging_response import MessagingResponse

# The session object makes use of a secret key.
SECRET_KEY = 'a secret key'
app = Flask(__name__)
app.config.from_object(__name__)

# Try adding your own number to this list!
callers = {
    "+14158675309": "Rey",
    "+14158675310": "Finn",
    "+14158675311": "Chewy",
}

@app.route("/", methods=['GET', 'POST'])
def hello():
    """Respond with the number of text messages sent between two parties."""
    # Increment the counter
    counter = session.get('counter', 0)
    counter += 1

    # Save the new counter value in the session
    session['counter'] = counter

    from_number = request.values.get('From')
    if from_number in callers:
        name = callers[from_number]
    else:
        name = "Friend"

    # Build our reply
    message = '{} has messaged {} {} times.' \
        .format(name, request.values.get('To'), counter)

    # Put it in a TwiML response
    resp = MessagingResponse()
    resp.message(message)

    return str(resp)

if __name__ == "__main__":
    app.run(debug=True)
import java.io.IOException;
import java.util.HashMap;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.twilio.twiml.Body;
import com.twilio.twiml.Message;
import com.twilio.twiml.MessagingResponse;
import com.twilio.twiml.TwiMLException;

public class TwilioServlet extends HttpServlet {
  public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
    HttpSession session = request.getSession(true);
    Integer counter = (Integer) session.getAttribute("counter");
    if (counter == null) {
      counter = new Integer(0);
    }

    /* Increment the counter by one, and store the count in the session. */
    int count = counter.intValue();
    count++;
    session.setAttribute("counter", new Integer(count));

    // Create a dict of people we know.
    HashMap<String, String> callers = new HashMap<String, String>();
    callers.put("+14158675309", "Rey");
    callers.put("+14158675310", "Finn");
    callers.put("+14158675311", "Chewy");

    String fromNumber = request.getParameter("From");
    String toNumber = request.getParameter("To");
    String fromName = callers.get(fromNumber);
    if (fromName == null) {
      // Use the caller's name
      fromName = "Friend";
    }

    String message =
        fromName + " has messaged " + toNumber + " " + String.valueOf(count) + " times.";

    // Create a TwiML response and add our friendly message.
    Message sms = new Message.Builder().body(new Body(message)).build();
    MessagingResponse twimlResponse = new MessagingResponse.Builder().message(sms).build();

    response.setContentType("application/xml");

    try {
      response.getWriter().print(twimlResponse.toXml());
    } catch (TwiMLException e) {
      e.printStackTrace();
    }
  }
}
<?php

    // start the session
    session_start();

    // get the session varible if it exists
    $counter = $_SESSION['counter'];

    // if it doesnt, set the default
    if(!strlen($counter)) {
        $counter = 0;
    }

    // increment it
    $counter++;

    // save it
    $_SESSION['counter'] = $counter;

    // make an associative array of senders we know, indexed by phone number
    $people = array(
        "+14158675309"=>"Rey",
        "+14158675310"=>"Finn",
        "+14158675311"=>"Chewy",
    );

    // if the sender is known, then greet them by name
    if(!$name = $people[$_REQUEST['From']]) {
        $name = "Friend";
    }

    // output the counter response
    header("content-type: text/xml");
    echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
?>
<Response>
    <Message><?php echo $name ?> has messaged <?php echo $_REQUEST['To']." ".$counter ?> times</Message>
</Response>
Tracking SMS Conversations using Cookies
Jarod Reyes
David Prothero
Mario Celi

Need some help?

We all do sometimes; code is hard. Get help now from our support team, or lean on the wisdom of the crowd browsing the Twilio tag on Stack Overflow.

1 / 1
Loading Code Samples...
SDK Version:
  • 4.x
  • 5.x
SDK Version:
  • 6.x
  • 7.x
SDK Version:
  • 2.x
  • 3.x
SDK Version:
  • 5.x
  • 6.x
SDK Version:
  • 4.x
  • 5.x
var http = require('http'),
    express = require('express'),
    session = require('express-session'),
    twilio = require('twilio');

var app = express();
app.use(session({ secret: 'anything-you-want-but-keep-secret' }));

app.post('/sms', function(req, res) {
  var smsCount = req.session.counter || 0;

  var message = 'Hello, thanks for the new message.';
  if(smsCount > 0) {
    message = 'Hello, thanks for message number ' + (smsCount + 1);
  }
  
  req.session.counter = smsCount + 1;

  var twiml = new twilio.TwimlResponse();
  twiml.message(message);
  res.writeHead(200, {'Content-Type': 'text/xml'});
  res.end(twiml.toString());
});

http.createServer(app).listen(1337, function () {
  console.log("Express server listening on port 1337");
});
const http = require('http');
const express = require('express');
const session = require('express-session');
const MessagingResponse = require('twilio').twiml.MessagingResponse;

const app = express();

app.use(session({secret: 'anything-you-want-but-keep-secret'}));

app.post('/sms', (req, res) => {
  const smsCount = req.session.counter || 0;

  const message = 'Hello, thanks for the new message.';

  if(smsCount > 0) {
    message = 'Hello, thanks for message number ' + (smsCount + 1);
  }

  req.session.counter = smsCount + 1;

  const twiml = new MessagingResponse();
  twiml.message(message);

  res.writeHead(200, {'Content-Type': 'text/xml'});
  res.end(twiml.toString());
});

http.createServer(app).listen(1337, () => {
  console.log('Express server listening on port 1337');
});
// In Package Manager, run:
// Install-Package Twilio.Mvc -DependencyVersion HighestMinor

using System.Collections.Generic;
using System.Web.Mvc;
using Twilio.Mvc;
using Twilio.TwiML;
using Twilio.TwiML.Mvc;

public class SmsController : TwilioController
{
    [HttpPost]
    public ActionResult Index(SmsRequest request)
    {
        var counter = 0;

        // get the session varible if it exists    
        if (Session["counter"] != null)
        {
            counter = (int) Session["counter"];
        }

        // increment it
        counter++;

        // save it
        Session["counter"] = counter;

        // make an associative array of senders we know, indexed by phone number
        var people = new Dictionary<string, string>()
        {
            {"+14158675309", "Rey"},
            {"+14158675310", "Finn"},
            {"+14158675311", "Chewy"}
        };

        // if the sender is known, then greet them by name
        var name = "Friend";
        if (people.ContainsKey(request.From))
        {
            name = people[request.From];
        }

        var response = new TwilioResponse();
        response.Message($"{name} has messaged {request.To} {counter} times");
        return TwiML(response);
    }
}
require 'rubygems'
require 'twilio-ruby'
require 'sinatra'

use Rack::Session::Cookie, :key => 'rack.session',
                           :path => '/',
                           :secret => 'can-be-anything-but-keep-a-secret'

post '/sms' do
  session["counter"] ||= 0
  sms_count = session["counter"]
  if sms_count == 0
    message = "Hello, thanks for the new message."
  else
    message = "Hello, thanks for message number #{sms_count + 1}"
  end
  twiml = Twilio::TwiML::Response.new do |r|
    r.Message message
  end
  session["counter"] += 1

  content_type 'text/xml'
  twiml.text
end
// In Package Manager, run:
// Install-Package Twilio.AspNet.Mvc -DependencyVersion HighestMinor

using System.Collections.Generic;
using System.Web.Mvc;
using Twilio.AspNet.Mvc;
using Twilio.TwiML;

public class SmsController : TwilioController
{
    [HttpPost]
    public ActionResult Index()
    {
        var counter = 0;

        // get the session varible if it exists
        if (Session["counter"] != null)
        {
            counter = (int) Session["counter"];
        }

        // increment it
        counter++;

        // save it
        Session["counter"] = counter;

        // make an associative array of senders we know, indexed by phone number
        var people = new Dictionary<string, string>()
        {
            {"+14158675309", "Rey"},
            {"+14158675310", "Finn"},
            {"+14158675311", "Chewy"}
        };

        // if the sender is known, then greet them by name
        var name = "Friend";
        var from = Request.Form["From"];
        var to = Request.Form["To"];
        if (people.ContainsKey(from))
        {
            name = people[from];
        }

        var response = new MessagingResponse();
        response.Message($"{name} has messaged {to} {counter} times");

        return TwiML(response);
    }
}
from flask import Flask, request, session
from twilio import twiml

# The session object makes use of a secret key.
SECRET_KEY = 'a secret key'
app = Flask(__name__)
app.config.from_object(__name__)

# Try adding your own number to this list!
callers = {
    "+14158675309": "Rey",
    "+14158675310": "Finn",
    "+14158675311": "Chewy",
}

@app.route("/", methods=['GET', 'POST'])
def hello():
    """Respond with the number of text messages sent between two parties."""
    # Increment the counter
    counter = session.get('counter', 0)
    counter += 1

    # Save the new counter value in the session
    session['counter'] = counter

    from_number = request.values.get('From')
    if from_number in callers:
        name = callers[from_number]
    else:
        name = "Friend"

    # Build our reply
    message = '{} has messaged {} {} times.' \
        .format(name, request.values.get('To'), counter)

    # Put it in a TwiML response
    resp = twiml.Response()
    resp.message(message)

    return str(resp)

if __name__ == "__main__":
    app.run(debug=True)
require 'rubygems'
require 'twilio-ruby'
require 'sinatra'

use Rack::Session::Cookie, key: 'rack.session',
                           path: '/',
                           secret: 'can-be-anything-but-keep-a-secret'

# Return the session number for each sms received.
post '/sms' do
  session['counter'] ||= 0
  sms_count = session['counter']

  message = if sms_count.zero?
              'Hello, thanks for the new message.'
            else
              "Hello, thanks for message number #{sms_count + 1}"
            end

  twiml = Twilio::TwiML::MessagingResponse.new do |r|
    r.message(body: message)
  end

  session['counter'] += 1

  content_type 'text/xml'

  twiml.to_s
end
package com.twilio;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.io.IOException;
import java.util.HashMap;

import com.twilio.sdk.verbs.TwiMLResponse;
import com.twilio.sdk.verbs.TwiMLException;
import com.twilio.sdk.verbs.Message;

public class TwilioServlet extends HttpServlet {

    public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {

        HttpSession session = request.getSession(true);
        Integer counter = (Integer)session.getAttribute("counter");
        if (counter == null) {
            counter = new Integer(0);
        }

        /* Increment the counter by one, and store the count in the session. */
        int count = counter.intValue();
        count++;
        session.setAttribute("counter", new Integer(count));

        // Create a dict of people we know.
        HashMap<String, String> callers = new HashMap<String, String>();
        callers.put("+14158675309", "Rey");
        callers.put("+14158675310", "Finn");
        callers.put("+14158675311", "Chewy");

        String fromNumber = request.getParameter("From");
        String toNumber = request.getParameter("To");
        String fromName = callers.get(fromNumber);
        if (fromName == null) {
            // Use the caller's name
            fromName = "Friend";
        }

        String message = fromName + " has messaged " + toNumber + 
            " " + String.valueOf(count) + " times.";

        // Create a TwiML response and add our friendly message.
        TwiMLResponse twiml = new TwiMLResponse();
        Message sms = new Message(message);
        try {
            twiml.append(sms);
        } catch (TwiMLException e) {
            e.printStackTrace();
        }

        response.setContentType("application/xml");
        response.getWriter().print(twiml.toXML());
    }
}
from flask import Flask, request, session
from twilio.twiml.messaging_response import MessagingResponse

# The session object makes use of a secret key.
SECRET_KEY = 'a secret key'
app = Flask(__name__)
app.config.from_object(__name__)

# Try adding your own number to this list!
callers = {
    "+14158675309": "Rey",
    "+14158675310": "Finn",
    "+14158675311": "Chewy",
}

@app.route("/", methods=['GET', 'POST'])
def hello():
    """Respond with the number of text messages sent between two parties."""
    # Increment the counter
    counter = session.get('counter', 0)
    counter += 1

    # Save the new counter value in the session
    session['counter'] = counter

    from_number = request.values.get('From')
    if from_number in callers:
        name = callers[from_number]
    else:
        name = "Friend"

    # Build our reply
    message = '{} has messaged {} {} times.' \
        .format(name, request.values.get('To'), counter)

    # Put it in a TwiML response
    resp = MessagingResponse()
    resp.message(message)

    return str(resp)

if __name__ == "__main__":
    app.run(debug=True)
import java.io.IOException;
import java.util.HashMap;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.twilio.twiml.Body;
import com.twilio.twiml.Message;
import com.twilio.twiml.MessagingResponse;
import com.twilio.twiml.TwiMLException;

public class TwilioServlet extends HttpServlet {
  public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
    HttpSession session = request.getSession(true);
    Integer counter = (Integer) session.getAttribute("counter");
    if (counter == null) {
      counter = new Integer(0);
    }

    /* Increment the counter by one, and store the count in the session. */
    int count = counter.intValue();
    count++;
    session.setAttribute("counter", new Integer(count));

    // Create a dict of people we know.
    HashMap<String, String> callers = new HashMap<String, String>();
    callers.put("+14158675309", "Rey");
    callers.put("+14158675310", "Finn");
    callers.put("+14158675311", "Chewy");

    String fromNumber = request.getParameter("From");
    String toNumber = request.getParameter("To");
    String fromName = callers.get(fromNumber);
    if (fromName == null) {
      // Use the caller's name
      fromName = "Friend";
    }

    String message =
        fromName + " has messaged " + toNumber + " " + String.valueOf(count) + " times.";

    // Create a TwiML response and add our friendly message.
    Message sms = new Message.Builder().body(new Body(message)).build();
    MessagingResponse twimlResponse = new MessagingResponse.Builder().message(sms).build();

    response.setContentType("application/xml");

    try {
      response.getWriter().print(twimlResponse.toXml());
    } catch (TwiMLException e) {
      e.printStackTrace();
    }
  }
}
<?php

    // start the session
    session_start();

    // get the session varible if it exists
    $counter = $_SESSION['counter'];

    // if it doesnt, set the default
    if(!strlen($counter)) {
        $counter = 0;
    }

    // increment it
    $counter++;

    // save it
    $_SESSION['counter'] = $counter;

    // make an associative array of senders we know, indexed by phone number
    $people = array(
        "+14158675309"=>"Rey",
        "+14158675310"=>"Finn",
        "+14158675311"=>"Chewy",
    );

    // if the sender is known, then greet them by name
    if(!$name = $people[$_REQUEST['From']]) {
        $name = "Friend";
    }

    // output the counter response
    header("content-type: text/xml");
    echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
?>
<Response>
    <Message><?php echo $name ?> has messaged <?php echo $_REQUEST['To']." ".$counter ?> times</Message>
</Response>