Create an SMS Conversation in Python

Today we're going to answer a fun question: how do you turn a handful of isolated text messages to and from the same party into a true conversation?

The problem here? SMS is a stateless protocol.  You're going to need some way to remember state between each exchanged message.

Luckily for us, building traditional web applications has this same hurdle, as HTTP is also a stateless protocol. This problem has been solved for web applications through the use of HTTP cookies and, rather than reinvent that old wheel, the Twilio Messaging API uses the same solution.

This guide will show you how Programmable SMS makes this easy. We'll use Python, the Flask framework, and the Twilio Python SDK.

If you haven't written your own SMS webhooks with Python before, you may want to first check out our guide, Receive and Reply to SMS and MMS Messages in Python.

Ready to go? Let's get started!

 

Using HTTP Cookies with Webhooks

Just like in web applications, a cookie is a small file that your application can store on Twilio's servers to keep track of information, such as a username or account.

For Twilio Programmable SMS, cookies are scoped to the "conversation" between two parties — you can have a unique cookie for each To/From phone number pair. For example, you can store a unique cookie for any messages sent between 415-555-2222 and 415-555-1111, which will be different than the cookie used between 415-555-3333 and 415-555-1111.

In a web app, you write a cookie to keep "statefulness" between separate requests from the same browser.

Similarly, SMS messages are independent communications between two parties, so Twilio allows you to tie them together as a logical session via cookies. This means you can use server-side sessions to keep track of application state between requests. (How cool is that?)

Twilio will expire the cookies for that conversation after four hours of inactivity, as if the user "closed the browser."

Storing Conversation Data

The cookies let you share state across multiple messages allowing you to treat separate messages as a conversation, and store data about the conversation in the cookies for future reference.

You can store the data directly in a cookie, or you can use a session state management framework. We'll use Flask's built-in session library for this example.

Track SMS Conversations Using a Session

Now let's try using session counters to see if a particular user has messaged us before. If they're a new sender, we'll thank them for the new message. If they've sent us messages before, we'll specify how many messages we've gotten from them.

Loading Code Samples...
Language
SDK Version:
  • 5.x
  • 6.x
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)
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)
Tracking SMS Conversations using Cookies

It's almost too easy, isn't it?

If you're looking for a more complex example of using cookies to track a conversation, take a look at our Employee Directory tutorial where we build a full fledged employee directory with Twilio's powerful APIs.

Andrew Baker
Jarod Reyes
David Prothero
Paul Kamp

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:
  • 5.x
  • 6.x
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)
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)