How To Build A Mustached Message Service With Twilio MMS And Python

September 18, 2014
Written by

stash_pics

All of us at Twilio are over the moon by the possibilities now unlocked by the availability of MMS on US phone numbers.  We know from experience that the real ingenuity will come from you – the air around Twilio is electric with anticipation of the amazing things you’ll build.  We’ve got a lot of hacks we’re excited to show you in the weeks that follow along with the best work we find from all of you.

Have a sick MMS hack?  Send it my way – rob@twilio.com.  Want to get started? Check out this guide by Kevin Whinnery. We can’t wait to see what you build.

To kick off our autumn of MMS hacking, I wanted to share the first thing I did with Twilio MMS.  A couple years ago, my buddy Aidan Feldman released one of the most critical photo services the Internet has yet seen: Mustachify.me.  A truly democratizing technology, Aidan’s killer website makes the august, sophisticated countenance of a long, curly mustache available to everyone.

His magical code can turn this:

Into this:

From the second I got my hands on Twilio MMS, I knew I had to extend Aidan’s service to every phone in the United States and Canada.

Try it now by sending a selfie here:

  • US – (646) 846-8238
  • Canada – (438) 793-8863

Now let’s build our own together.

What You’ll Need

If you want to cut to the chase and have your own working mustache machine, go ahead and deploy the Mustached Message Service to Heroku immediately:

Deploy

If you’d like to build the service yourself, we can get those glorious mustaches messaging with a few ingredients:

  • Your Twilio account – signup for free here.
  • A Twilio phone number enabled for MMS (available in Canada and the United States only for now)
  • Python
  • Flask, a web microframework for Python.
  • A web host accessible on the Internet or a localhost tunneling service like the excellent ngrok.

Getting Started

Awww snap gang – time to bust some hot Pythonic stash action. First, we’ll kick out a little boilerplate to get our Flask app ready to accept some Twilio requests. If you are using pip, you can satisfy these dependencies with a requirements.txt file.

Flask==0.10.1
twilio==3.6.7

Or directly by running this command:

pip install twilio flask

Now let’s cut a little boilerplate to respond with a simple text message.

# Import Flask microframework
from flask import Flask
# Import Twilio Python module
from twilio import twiml

app = Flask(__name__)

# Define the endpoint we'll use for the project. 
@app.route('/sms', methods=['POST'])
def sms():
    # Use the Twilio Python module to craft our response to inbound MMS.
    response = twiml.Response()

    # For now, send a text message back.
    response.message("Boiler plate, snacky!")

    # Casting the object as a string will format our response into TwiML 
    # that Twilio can read and parse.
    return str(response)

if __name__ == "__main__":
    # Since this is a development project, we will keep debug on to make our
    # lives easier. We would want to configure our app more conservatively
    # in production.
    app.debug = True
    app.run()

 

Configuring Your Twilio Number

Now we’ll take the basic endpoint we created and point a Twilio phone number to it. First, we need to go to our Twilio account and purchase a MMS-enabled number. (Note: MMS enabled phone numbers are only available for numbers in the United States and Canada)

Selection_001

Next we’ll set up that number with the publicly accessible address of the application we created above. Like we specified in our app’s only route, we’ll point to /sms for our domain.

Awesome – now after we click save, we should be able to send a message to the number and get a response from our boilerplate app.

Echoing Back MMS Messages

Next, let’s adjust our app to echo back to the user the messages he/she sends to our Twilio MMS-enabled number. We can leverage the noun and Flask’s request object to send the photo our app receives back to the user as a visual echo statement.

from flask import Flask
# Import the request object from Flask.
from flask import request

from twilio import twiml

app = Flask(__name__)

# Define the endpoint we'll use for the project. 
@app.route('/sms', methods=['POST'])
def sms():
    response = twiml.Response()

    # Check if we have media in the message.
    if request.form['NumMedia'] != '0':
        # If we do, echo back the media to the user.
        with response.message() as message:
            message.body = "I received this image."
            message.media(request.form['MediaUrl0'])
    else:
        # If we do not, indicate such to user.
        response.message("Could not find an image in your message.")

    return str(response)

if __name__ == "__main__":
    # Since this is a development project, we will keep debug on to make our
    # lives easier. We would want to configure our app more conservatively
    # in production.
    app.debug = True
    app.run()

Rad – now that we can receive an image and then send it back to the user.

Stashing The Faces

Now we can use Aidan’s mustachify.me service to apply upon every face it can fine with a killer curly cookie duster. Fortunately, mustachify’s interface is a simple URL param with the MediaUrl we receive from Twilio.

from flask import Flask
from flask import request

from twilio import twiml

app = Flask(__name__)

# Define the URL for the service mustaching our photos.
MUSTACHIFY_URL = "http://mustachify.me/?src="

@app.route('/sms', methods=['POST'])
def sms():
    response = twiml.Response()

    if request.form['NumMedia'] != '0':
        with response.message() as message:
            message.body = "STASHED."
            # Give mustachify.me our MediaUrl
            message.media("{0}{1}".format(MUSTACHIFY_URL,
                                          request.form['MediaUrl0']))
    else:
        response.message("Could not find an image in your message.")

    return str(response)

if __name__ == "__main__":
    # Since this is a development project, we will keep debug on to make our
    # lives easier. We would want to configure our app more conservatively
    # in production.
    app.debug = True
    app.run()

Now if we give it a try, every photo gets some distinguished upperlipholstery.

Check out what the Twilio Devangel crew did with this already:

Next Steps

If you’d like to see a more fully fleshed version of this application, be sure to check out the Github Repo here. You can also find the code for Aidan’s mean mustaching machine here.

While mustaches make everything more fun, this is just the entertaining tip of the iceberg of what is possible with receiving and sending Twilio MMS.  Here are just a few of the MMS-powered image manipulation use cases we’ve kicked around:

  • Funhouse mirror photobooths
  • Using optical character recognition to translate signs into different languages
  • Chromakey / alpha channel replacement transporting photo subjects to different places
  • Apply Instagram style vintage filters

We know from experience that no matter how imaginative we get with the services we create, those ideas serve as a mere horizon of the world of wonder you – the Twilio developer – have built time and time again.  We can’t wait to see it – reach out to me at @dn0t on Twitter or via email at rob@twilio.com with your MMS hacks!