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 to use Programmable Messaging to do this. 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!
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.
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.
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.
1from flask import Flask, request, session2from twilio.twiml.messaging_response import MessagingResponse34# The session object makes use of a secret key.5SECRET_KEY = 'a secret key'6app = Flask(__name__)7app.config.from_object(__name__)89# Try adding your own number to this list!10callers = {11"+14158675308": "Rey",12"+12349013030": "Finn",13"+12348134522": "Chewy",14}151617@app.route("/", methods=['GET', 'POST'])18def hello():19"""Respond with the number of text messages sent between two parties."""20# Increment the counter21counter = session.get('counter', 0)22counter += 12324# Save the new counter value in the session25session['counter'] = counter2627from_number = request.values.get('From')28if from_number in callers:29name = callers[from_number]30else:31name = "Friend"3233# Build our reply34message = '{} has messaged {} {} times.' \35.format(name, request.values.get('To'), counter)3637# Put it in a TwiML response38resp = MessagingResponse()39resp.message(message)4041return str(resp)424344if __name__ == "__main__":45app.run(debug=True)