Posts Tagged ‘webapi’

How-To: Sending an SMS using WebAPI

Friday, September 10th, 2010

Sending an SMS with WebAPI is quite simple, especially since we added the {message:} object to the API. To get started we’ll need you to first create a WebAPI application in your Tropo account. Once you have set this up you will need to assign an SMS enabled phone number to the application, this part is required to send messages from the application. The next step is to make sure you have a messaging token associated with the application, since you will need this to start the session via our API (more on this in a few). Please note there are two Tokens associate with Tropo applications, one for voice calls, and one for messaging, we will want to use the Messaging token for our purposes here, but if you are interested in Voice calls please check out our guides for Scripting and WebAPI.

I will be using the Ruby WebAPI helper class for most of this example,  however I will post also include the raw JSON in-case you are using other libraries to render it (C#, Python, PHP, ect).

To start please take a look at the finished product, this is an example in Sinatra, using the Ruby helper class ( Tip: Additional WebAPI Power tips can be found in a previous blog posting here).

require 'rubygems'
require 'sinatra'
require 'tropo-webapi-ruby'

post '/' do
  sessions_object = Tropo::Generator.parse request.env['rack.input'].read
msg = sessions_object[:session][:parameters][:msg]
number_to_dial = sessions_object[:session][:parameters][:to]

tropo = Tropo::Generator.new do
            message({
                          :to => 'tel:+1'+number_to_dial,
                          :channel => 'TEXT',
                          :network => 'SMS'}) do
                             say     :value => "#{msg}"
                          end
            end

  tropo.response

end

If you have the WebAPI class installed then you can start Sinatra by just running sinatra my_app.rb from the command line.  This will start the server, and as long as you have the URL to this machine in the messaging portion of your application then we are all set!  If you are doing development, and are perhaps behind a firewall, you can get setup quickly by using something like tunnlr ( more info here ).

So lets review…  we have our server running, Tropo application created and pointed to our running server.  We have a messaging number associated with the application, and a messaging token.  I thin we are ready to rock and roll!!

So to send the message we need to send an HTTP request to Tropo’s sessions API.  So I’ll go ahead and use CURL, which is a command line tool which will among other things send HTTP requests.  If you dont have CURL you can just as easily place the URL in your browser, since this will accomplish the same end result ( Tip: make sure to substitute your number in the to parameter, and use your own messaging token in place of ‘my_messaging_token_id’ )

curl "http://api.tropo.com/1.0/sessions?action=create&token=my_messaging_token_id&msg=my+message+to+send&to=4075551212"

Now the magic begins! What will happen is this HTTP request will hit our API servers, and using the messaging tokenID we’ll route that to your applications startURL. This will in turn send a JSON payload to your messaging startURL similar to what you see below. Please pay close attention to the parameters located in this JSON body, this contains the message, the number we are sending a msg to, as well as various other parameters:

{
    "session": {
        "id": "76b05a0b25127dbf59a4627f6dcd38a7",
        "accountId": "12345",
        "timestamp": "2010-05-05T01:59:19.402Z",
        "userType": "NONE",
        "initialText": null,
        "callId":"092f931c4dddf0124ef426c56d26f98c",
        "parameters": {
            "token": "my_messaging_token_id",
            "action": "create",
	     "msg":"my message to send",
	     "to":"4075551212"
        }
    }
}

This JSON payload will hit out application and using the parse method of Tropo’s WebAPI helper class we can grab the associated values needed to send out message. This way we can use the same application to send multiple messages, to multiple recipients, with out having to change our code:

  sessions_object = Tropo::Generator.parse request.env['rack.input'].read
    msg = sessions_object[:session][:parameters][:msg]
    number_to_dial = sessions_object[:session][:parameters][:to]

Now we just use the generator method to build the return JSON payload, which we’ll send back to the Tropo session, which will then send the message. You can see the final JSON that our script sends back to Tropo below for your reference:

{
     "tropo":   [
         {
          "message": {
           "channel": "TEXT",
           "to": "tel:+14075551212",
            "say": [
                 {
                "value":"my message to send"
                 }
             ],
              "network": "SMS"
         }
    }
  ]
}
This payload instructs Tropo to send the message to your user, and all of this was started with a simple HTTP request, how cool is that! Now to wrap things up I wanted to touch on a few frequently asked questions we see related to messaging:

  • When you send a message you can set the from callerID, however the number must be associated with the application sending the message.
  • SMS Messages are carrier limited to 10 messages per number a minute, and currently the developer is responsible the throttling their messaging campaigns.
  • Tropo does not block international SMS messages at this time, but delivery to international carriers is not officially supported at this time.
  • I really hope this information is helpful, and if there are any other questions please let us know, as our team is most certainly always standing by to offer any help our developers may require. You can always find us on Freenode irc.freenode.net in #tropo.

    John Dyer

    Tropo Support

    HOWTO: Working with the Python 3 branch of the Tropo Python Web API library

    Wednesday, September 8th, 2010

    Python logoAs we’ve rolled out the python module for the Tropo WebAPI, one of the questions naturally is – which version of python is this for?

    Developers who don’t work with python may not be aware that the new python version 3.x is deliberately NOT backwards-compatible with python 2.x. There are many reasons and the reality is that python 2.x will be in usage for many years – even as all the new development happens with 3.x.

    So the quick answer is that the main branch of the python library for the Tropo WebAPI is targeted at python 2.5 or later. (Current is 2.7.)

    However, for people who want to work with python 3.x, I created a branch in the Github repository called “python3″ that includes a version of the Web API that works with python 3.x. There’s a catch, though:

    When you download the code or clone the repo from Github, you only get the ‘master’ branch with the 2.x code.

    The “git clone” command just pulls the one main master branch. Similarly, if you download the code directly from the website (i.e. not using ‘git’), you will by default get the 2.x code only.

    Here’s how to fix that… for both command-line git and for the web download.


    THE WEB WAY

    If you download the python module from the Github website, it’s a simple process to get the python3 code. Simply go to the module web page, click on the “Switch Branches” link on the nav bar, and choose “python3″:

    tropowebapi-switchingbranches.jpg

    Now when you click on the “Download Source” button in the upper right of the screen you will get the python 3.x source code.


    THE GIT WAY

    For command-line git, the process isn’t too much different – and you can nicely have both the 2.x and 3.x code in your same local directory on your system. Github nicely provides this handy “git cheat sheet” that includes these relevant lines:

    TO PULLNEW BRANCH FROMREMOTE REPOSITORY

    git fetch origin [remote-branch]:[new-local-branch]

    So the magic command to get the python 3 branch into your local clone of the repo is to make sure you are in your local repo and type:

    git fetch origin python3:python3

    You now will have the python3 branch in your local repo – but the code you see will still be the 2.x until you switch to the new branch.

    Here’s how the command-line sequence would look:

    $ git fetch origin python3:python3
    From git@github.com:danyork/tropo-webapi-python
    * [new branch] python3 -> python3 $ git branch
    * master
    python3
    $ git checkout python3
    Switched to branch "python3"
    $

    The code in your repo will now be the python 3.x code and you can work with it and try it out with your applications.

    To switch back to the 2.x code, just do:

    git checkout master

    And to go back to the 3.x code, just do:

    git checkout python3

    Alternatively, you could clone the repo twice into two different directories and have one be the python3 branch all the time. Different people have different strategies.

    Over time, if you want to pull down any changes that have been made to the Github repo for the python 3 branch, you can type this (MAKE SURE YOU ARE IN THE ‘python3′ BRANCH IN YOUR LOCAL REPO):

    git pull origin python3

    That’s it.


    MOVING FORWARD WITH PYTHON 3.X CODE

    I created the “python3″ branch because I had a personal interest in experimenting with python 3.x for a Tropo app. I plan to do my best to keep it in sync with any changes and improvements that are made to the 2.x track… but any help is welcome! If you work with python 3 and find ways to make the Tropo module work better (or more “Python 3-ish”) please do contact me either via Github (I’m “danyork“) or via email.

    P.S. If you are a regular Github user, feel free to fork http://github.com/tropo/tropo-webapi-python, make your changes in your fork and then send a pull request. (And if that last sentence made no sense whatsoever to you, don’t worry… it’s all good.)

    New Guidelines for Naming Tropo Web API Language Libraries (ruby, PHP, python, C#)

    Tuesday, August 31st, 2010

    UPDATE, Sept 3, 2010:After some discussion, the consensus is to make the language library naming even a bit easier for developers and move the module names from “tropo-webapi” to simply “tropo”. The table below has been updated to show the change.


    With the availability of the Tropo Web API, it’s been great to see the development of Tropo libraries for various programming languages, which let developers easily and quickly build Tropo apps for voice and SMS.  We now have Tropo Web API libraries available for Ruby, PHP, Python and C#:

    http://github.com/tropo

    However, as those libraries have evolved, we’ve found that they’ve developed in slightly different directions with regard to the naming of the repository on Github and to the module names, etc.  We gave some thought to the best way to provide guidance to make it easier on developers, and came up with these goals:

    • Provide a consistent repo name so developers using multiple languages can easily locate their downloaded/cloned directories on their local systems.
    • Provide consistent naming of module/library names and function/class names so developers can move with ease from one language to another. (Use case: a developer builds a Ruby app for one client for Tropo. Developer then needs to build a PHP app for another client. Developer should be able to move from one Tropo library to another without having to relearn or guess what the names are.)
    • Allow for the future creation of additional Tropo-related modules/libraries

    To get there, the existing repositories are going to migrate to these new names:

    • http://github.com/tropo/tropo-webapi-ruby
    • http://github.com/tropo/tropo-webapi-php
    • http://github.com/tropo/tropo-webapi-python
    • http://github.com/tropo/tropo-webapi-ruby

    Going forward, we’ll ask that anyone creating a new Tropo Web API module please follow this same naming convention.

    We’re also going to move the names of the actual modules to be more consistent. The result will be something like:

    Ruby require ‘tropo-webapi-ruby’
    require ‘tropo’
    PHP require ‘tropo-webapi.class.php’;
    require ‘tropo.class.php’;
    python import tropo_webapi
    import tropo
    C# using TropoCSharp.TropoWebAPI;
    using TropoCSharp.Tropo;

    You’ll note that we’re treating “webapi” as one word in the names. (Note: These may be the final names, but they may change as the changes get made to each library.)

    We’re in the process of working with the library authors to make these changes now.  The migration is a pain, quite honestly, because it’s going to break existing applications, samples, tests, etc., but we want to do this once so as these modules start to get more widely used, there is a good degree of consistency between them.

    We’ll let you know as the libraries are moved over to the new convention – and please let us know now if you have any feedback on this issue.

    Thanks – and we’re definitely looking forward to continuing to see the awesome apps you all are building with Tropo!

    Tracking calls with Google Analytics

    Monday, June 28th, 2010

    If you’re building a web site you’re probably using Google Analytics to track traffic. All the cool kids are. How’d you like to start tracking your Tropo phone calls in Analytics as well?

    This tutorial is going to show you how to use Google Analytic’s Mobile Web support to insert call information into your Analytics account.

    First download the client libraries for Google Analytics Mobile (use the “server-side snippets” code). At the time of this writing, the download includes libraries for PHP, Perl, JSP and ASPX. There’s a PDF file in the download that tells you how to get your mobile tracking ID. It’s just your Google Analytics account ID, but with the UA- replaced with MO-. If your Analytics ID is UA-123456-1 then your mobile ID will be MO-123456-1.

    Normally Google Analytics uses tracking code that uses JavaScript on your page to send some data to Google each time a page is accessed. On mobile web sites and apps, Javascript might not be available, so Google has created a way for you to send the data over to them using code running on your server. The phone doesn’t run client-side JavaScript either, so we’re going to use this same server side method on a Tropo WebAPI application to push call data into Analytics.

    Google has designed the the client library to create a unique URL that’s inserted as an image tag on your mobile site. When the image is loaded, the library builds the analytics data and pushes it to Google. Since the phone is an environment that doesn’t support image tags, we’re going to build the URL and then open it with an HTTP client during each call.

    This code uses the PHP Google library, Tropo’s Web API, and the Tropo PHP library for the WebAPI.

    Most of the things that you’d track in web reports like URLs visited, IP addresses, and user-agent strings don’t exist in a phone call, so to make our reports more useful, we’re going to set some of the headers and environment variables manually. This is something you’ll probably want to tweak to get useful reports. I’m going to set the User-Agent to the caller’s area code and build a unique user ID cookie for tracking repeat calls.

    The PHP library has a snippet of code (snippet1.php) that’s supposed to be placed at the top of our PHP file. Place that at the top of your app’s code. Google’s instructions also include a second snippet that’s to be placed at the bottom of the PHP page, but since we’re not using the image tags, you don’t need to do that.

    You’ll need to edit the snippet after you add it, since it contains a bug. The PHP and Perl libraries don’t properly set the query string. The ASPX and JSP libraries don’t have this bug. In the PHP snippet you just added, find the lines that say …

    if (!empty($path)) {
      $url .= "&utmp=" . urlencode($path);
    }
    

    … and change it to read …

    if (!empty($path)) {
      if (!empty($query)) {
        $path .= "?$query";
      }
      $url .= "&utmp=" . urlencode($path);
    }
    

    Or, instead of manually editing the files, here’s a zip with patches for PHP and Perl.

    Now right before the snippet you added, we’ll create a user-agent string with the caller’s area code and a cookie value that matches the format that Google sets when they create a tracking cookie.

    $session = new Session();
    // Create a User-Agent string for the area code.
    $UA = 'Area code '. substr($session->from['id'],1,3);
    // Create a user ID cookie based on the callerid
    $cookie = "0x" . substr(md5($session->from['id']), 0, 16);
    

    Now right after the snippet from the PHP library, we need to load the tracking URL with PHP. The Mobile Web library snippet includes a function googleAnalyticsGetImageUrl() that builds a portion of the URL but it only returns the filename and query string. To load the URL manually, we need a fully-qualified base URL in the form http://example.com/some/path/ instead. Assuming that you’re putting ga.php in the same directory as your Tropo app, all you need to do is construct a base URL and append the output of googleAnalyticsGetImageUrl() to it.

    $protocol = $_SERVER['HTTPS'] == 'on' ? 'https' : 'http';
    $port = ($_SERVER["SERVER_PORT"] == "80") ? "" : ":".$_SERVER["SERVER_PORT"];
    $path = dirname($_SERVER['REQUEST_URI']);
    $path == '/' ? '' : $path;
    $url = $protocol .'://'. $_SERVER['HTTP_HOST'] . $port . $path .'/'. googleAnalyticsGetImageUrl();
    

    Now that the URL is built, we need to send a GET request to it. This GET request will set the cookie and the user-agent then load the URL just as if it were an image being called from a web browser. The image itself never gets displayed, but the fact that it gets loaded means the tracking data is sent off to Google’s servers for your Analytics account.

    $options = array(
      "http" => array(
          "method" => "GET",
          "user_agent" => $UA,
          "header" => "Accept-Language: " . 
                      $_SERVER["HTTP_ACCEPT_LANGUAGE"] . "\r\n".
                      "Cookie: __utmmobile=" . $cookie . "\r\n"
          )
    );
    $data = file_get_contents($url, false, stream_context_create($options));
    

    Putting it all together, we have the following code, added to the top of any Tropo PHP web application:

    <?php
    require_once 'TropoClasses.php';
    require_once 'ga.php';
    $session = new Session();
    // Create a User-Agent string for the area code.
    $UA = 'Area code '. substr($session->from['id'],1,3);
    // Create a user ID cookie based on the callerid
    $cookie = "0x" . substr(md5($session->from['id']), 0, 16);
    // Build a tracking URL
    $protocol = $_SERVER['HTTPS'] == 'on' ? 'https' : 'http';
    $port = ($_SERVER["SERVER_PORT"] == "80") ? "" : (":".$_SERVER["SERVER_PORT"]);
    $path = dirname($_SERVER['REQUEST_URI']);
    $path == '/' ? '' : $path;
    $url = $protocol .'://'. $_SERVER['HTTP_HOST'] . $port . $path .'/'. googleAnalyticsGetImageUrl();
    $options = array(
      "http" => array(
          "method" => "GET",
          "user_agent" => $UA,
          "header" => "Accept-Language: " . 
                      $_SERVER["HTTP_ACCEPT_LANGUAGE"] . "\r\n".
                      "Cookie: __utmmobile=" . $cookie . "\r\n"
          )
    );
    $data = file_get_contents($url, false, stream_context_create($options));
    ?>
    

    You can even turn it into an include and stick it at the beginning of all your calls.

    Once this is added, any calls to your app will be recorded by Google Analytics and will show up in your reports alongside your web traffic.

    If you want to track specific data in your application, one technique you could use is to set the query string to include the information you want to appear in Analytics. Just add this code somewhere before you call googleAnalyticsGetImageUrl().

    $_SERVER["QUERY_STRING"] = urlencode('Your data here');
    

    Think about what you want to track in your app. Have a menu-driven IVR? Perhaps you can track each step of the menu. Have different phone numbers you’re using for different locations and want to know which one is getting used more often? Shove $session->to['id'] into your query string.

    A PHP library for Tropo’s Web API

    Friday, June 25th, 2010

    This is a guest post from Mark Headd, introducing a PHP library for the Tropo WebAPI.

    A few months back, I wrote a series of posts on building NoSQL telephony applications with Tropo and CouchDB. Today I’m going to start a continuation of that series, focusing on how to build cutting edge cloud communications apps with the Tropo WebAPI.

    What is the Tropo WebAPI?

    The Tropo WebAPI is, in a nutshell, an HTTP/JSON API for building multi-channel communication applications – applications that you interact with via phone, IM, SMS or Twitter. While my earlier series on Tropo focused on building applications in Tropo’s scripting environment (another fine option for developers), this series will focus on building JSON-based applications (generated using PHP) that can be hosted anywhere and executed in the Tropo cloud environment.

    The Tropo service is truly multi-channel – using the Tropo WebAPI you can build applications that work on a range of different communication channels, not just phones (although you can build some pretty slamming phone apps as well).

    Since I’m a phone app developer at heart, some of the features that Tropo provides for phone applications really get me excited. Tropo supports both DTMF entry and speech recognition. It also has broad multilingual support. In addition, Tropo gives phone application developers the ability to manipulate SIP headers, an important feature in building sophisticated cloud communication apps that I hope to demonstrate down the road a bit.

    Getting Started

    Head on over to Tropo.com and set up a new account (if you don’t have one already). Take a little time to review the documentation for the Tropo WebAPI. For the example applications in this series of blog posts I’ll be using a PHP class library I developed specifically to interact with the Tropo WebAPI.

    The crew behind Tropo have provided a Ruby Gem for interacting with the Tropo WebAPI. However, since I like to do my cloud telephony work with PHP I decided to write my own set of classes for doing this. Whether you’re a Ruby-head or a PHP enthusiast, using one of these tools to generate JSON for consumption by the Tropo WebAPI can make build an application significantly easier, particularly as you get into more sophisticated application development.

    You can get my PHP Library, as well as some of the sample apps we’ll be looking at, from GitHub:

    $ git clone git@github.com:tropo/tropo-webapi-php.git

    Or download a Zip file with the library.

    You’ll need to host these classes and the PHP scripts you write with them on a server that can be accessed from the Tropo environment. Any web server that supports PHP will do.

    My First Tropo WebAPI Application

    Let’s start with the standard Hello World app:

    <?php
    
    // Include Tropo classes.
    require('path/to/TropoClasses.php');
    
    // Create a new instance of the Tropo object.
    $tropo = new Tropo();
    
    // Add a prompt to the object using the Say() method.
    $tropo->Say("Hello World!");
    
    // Render the JSON for the Tropo WebAPI to consume.
    $tropo->RenderJson();
    
    ?>
    

    You can look at the rendered JSON in your browser, and you should see something like this:

    {
        "tropo": [
            {
                "say": [
                    {
                        "value": "Hello World!"
                    }
                ]
            }
        ]
    }
    

    Go to the Applications section in your Tropo account and set up a new WebAPI application that points to the location of this script.

    When you create your application, Tropo will automatically provision a Skype number, a SIP number and an iNum. You can additionally add a PSTN number in a range of different area codes at no charge.

    You may also notice the section below the provisioned phone numbers entitled “Instant Messaging Networks” – this section allows you to set up any number of different IM accounts (and Twitter!) that your application can use. We’ll dive deeper into this in future posts.

    For now, we’ll keep it simple and use the auto provisioned Skype number – when you call this number, you will hear it say “Hello World.”

    The next post in this series will focus on a more sophisticated application that uses the TropoPHP classes and the utterly awesome Limonade PHP framework.

    Stay tuned…

    About the author: Mark J. Headd is an experienced voice, mobile and web application developer who has been certified as a VoiceXML Application Developer by the VoiceXML Forum. He currently works as a Senior Application developer for Tele-Works, Inc., which develops IVR solutions and software for local government across the country. This post originally appeared on Mark’s blog.

    Processing recordings with PHP

    Thursday, June 10th, 2010

    When you tell Tropo to record audio, either through a call recording or by using the record command to record a specific prompt, Tropo then sends that audio to your server. You can give Tropo FTP credentials and we’ll FTP it over to you, or you can give an http URL and we’ll make an POST to that URL containing your file.

    When Tropo POSTS an audio file, we submit it as multipart form data, so the same tools you’d use to process a file upload field on a form can be used to save your recording. The form field name Tropo uses for the file is “filename“.

    Here’s an example using the Tropo WebAPI, PHP, and the PHP WebAPI library. In this example, I’m building a simple voicemail recorder, asking the caller to leave a message at the beep, and then saving the recorded audio to my server.

    I’m also introducing some logging, using the excellent KLogger class to write a log file every time we save a recording.

    First, a walkthrough of the important parts of the code, then a link to the full code at the end.

    <?php
      $tropo->record(array(
        'say' => 'Leave your message at the beep.',
        'url' => getself() . '?record', // append ?record to the URL
        ));
    
    function getself() {
     $pageURL = 'http';
     $url = ($_SERVER["HTTPS"] == "on") ? 'https' : 'http';
     $url .= "://" . $_SERVER["SERVER_NAME"];
     $url .= ($_SERVER["SERVER_PORT"] != "80") ? ':'. $_SERVER["SERVER_PORT"] : '';
     $url .= $_SERVER["REQUEST_URI"];
     return $url;
    }
    ?>
    

    Create a recording prompt, saying “Leave your message at the beep.” Tropo has a beep parameter that you can use to turn off the beep if you want. It’s on by default, and we want to leave it on here. We also add the URL where we’d like to send the recording using a simple function that gives us the full URL of the current application. Appended to the URL is ?record, a flag we’ll use to see if the request to our app is an incoming call or a call recording being posted.

    This PHP code generates the follow JSON that’s sent to Tropo:

    {
        "tropo": [
            {
                "record": {
                    "say": {
                        "value": "Leave your message at the beep."
                    },
                    "url": "http://example.com/recordingdemo.php?record"
                }
            }
        ]
    }
    

    So now to save the file…

    <?php
      $target_path = 'path/to/recording/' . $_FILES['filename']['name'];
      if(move_uploaded_file($_FILES['filename']['tmp_name'], $target_path)) {
        $log->LogInfo("$target_path [{$_FILES['filename']['size']} bytes] was saved");
      } else {
        $log->LogError("$target_path could not be saved.");
      }
    ?>
    

    In this code, which we only run if the ?record flag is present, we use PHP’s global $_FILES array to fetch the file data out of the multipart form post. We start by setting the path and filename we’d like to use for saving the file (line 2) using the filename that Tropo gives us in $_FILES['filename']['name']. Then in line 3, we move the uploaded file from the temporary location that PHP stores a new upload in to the path we chose. If the file is moved successfully, we write a log entry with the path and file size (line 4). If an error occurred, we note that in the log on line 6.

    To get the whole sample code, grab the Tropo WebAPI PHP library from github and look in the Samples directory or just grab the sample off Github directly.

    tropo-webapi-ruby Gem v0.1.8 Released

    Friday, May 14th, 2010

    We have made a few enhancements to the tropo-webapi-ruby gem today:

    • You may now set a default ‘voice’ for speech synthesis/text-to-speech for an object
    • You may now set a default ‘recognizer’ for speech recognition/asr for an object
    • The gem is now compatible with Ruby MRI v1.8.6
    • Unit tests pass on Ruby MRI v1.8.6/v1.8.7 and JRuby v1.5.0

    To take advantage of the new default voice capability, you simply set it as follows:

    t = Tropo::Generator.new(:voice => 'simon')
    t.say 'Hello there!' # This will now render with the UK British voice Simon
    t.response
    
    # or
    
    t = Tropo::Generator.new
    t.voice = 'simon'
    t.say 'Hello there!' # This will now render with the UK British voice Simon
    t.say 'What time is it?', :voice => 'kate' # You may still overwrite the default on a method basis
    t.response
    

    To take advantage of the new recognizer capability, you simply set it as follows:

    t = Tropo::Generatory.new(:recognizer => 'fr-fr')
    t.ask 'Bonjour!', :voice => 'florence' # This will now use the French speech recognition engine
    t.response
    
    # or
    
    t = Tropo::Generatory.new
    t.recognizer = 'fr-fr'
    t.ask 'Bonjour!', :voice => 'florence' # This will now use the French speech recognition engine
    t.ask 'What time is it?', :recognizer => 'en-gb' # You may still overwrite the default on a method basis
    t.response
    

    The gem has already been posted to Rubygems.org. Enjoy!

    WebAPI: Now with outbound and transcription

    Thursday, May 6th, 2010

    When we released the new WebAPI last month, two things were missing. You couldn’t make an outbound call and transcription wasn’t available for recordings. Today we’ve added some things to make working with text and IM easier and brought parity to the Web and Scripting APIs, ensuring both have all the same features. So whether you want to host yourself and communicate over JSON or like the simplicity of our hosted Scripting API, you can do all the same things.

    Here’s what’s new:

    • Outbound calls no longer require “Channel” parameter.
    • Quickly send a text message with new “message” feature
    • Outbound calling and messaging from the Web API
    • Transcriptions on the WebAPI
    • Sweden and Italy

    No Channel required

    When sending a text message or instant message, you need to provide call() with the network you want to send it out on. Previously we required you to also tell us if it was a voice or text channel. Obviously, if it’s an SMS message, it’s a text channel and not voice, so we’ve added defaults to the channel parameter. Now you can save a few keystrokes and just do this (JavaScript shown):

    call('tel:+14075551212',{network:'SMS'});
    

    Send a Message()

    One thing people use Tropo’s text features for a lot is alerting. Sending a quick message out used to require that you set up a call, then say() something on that call and finally hang up the call. You can still do that if you want, but now you can do it all in one step;

    <?php
    message("Home team just scored. It's now Home: 4, Visitors: 1", array('network'=>'SMS', 'to'=>'14075551212'));
    ?>
    

    Quick and easy, just fire off a message. This also comes in very handy if you want to fire of a text message while your application is on a voice call.

    <?php
    answer();
    say('Thanks for calling the Tropo information service. Sending you a text message now.');
    message('Here is what you were looking for...', array('network'=>'SMS', 'to'=>$currentCall->callerID));
    ?>
    

    For reference, you can take a look at the message docs on either the Scripting or WebAPI.

    Outward Bound

    The session API can now kick off a WebAPI call. When you pass in the token for your WebAPI application, Tropo will now POST the JSON for the call to your URL so you can handle it. You can now respond to these POST requests with a new call element in the JSON.

    {"tropo":[
       {"call":{
           "to":"tel:+13055195825"
       }},
       {"say":{
           "value":"Welcome to Tropo."
       }},
    ]}
    

    For a full list of what options you can provide the call element, check out the WebAPI documentation for Call and the Session API.

    Transcriptionist

    When you record a caller’s input, you can now request that it be transcribed to text. Our transcription API can email you the text of the recording or POST it to the URL of your choosing.

    {"tropo":[
       {"record":{
            "beep":true,
            "say":{
                "value":"I'm not here right now. Record your message after the beep."
            },
            "transcription": {
                "url":"mailto:you@example.com"
            }
        }},
    ]}
    

    You can even pass in an ID that we’ll give to you when we hand you the transcription so you can tell different transcriptions apart. As always, the docs have the details on how to use a URL instead of email and all the other options you’ve got.

    The new features are available for development applications today. The production servers will get upgraded in the near future, after we’ve seen the new code put through its paces on some developer applications.

    And finally, we’ve added numbers in Sweden and Italy to our pool, allowing developers to purchase local numbers in those countries. Like elsewhere outside the US, these numbers can only be added to production accounts.

    Using the Tropo Web API behind a firewall with Tunnlr

    Wednesday, February 24th, 2010

    Many times we find ourselves sitting behind networks without the ability to open a TCP port to hack on our web services. This may be at a coffee shop, a corporate network or that guest network you just connected to at your developer meetup. We have a solution for that.

    In steps Tunnlr, a great little service by the folks at ElevatedRails. With Tunnlr, you are able to create a reverse SSH tunnel to a port on your computer. While they do have a plug-in for Ruby on Rails, this may be used to redirect traffic to any application running on a port. In this example I will walk you through how to do this using another Ruby web framework, Sinatra.

    The first step is to sign-up for a Tunnlr account. You may select a single plan for USD$5 per month, but you get a 90-day free trial with no credit card required at sign-up. Once you have signed-up and verified your account, they will then provide you with a URL to use to access your tunnel. You will also need to provide them with your public SSH key in your account.

    Tunnlr

    Once you have this setup, then you need to create the tunnel from your computer. I created a shell script that I may run each time I want to have a tunnel.

    create_tunnel.sh

    Then, fire up your tunnel in a terminal window. Terminal — ssh — 80×24

    Now that the hard part is over, write a Sinatra (or any others) app using our Tropo-WebAPI-Ruby gem and run it on the port you specified in your shell script above.

    tunnlr_sample.rb

    Thats it, now your Tropo WebAPI app is ready to run behind any firewall. Now you may demonstrate Tropo at that next developer meetup!