SMS Sentiment Analysis in Python with Flask and the IBM Watson Twilio Add-on

July 14, 2016
Written by
Sam Agnew
Twilion

watson

With Twilio’s new Add-ons marketplace developers can reap the benefits of third party APIs with the flip of a switch. The IBM Watson Message Sentiment Add-on adds sentiment analysis information to every SMS request sent to your web application.

Let’s build a Flask app that will determine the sentiment of text messages sent to your Twilio number.

Getting started

Before writing any code make sure you have:

Now let’s install the necessary third party libraries.

Run the following commands in your terminal to install Flask and the Twilio Python module, preferably in a virtual environment:

pip install flask
pip install twilio

Responding to Incoming text messages

Before being able to respond to messages, you’ll need a Twilio phone number. You can buy a phone number here.

Now let’s create a web app that responds to text messages sent to this number. Open a file called app.py and create a Flask app with one route:

from flask import Flask, request
from twilio import twiml


app = Flask(__name__)


@app.route('/sms', methods=['POST'])
def sms_reply():
    message_received = request.form['Body']
    response_message = 'Your message was {}.'.format(message_received)

    response = twiml.Response()
    response.message(response_message)
    return str(response)


app.run()

When a text comes into Twilio, Twilio makes an HTTP request to your webapp and expects instructions back in the form of TwiML. The single route on this web app uses the Twilio Python library to generate and return TwiML that responds to the with another message.

Your Flask app will need to be visible from the Internet in order for Twilio to send requests to it. We will use ngrok for this, which you’ll need to install if you don’t have it.  In your terminal run the following command:

ngrok http 5000

Screen Shot 2016-07-14 at 10.52.54 AM.png

This provides us with a publicly accessible URL to the Flask app. Configure your phone number as seen in this image:
        

Screen Shot 2016-07-14 at 10.54.53 AM.png

You are now ready to send a text message to your new Twilio number.

SMS Sentiment Analysis with IBM Watson

To add sentiment analysis to all of your , you just need to activate the IBM Watson Message Sentiment Add-on by clicking the “Install” button in your console.

Screen Shot 2016-07-14 at 10.57.24 AM.png

In the POST request sent to your application, there will be a new AddOns field, inside of which you can access the data from the IBM Watson API:

{ 
    "status": "REQUEST_STATUS",
        "language": "DOCUMENT_LANGUAGE",
    "docSentiment": {
        "type": "SENTIMENT_LABEL",
        "score": "DOCUMENT_SENTIMENT",
        "mixed": "SENTIMENT_MIXED"
    } 
}

This AddOns object will be JSON that you will need to parse. Open app.py again and add the following line to the top of your code:

import json

To access the sentiment of the incoming messages, you just need to add a few more lines of code. Open app.py again and rewrite your /sms route:

@app.route('/sms', methods=['POST'])
def sms_reply():
    add_ons = json.loads(request.form['AddOns'])
    if add_ons['status'] == 'successful':
        result = add_ons['results']['ibm_watson_sentiment']['result']
        sentiment = result['docSentiment']['type']
        response_message = 'Your response was {}.'.format(sentiment)
    else:
        response_message = 'An error has occured.'

    response = twiml.Response()
    response.message(response_message)
    return str(response)

Now send some happy and sad text messages to your Twilio number!

Looking Ahead

With some configuration and a few extra lines of code, you can get the sentiment of all messages sent to your Twilio phone numbers, whether you’re using it to improve customer experience or to decide which GIFs to send to your users.

U1VADVq.gif

Feel free to reach out if you have any questions or comments or just want to show off the cool stuff you’ve built.