It’s getting easier to get sentimental about SMS with Twilio Add-ons

August 09, 2016
Written by
Phil Nash
Twilion

Twilio Add-ons is a marketplace for 3rd party services that you can use to add superpowers to your Twilio applications. I’m a huge fan of Add-ons because they handle tasks we would otherwise need custom code for in our applications. We can also streamline existing applications by replacing our code with an Add-on.

Last year I wrote about sentiment analysis of SMS messages using Twilio, Bluemix and AlchemyAPI. It didn’t take a lot of code to create the beginnings of a powerful service based on sentiment analysis of incoming SMS messages. But with code I often find less is more. At least, less code that I have to maintain is better in my mind. One of my favourite things is deleting code, so let’s see what happens if we take that original code and replace the explicit call to the AlchemyAPI with the IBM Watson Message Sentiment Add-on.

Tools

We’re going to be building on top of the original Ruby application that I wrote.

If you’ve got all that, then let’s see how we can improve this project.

Switch on the Add-on

First we need to switch on the Add-on for our account. Open up the Add-ons section of the Twilio console and find the IBM Watson Message Sentiment Add-on (or click here to go straight to it). Click the big red install button, read and agree to IBM’s terms of service and you’re nearly done. Just check the box that enables the Add-on for incoming SMS messages, save the form and you will start receiving sentiment analysis with every text.

In the Twilio console, once you have installed the Add-on, make sure you check the box to use the Add-on in incoming SMS messages.

Please note that this will pass all incoming messages to your account through this service and charge you $0.0015 per request. If you don’t plan to use this after this blog post remember to turn off the Add-on.

Time to remove some code

Now that the work to gather the sentiment analysis from Watson is being done by Twilio we’re not going to need the AlchemyAPI gem any more. Remove it from the Gemfile.

source 'https://rubygems.org'
ruby "2.3.1"
gem 'sinatra', '>= 0'
gem 'json', '>=0'
-gem 'alchemy-api-rb', :require => 'alchemy_api'

And stop requiring it in helloWorld.rb.

# helloWorld.rb
require 'sinatra'
require 'json'
-require 'alchemy_api'

We no longer need to pick up our AlchemyAPI credentials from Bluemix’s VCAP_SERVICES. Nor do we need to initialise the AlchemyAPI wrapper with an API key.

-def vcap_services
-  JSON.parse(ENV['VCAP_SERVICES'])
-end
-
-AlchemyAPI.key = vcap_services['user-provided'][1]['credentials']['apikey']

Now we get to our /messages endpoint. This is the path that Twilio will use to POST SMS messages to as they arrive. Instead of receiving the message and sending the body off to the AlchemyAPI we will be getting the sentiment analysis along with the message.

Using Twilio Add-ons we get an extra parameter delivered with our message, AddOns. It contains a JSON string which contains all the information Twilio has gathered based on the Add-ons you have activated in your account. We need to parse the JSON, find out if Twilio was successful in retrieving the results from the Add-ons and then reach into the results and extract the data we are interested in.

When using the IBM Watson sentiment analysis Add-on the results live under the ibm_watson_sentiment key. You can see more about this in the Add-on documentation, but the format is:

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

To replicate our previous feature, we need to retrieve the type from within the docSentiment field.

 post '/messages' do
   content_type "text/xml"
 
-  sentiment = AlchemyAPI.search(:sentiment_analysis, text: params["Body"])
+  add_ons = JSON.parse(params["AddOns"])
+  if add_ons["status"] == "successful"
+    sentiment = add_ons["results"]["ibm_watson_sentiment"]["result"]["docSentiment"]
     case sentiment['type']
     when "positive"
       message = "Glad you're having a good day! Is there anything I can help with?"
     when "negative"
       message = "Sorry things aren't going so well, how can I help?"
     else
       message = "What can I help with?"
     end

The rest of the request is the same. Well, there’s actually some error handling here that I missed the first time around. We check if the Add-on returned successfully by ensuring the status is “successful”, in the case that we didn’t have a successful result we want to return the generic response that isn’t based on sentiment. So we add the else to that conditional like so:

+  else
+    message = "What can I help with?"
+  end

And that’s it! Push your work up to Bluemix, wait for the deploy to complete and send yourself a positive or negative SMS.

$ cf push

When you send a message you get different responses based on the sentiment of your message.

You’ll see you have the same results, but with one less gem dependency, one fewer HTTP request in our code and 3 less lines of code total.

The git diff --stat command shows 2 files changed with 6 insertions and 9 deletions.

Twilio Add-ons do the work so that you don’t have to

We’ve seen today that including an Add-on can save you time, effort and code. Using Twilio Add-ons for a feature like sentiment analysis means your application can be more powerful and more intelligent without you having to write a whole bunch of code or learn a new API or platform. In our simple example we removed a dependency and an HTTP request and required less lines of code to achieve the same result. Check out the code now.

There’s more to Add-ons than just sentiment analysis too.

Check out all the available Add-ons and find out the super-powers your application could gain. Maybe you’ll get to delete some code too!