Skip to contentSkip to navigationSkip to topbar
Rate this page:
On this page

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 Messaging(link takes you to an external page) makes this easy. We'll use Python, the Flask(link takes you to an external page) 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!

(information)

Info

Twilio Conversations, a more recent product offering, is an omni-channel messaging platform that allows you to build engaging conversational, two-way messaging experiences. Be sure to check out our Conversations product to see if it's a better fit for your needs.


Using HTTP Cookies with Webhooks

using-http-cookies-with-webhooks page anchor

Storing Conversation Data

storing-conversation-data page anchor

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

track-sms-conversations-using-a-session page anchor

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.

Tracking SMS Conversations using Cookies

tracking-sms-conversations-using-cookies page anchor
Python

_45
from flask import Flask, request, session
_45
from twilio.twiml.messaging_response import MessagingResponse
_45
_45
# The session object makes use of a secret key.
_45
SECRET_KEY = 'a secret key'
_45
app = Flask(__name__)
_45
app.config.from_object(__name__)
_45
_45
# Try adding your own number to this list!
_45
callers = {
_45
"+14158675308": "Rey",
_45
"+12349013030": "Finn",
_45
"+12348134522": "Chewy",
_45
}
_45
_45
_45
@app.route("/", methods=['GET', 'POST'])
_45
def hello():
_45
"""Respond with the number of text messages sent between two parties."""
_45
# Increment the counter
_45
counter = session.get('counter', 0)
_45
counter += 1
_45
_45
# Save the new counter value in the session
_45
session['counter'] = counter
_45
_45
from_number = request.values.get('From')
_45
if from_number in callers:
_45
name = callers[from_number]
_45
else:
_45
name = "Friend"
_45
_45
# Build our reply
_45
message = '{} has messaged {} {} times.' \
_45
.format(name, request.values.get('To'), counter)
_45
_45
# Put it in a TwiML response
_45
resp = MessagingResponse()
_45
resp.message(message)
_45
_45
return str(resp)
_45
_45
_45
if __name__ == "__main__":
_45
app.run(debug=True)


Rate this page: