Supercharge your Twilio API calls with Add-ons

May 24, 2016
Written by

PTzDLNbR0Smx0esXCjKZd0hri5eq6vLtRxWphSX57FfkoFfkWvQ9_8cCVb_1KJ4oGQQs3TTyEwTJTQX6q6kA8jdsH6L4UbbsJP9zthuEga6PVLSd77r2fJDL730fECRpJWzrRnVB

Twilio Add-ons let you supercharge your Twilio API calls with features and capabilities offered by other communications API’s. Let’s add some Add-ons to our account and see how these mashups let us build better apps with fewer API calls.

giphy.gif

Activating your favorite Add-ons

Find Add-ons to add to your account by heading over to the new Twilio Marketplace section of the Console. In this post we’ll look at two of them, the Ekata Reverse Phone and the IBM Watson Message Sentiment Add-ons.

To activate the Ekata Reverse Phone and the IBM Watson Message Sentiment Add-ons, press the Install button.

Screenshot of Twilio Console on the Ekata add-on screen

 

For the Ekata Reverse Phone Add-on, make sure that the Use In Lookups checkbox is selected. For the IBM Watson Message Sentiment Add-on, make sure that the Use In Incoming SMS Message checkbox is selected.

addon-installed-config-notes.png

Once both Add-ons are activated we’re ready to start using them.

No more spam or serial-fraudsters!

giphy (2).gif

With the Ekata Reverse Phone Add-on we can retrieve additional historic phone number related data as part of a request to the Twilio Lookup API.

To tell Twilio we want this additional data all we need to do is pass the AddOns parameter to the API specifying the unique names of the Add-ons to use.

For example, using the Twilio Node helper library you include an addOns parameter with your Lookup request:

const twilio = require('twilio');
const client = twilio('YOUR_TWILIO_ACCOUNT_SID', 'YOUR_TWILIO_AUTH_TOKEN');

client.lookups.phoneNumbers('+18448144627').fetch({
  type: 'carrier',
  addOns: 'ekata_reverse_phone'
}, (error, number) => {
  console.dir(number.addOns.results['ekata_reverse_phone'], { depth: 5 });
});

Twilio will do a phone number lookup and mash the results of that API request together with the result from the Ekata Reverse Phone API, placing that data into a property named add_ons.

{
    "callerName": null,
    "countryCode": "US",
    "phoneNumber": "+14157012311",
    "nationalFormat": "(415) 701-2311",
    "carrier": {
        "mobile_country_code": null,
        "mobile_network_code": null,
        "name": "Pacific Bell",
        "type": "landline",
        "error_code": null
    },
    "addOns": {
        "status": "successful",
        "message": null,
        "code": null,
        "results": {
            "ekata_reverse_phone": {
                "status": "successful",
                "request_sid": "XR7f9025da0917e7f55238d9ddad168f0f",
                "message": null,
                "code": null,
                "result": {
                    "phone_number": "4157012311",
                    "warnings": [],
                    "historical_addresses": [],
                    "alternate_phones": [
                        "8775437669"
                    ],
                    "error": null,
                    "is_commercial": true,
                    "associated_people": [],
                    "country_calling_code": "1",
                    "belongs_to": [
                        [
                            null
                        ]
                    ],
                    "is_valid": true,
                    "line_type": "Landline",
                    "carrier": "Pacific Bell",
                    "current_addresses": [
                        [
                            null
                        ]
                    ],
                    "id": "Phone.f2af6fef-a2e0-4b08-cfe3-bc7128b7ef8d",
                    "is_prepaid": false
                }
            }
        }
    },
    "url": "https://lookups.twilio.com/v1/PhoneNumbers/+14157012311?Type=carrier"
}

In this payload we can review info like, is this a commerical business, is this a prepaid number, who is associated with that number and if there are any historic warnings about this number.

Happy or sad customer SMS?

Programmatically receiving and responding to SMS messages can enable great customer experiences. However without appropriately determining the context of the message we can end up with a static experience that feels robotic to the user.

With the IBM Watson Message Sentiment Add-on you can perform sentiment analysis on every incoming message without making any changes to your application. Because we’ve enabled the Add-on we start getting the semantic analysis results automatically passed in the payload of every incoming SMS webhook request.

Grab the ibm_watson_sentiment information out of the AddOns property from the payload and use it to determine whether the message is positive, negative or neutral and even how strong the sentiment is so that you can reply accordingly.

Give it a try using Node.js by creating a new file called server.js and dropping this code into it:

'use strict';

const bodyParser = require('body-parser');
const express = require('express');
const http = require('http');
const twilio = require('twilio');

const app = express();
const port = process.env.PORT || 3000;

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

app.post('/sms', (req, res) => {
  let twiml = new twilio.TwimlResponse();
  
  let addOnResults = JSON.parse(req.body.AddOns);
  let sentimentResult = addOnResults.results['ibm_watson_sentiment'];
  if (sentimentResult.status === 'successful') {
    if (sentimentResult.result.docSentiment.type === 'positive') {
      twiml.message('YAY! Glad to see you happy!');
    } else if (sentimentResult.result.docSentiment.type === 'negative') {
      twiml.message('That is unfortunate. Anything I can do?');
    } else {
      twiml.message('Ahoy! How are you?');
    }
  } else {
    twiml.message('We could not determine how you feel :(');
  }
  
  res.type('text/xml').send(twiml.toString());
});

http.createServer(app).listen(port, () => {
  console.log(`listening on port '${port}'`);
});

Install the application dependencies and start the server:

$ npm install body-parser express twilio
$ node server.js

sentiment-sms-screenshot.png

Run ngrok http 3000 in a separate window to expose your server to the public using ngrok. If you want to know more about ngrok you can read more here.

Wire up the Message Request URL of an SMS enabled Twilio Phone Number with your ngrok URL. Send a text message to that number and watch as your application responds with a contextually appropriate message.

Just the beginning

Awesome! We have now supercharged our API calls to improve our customers experience even more and all that with only a few changes. Checking for fraud and the sentiment of a message is just the beginning though. You can find more Add-ons in the Twilio Marketplace.

Interested in offering your own API in the Twilio Marketplace? Request an invite and we’ll get in touch with you.

I can’t wait to see what you build with the new Add-ons! Feel free to contact me on Twitter @dkundel or via email dkundel@twilio.com to tell me more about it.

Flying away Dragonball Scene