How To Use Recording Add-ons in Python

January 10, 2017
Written by
Reviewed by
Paul Kamp
Twilion
Kat King
Twilion
Hector Ortega
Contributor
Opinions expressed by Twilio contributors are their own
Jose Oliveros
Contributor
Opinions expressed by Twilio contributors are their own

recording-add-ons-python

In this guide we’ll cover how to combine Twilio Add-ons with Programmable Voice to use data from Twilio's partners in your Flask web application. Let's get started!

What’s an Add-On?

Twilio Add-ons are pre-integrated third party services that you can use with your Twilio application. Add-ons enhance the responses your application receives from Twilio by including additional data from Twilio’s partners.

In this guide we’ll cover how to combine Twilio Add-ons with Programmable Voice to use data from Twilio's partners in your Flask web application. The sample code in this guide will use the Twilio Python SDK and the Flask web framework. Let's get started.

{
  "status":"successful",
  "message":null,
  "code":null,
  "results":{
    "ibm_watson_speechtotext":{
      "request_sid":"XRc82d4197bbc51d5982588ae367365a51",
      "status":"successful",
      "message":null,
      "code":null,
      "payload":[
        {
        "content_type":"application/json",
        "url":"https://api.twilio.com/2010-04-01/Accounts/AC597d02bf69de79f8f411f289ac211a0d/Recordings/REab85c1c2860471abf040b545c4e5aa40/AddOnResults/XRc82d4197bbc51d5982588ae367365a51/Payloads/XH364bd4514b1377fd8844cd9793416131/Data"
        }
      ],
      "links":{
        "add_on_result":"https://api.twilio.com/2010-04-01/Accounts/AC597d02bf69de79f8f411f289ac211a0d/Recordings/REab85c1c2860471abf040b545c4e5aa40/AddOnResults/XRc82d4197bbc51d5982588ae367365a51",
        "payloads":"https://api.twilio.com/2010-04-01/Accounts/AC597d02bf69de79f8f411f289ac211a0d/Recordings/REab85c1c2860471abf040b545c4e5aa40/AddOnResults/XRc82d4197bbc51d5982588ae367365a51/Payloads",
        "recording":"https://api.twilio.com/2010-04-01/Accounts/AC597d02bf69de79f8f411f289ac211a0d/Recordings/REab85c1c2860471abf040b545c4e5aa40"
      }
    }
  }
}

Here’s an example that uses the IBM Watson Speech to Text Add-on. The generated transcription will be pushed to the application through a callback from Twilio.

The IBM Watson Speech add-on can convert Twilio audio recordings into text using machine intelligence to combine information about grammar and language structure.

{
  "user_token": "XRf951c9b0bce23930750991099e553b0a",
  "results":[
    {
      "results":[
        {
          "keywords_result":{},
          "alternatives":[
            {
            "timestamps":[
              ["I", 0.04, 0.28],
              ["love", 0.28, 0.71],
              ["coding", 0.74, 1.25]
            ],
            "confidence":0.782,
            "transcript":"I love coding "
            }
          ],
          "final":true
        }
      ],
      "result_index":0
    }
  ],
  "id":"b0e7a660-bcb6-11e6-8b1b-192a5f5dc12f",
  "event":"recognitions.completed_with_results"
}

Enabling Add-ons in the Twilio Console

The first stop in using an add-on is your Twilio Console. Log in and navigate to the Add-ons page within the Marketplace section.

Add-ons catalog

Then choose on the add-on you want to enable and click the “Install” button. After accepting the Terms of Service, it will be installed on your account. In this example, we’ll use the IBM Watson Speech to Text Add-on.

IBM Watson Speech to Text install Add-on


Once installed, select the checkbox for the recording method you are using (see the different recording methods here). In our example to follow, we would only need the "Record Verb Recordings".  

Set the "Callback URL" and "Callback Request Method" as appropriate for your public server URL (instructions below).

Pro Tip: you can quickly inspect what Twilio will send to your callback URL using tools like PostBin before you actually set up your server.

IBM Watson Speech to Text Configure tab

Legal implications of call recording

If you choose to record voice or video calls, you need to comply with certain laws and regulations, including those regarding obtaining consent to record (such as California’s Invasion of Privacy Act and similar laws in other jurisdictions). Additional information on the legal implications of call recording can be found in the "Legal Considerations with Recording Voice and Video Communications" Help Center article.

Notice: Twilio recommends that you consult with your legal counsel to make sure that you are complying with all applicable laws in connection with communications you record or store using Twilio.

Now we’re ready to use the extra data from our add-on in our Flask application.

Using Add-on data in your application

Twilio will include data from all of your add-ons in an “AddOns” field on HTTP requests it makes to your application. The following example demonstrates how to access add-on data within your Flask application.

from flask import Flask, request
from twilio.twiml.voice_response import VoiceResponse
import json
import os
import requests

app = Flask(__name__)


@app.route("/voice", methods=['GET', 'POST'])
def voice():
    # Start our TwiML response
    response = VoiceResponse()
    response.say('Hi! I want to know what do you think about coding.')
    response.record(maxLength="10", action="/recording")
    response.hangup()

    return str(response)


@app.route("/recording", methods=['GET', 'POST'])
def recording():
    recording_url = request.values.get("RecordingUrl", None)
    print(recording_url)

    response = VoiceResponse()
    response.say("Thanks for howling... take a listen to what you howled.")
    response.play(recording_url)
    response.say("Goodbye.")

    return str(response)


@app.route("/callback", methods=['POST', 'PUT'])
def callback():
    add_ons = json.loads(request.values['AddOns'])

    # If the Watson Speech to Text add-on found nothing, return immediately
    if 'ibm_watson_speechtotext' not in add_ons['results']:
        return 'Add Watson Speech to Text add-on in your Twilio console'

    payload_url = add_ons["results"]["ibm_watson_speechtotext"]["payload"][0]["url"]

    account_sid = os.environ.get('TWILIO_ACCOUNT_SID')
    auth_token = os.environ.get('TWILIO_AUTH_TOKEN')
    resp = requests.get(payload_url, auth=(account_sid, auth_token)).json()

    results = resp['results'][0]['results']
    transcripts = map(lambda res: res['alternatives'][0]['transcript'], results)

    return ''.join(transcripts)


if __name__ == "__main__":
    app.run()

This application gets the transcription for the recorded call from IBM Watson Speech to Text Add-on we configured in the Twilio console. You can find a detailed specification of the data structure for an individual add-on within that add-on's page in the catalog.

And that’s it! Try giving your application a call to see your add-on in action. If you've never received a Twilio phone call with Python before, check out our guide on that topic.

Where to next?

We focused on the IBM Watson Speech to Text Add-on in this guide, but you can just as easily use any of the add-ons available in the catalog in your Twilio Console.

Check out the full Add-Ons API Reference documentation if you want to learn more about how add-ons work, or even how to publish your own.