How to Build a Galentine's Day Compliment Generator with Python, Flask, and Twilio

February 13, 2019
Written by

ann, you rainbow-infused space unicorn

Happy Galentine's Day, you opalescent tree shark! The holiday dedicated to waffles and your best gal-pals only happens once a year, so I built an SMS-based bot that can generate compliments Leslie Knope would be proud of anytime. Send a text to (765) 234-3009 for a preview of what we're going to build in this short tutorial.

Getting started

Before we dig into some code, make sure that your Python and Flask development environment is setup. If you haven't done so already:

  1. Create a Twilio account
  2. Buy a phone number
  3. Install Python 3
  4. Install Ngrok to make your Flask app visible from the internet so Twilio can send requests to it
  5. Set up your Python development environment 

If you're new to Python and Flask check out this handy guide for more information on getting started.

We also need to install Flask to respond to incoming web requests.

pip3 install Flask
you are a beautiful talented brilliant powerful musk ox

We need to source some adjectives and nouns for our compliments. I have some lists on my GitHub that we can use for just that. Download the following files into the project folder:

curl -O https://raw.githubusercontent.com/robinske/galentinesday/master/adjectives.txt
curl -O https://raw.githubusercontent.com/robinske/galentinesday/master/nouns.txt

Next, create a new file called compliment.py and add the following code:

import random

def construct_compliment():
    compliment = ""

    with open("adjectives.txt") as f:
        adjectives = f.readlines()
        adjectives = [x.strip() for x in adjectives]

        num_compliments = random.randint(2,4)
        compliment = ", ".join(random.sample(adjectives, num_compliments))

    with open("nouns.txt") as f:
        nouns = f.readlines()
        nouns = [x.strip() for x in nouns]
        
        compliment = compliment + " " + random.sample(nouns, 1)[0]
    
    return compliment

print(construct_compliment())

Try running the app to generate your first compliment!

python compliment.py

I got dignified, talented, sociable, easy-peasy jester!

Building a compliment SMS bot

beautiful and organized

Now we can hook up our compliment bot to Twilio. First we need to create a Flask application. In compliment.py add the following imports:

from flask import Flask, Response

Next instantiate the Flask app and create a route. Add the following code to compliment.py.

app = Flask(__name__)

@app.route("/sms", methods=["GET", "POST"])
def sms():
   compliment = construct_compliment()

   resp = """
   <Response>
       <Message>
           Happy Galentine's Day, you {}
       </Message>
   </Response>""".format(compliment)

   return Response(resp, mimetype="text/xml")

This route will return TwiML code that we will use to respond to incoming messages with Twilio. Finally, update the main function to run our Flask app:

app.run(debug=True)

Start the Flask application and test out the endpoint. From the terminal run:

python compliment.py

Navigate to http://localhost:5000/sms, you should see something like this:

TWIML (XML) response that reads "Happy Galentines Day, you working, street smart, perfectible unicorn"
beautiful sassy mannequin

Run the following command from terminal in the directory you'll put your code in.

ngrok http 5000

You should see a screen similar to the one below:

ngrok forwarding url

That publicly-accessible ngrok URL to our Flask app needs to be used when a message is sent to our Twilio number. Keep ngrok running in a separate terminal window while you're developing the application. Heads up: if you need to restart ngrok you'll be assigned a new Forwarding URL.

For Twilio to know how to respond to incoming messages, you need to configure your Twilio phone number to call your webhook URL whenever a new message comes in.

  1. Log into Twilio.com and go to the Console’s Numbers page.
  2. Click on your SMS-enabled phone number.
  3. Find the Messaging section. The default “CONFIGURE WITH” is what you’ll need: “Webhooks/TwiML”.
  4. In the “A MESSAGE COMES IN” section, select “Webhook” and paste in your ngrok URL plus /sms.

twilio ngrok link

Save your changes – you’re ready!

Test your application

As long as your localhost and the Ngrok servers are up and running, we’re ready for the fun part – testing our new compliment generator!

Send a text message from your mobile phone to your Twilio phone number. You should see an HTTP request in your Ngrok console. Your Flask app will process the text message, and you’ll get your response back as an SMS.

sms message

Where to next?

At Twilio we 😍 interactive bots. I’ve had so much fun building Swansonisms and my Where is Kelley bot. If you want to build more bots, you might be interested in these resources:

You can also download the finished code for this project on my GitHub.

The low overhead of SMS makes bots easy to share with friends and family and show off what you’ve built. I can’t wait to see what you build!