Posts Tagged ‘webapi’

Node.JS Magic 8 Ball Voice App

Friday, December 23rd, 2011

Remember the Magic 8 Ball game from yesteryear?

How would you like to have the game with you in your pocket when difficult answers are required.

I built this Magic 8 Ball game using Node.JS and the Tropo WebAPI. If you roll the array up to a single line of code, you’re only looking at a 25-line Node.JS application!

You can call this application at 415-889-8684!

Here is the Node.JS source code that runs the application.

var http = require('http');
var tropowebapi = require('tropo-webapi');

// http://en.wikipedia.org/wiki/Magic_8-ball
var answers = [
"It is certain",
"It is decidedly so",
"Without a doubt",
"Yes – definitely",
"You may rely on it",
"As I see it, yes",
"Most likely",
"Outlook good",
"Signs point to yes",
"Yes",
"Reply hazy, try again",
"Ask again later",
"Better not tell you now",
"Cannot predict now",
"Concentrate and ask again",
"Don't count on it",
"My reply is no",
"My sources say no",
"Outlook not so good",
"Very doubtful"
];

http.createServer(function (req, res) {

	// Create a new instance of the TropoWebAPI object.
	var tropo = new tropowebapi.TropoWebAPI(); 	
	var answer = answers[Math.floor(Math.random()*answers.length)];

	tropo.say("Welcome to the tropo node J S magic 8 ball.");

	var say = new Say("Ask your question now after the beep.");
    var choices = new Choices(null, null, "#");

    // Action classes can be passed as parameters to TropoWebAPI class methods.
    // use the record method https://www.tropo.com/docs/webapi/record.htm
    tropo.record(3, false, null, choices, "audio/wav", 5, 60, null, null, "recording", null, say, 5, null, "http://example.com/tropo", null, null);

    tropo.say(answer);

	tropo.say("Please call back to play again!");

    res.writeHead(200, {'Content-Type': 'application/json'}); 
    res.end(tropowebapi.TropoJSON(tropo));

}).listen(13188);

Be careful what you ask for…

Sending outbound SMS with Java

Friday, May 6th, 2011

Tropo’s Java API allows you to send SMS messages from your Java applications with little or no effort. In this blog post I’ll go through a very simple application that sends an SMS message with very few lines of code.

To make it a little bit more exciting I will use Quartz‘s latest version. If you are not familiar with it, Quartz is a task scheduler library that you can use in Java to schedule and execute tasks. It is a very powerful library that has tons of different configuration options and integrates quite well with different application servers. Java veterans know it very well as it has been there almost from the very beginning. As Quartz was releasing a major upgrade this March, I decided to test how it works. I also thought that delivering scheduled messages would be a great real-life example of how Tropo can be useful for you. Imagine for example you can use to do SMS broadcasting, send advertisements, send alerts on health monitoring applications and many more exciting use cases.

So let’s start. The first step is to create your application. If you are familiar with Tropo’s WebApi model and in particular with the Java library ( if not, you can have a look to this introductory screencast ) you may expect that we would create a WebApi based application. But this is not the case. We are going to take advantage of Tropo’s Java API REST implementation to make it super-easy to send SMS messages. What we are going to do is to create a script in Tropo that will send the SMS message, get a session token, and invoke that tropo script from our Java application using the session token. So, let’s go. The first step is to create a Scripting based application:

Next, give it a name, like for example QuartzTest and click on the “use a Hosted File” link and next click on the “Create a new hosted file for this application” option, like is shown in the screenshot below:

Ok, we are almost there. Now you need to enter the script contents. This script will send the actual SMS outbound message. I will use the message function and pass the message text and the phone number as parameters. At the docs section you will find plenty of information about all the functions and cool actions you can execute from Tropo scripts. As you can see in the screenshot below, our script is super simple:

Ok, so once you have created your application the last step you need to do is to get your Session API token. We will use that token from Java to run the script that we just have created. So, to get access to your token you only need to go to your application screen and click on the Voice link (message token is also valid) at the bottom of your application. A new window will pop up showing your token information:

And that is it. Let’s go now to the Java world. I’ve created a very simple Java project that uses Quartz and invokes our new and shiny tropo script. I’ve uploaded this project to Github. You can find the source code on this link. Feel free to browse the project sources. As you will see, we are using Tropo’s Java Webapi binary libraries that you can find here. And there is just only two classes. One is the scheduler that creates a quartz job and sends it (I wont go into this code, as it is just some Quartz specific stuff). And the second class is the actual job that sends the SMS message using Tropo. Lets have a look to that class:

public class LongJob implements Job {

	@Override
	public void execute(JobExecutionContext arg0) throws JobExecutionException {

		try {
			// This coude launches your Tropo application. You can configure your tropo application to 
			// do things like sending an SMS, calliing a phone, etc. 
			String token = "f46f1f14bdd7684d9195ad83e1bbce021d0f024ad5e56e8c99cbd10e9cf3b2b026cb68749b41cb487dd09a5d";
			Tropo tropo = new Tropo();
			Map<String, String> params = new HashMap<String, String>();
			params.put("message","This is an SMS message");
			params.put("numberToDial", "+34637710708");
			tropo.launchSession(token, params);		

		} catch (InterruptedException e) {
			e.printStackTrace();
		}		
	}
}

That is all the code you need to send an SMS message from Java. Isn’t it cool? Lets go through the different parts of that snipped:

  1. First we create a new Tropo instance. The Tropo class drives all the interactions with the Tropo cloud.
  2. Next, we build a set of parameters. If you remember our script, we need to pass the message and the number that we are sending the message to. All the keys that you put on that params map will be accessible from your script.
  3. And finally we launch the session using the launchSession method. That method will use our token to launch remotely the Tropo script that we created previously. The script will fetch the parameters from the map and will send the SMS message.

Feel free to download and run the example. One word of caution though. Tropo supports international SMS delivery which is very cool. But it could happen that your country could have not been enabled yet. So, if you find that the SMS messages aren’t getting into your phone then let us know about it because we would have to enable SMS delivery to that country through one of our multiple carrier agreements.

And that is it. Hope you have fun with Tropo and Java!

Deploying Tropo Apps with Orchestra.io

Friday, April 22nd, 2011

On a visit to Nashville, Tennessee, for the PHP Community Conference (Tropo is one of the sponsors) I got to hear a talk from Helgi Þorbjörnsson on front-end caching techniques.

During his talk Helgi mentioned a new Git-based deployment service for PHP applications – Orchestra.

Orchestra is very similar to other Git-based deployment service for different langages – Heroku for Ruby, and Nodester for Node.js – but it’s meant to support deployment of PHP-based applications.

If you’re like me, and you missed the chance to take part in the Codeita beta, you’re anxious to give a Git-based deployment service for PHP a try. When I checked out Orchestra, it looked incredibly easy to use, and a snap to get started with.

It’s also an excellent match for Tropo applications written with our PHP class library for WebAPI.

How easy is it to use Orchestra to deploy a PHP-based Tropo app?

I was able to write, deploy and test an app before Helgi had finished his presentation at the PHP Community Conference (about 20 minutes total with conference-grade wifi). I was even able to hear the end of Helgi’s talk.

Here is how I did it.

Building a Tropo WebAPI App

I built a very simply Tropo application using the PHP class library WebAPI.

My sample application is meant to answer an incoming call, ask the caller what their favorite programming language is (along with some choices), and then say something snarky based on their response.

Building a speech recognition app like this with Tropo is very easy. I also made use of the awesome Limonade PHP framework for my app.

All of the code for this app is made available on GitHub, which is also part of the process for deploying apps to Orchestra.

Setting up and Deploying to Orchestra

Orchestra settings

Go to the Orchestra site and create a new account. Take a spin through the knowledge base if you want more specifics on how everything works – you have two deployment options, a free deployment or an elastic deployment.

For the purposes of this post, I’ll use a free deployment.

You deploy your application to Orchestra by connecting a repo on GitHub with your Orchestra account – Simply set up a GitHub repo for your app, just as you would for a normal project. You’ll then use information about this repo to set things up in Orchestra.

When you tell Orchestra where your GitHub repo is, it will deploy your app and give you a public URL that you can use to access it.

Setting up a Tropo Application

Now that our application is deployed to Orchestra, we need to set up a phone number to use it in Tropo. Like all of the steps described above, this one is simple.

Log into your Tropo account and create a new application – when prompted select WebAPI. The URL that powers your application is the public URL provided by Orchestra when you deploy your application.

Since we’re using Limonade, we need to add a query string parameter for our starting route.

In our application, our starting route looks like this:

dispatch_post('start', 'tropoStart');
function tropoStart() {
 ...
}

So to access this route from Tropo, we would set up our app URL like this.


http://my-app-name.orchestra.io/index.php?uri=start

When you do this, you’ll be able to call the application and hear it work. Here is a quick screencast demonstrating how the app works.

One of the things I really like about Orchestra is that it uses a standard GitHub repo for deployment. Similar services for other languages often require you to set up a special stand alone repo for deployment, and for me this just always feels like an extra step I have to go through to deploy my app.

I love that I can push changes to GitHub and they are deployed by Orchestra. Quick and easy!

Orchestra has a number of add ons planned (i.e., for CouchDB and MongoDB) so it’s only going to get more awesome.

So if you want a fast, easy way to build powerful multi-channel communication apps in PHP, Tropo and Orchestra make a powerful combination.

Voice powered applications with Grails (Screencast)

Wednesday, April 20th, 2011

Grails Logo Hi. In a previous post we announced our new and shiny Grails Webapi library that allows all Grails developers to create voice and SMS powered applications very easily from their Grails applications.

If you go to the plugin’s web page at Grails.org you will find that there is already quite a few documentation out there. But I thought it would be quite useful to publish a screencast showing step by step how to create applications. This can be very interesting specially for developers that are not used to the Grails platform.

So here it is. It is a very short 15 minutes video in which I’ll show you how quick and easy you can create voice applications in Grails. I really hope you like it.

Control Your Tropo Scripts with External Events

Thursday, January 20th, 2011

A few weeks back, Adam Kalsey introduced an exciting new piece of functionality on the Tropo platform – the ability to control a Tropo script by injecting events into a running session.

This type of functionality has lots of very cool applications – you can break a caller out of a long running process, or stop an executing action like a conference or a transfer. And what’s even cooler, now you can have access to all of this functionality through the existing Tropo WebAPI library for PHP.

Here is a quick example to demonstrate how to use external events to interrupt an executing action – in this case, an inbound call to a Tropo script that performs a transfer to another number.

Say, for example, that you wanted to limit the amount of time that a caller could stay on the transfer. With external events, it’s a snap.

Consider the follow sample script.

// Include required classes.
require 'classes/tropo.class.php';
require 'classes/sag/sag.php';

// Grab the raw JSON sent from Tropo.
$json = file_get_contents("php://input");

// Create a new Session object and obtain the session ID value.
$session = new Session($json);
$session_id = $session->getId();

// Insert the Session object into a CouchDB database called sessions.
try {
	$sag = new Sag();
	$sag->setDatabase("sessions");
	$sag->put($session_id, $json);	
}
catch (SagCouchException $ex) {
	die("*** ".$ex->getMessage()." ***");
}

// Create a new Tropo object.
$tropo = new Tropo();

$tropo->say("Please hold while your call is transferred.");
$tropo->transfer("5551112222", array("from" => "7861112233", "allowSignals" => "transferOver"));

// Set event handlers
$tropo->on(array("event" => "continue", "next" => "hangup.php?uri=end&timeout=false"));
$tropo->on(array("event" => "transferOver", "next" => "hangup.php?uri=end&timeout=true", "say" => "You have reached the time limit. Transfer over"));

// Render JSON for Tropo to consume.
$tropo->renderJSON();

As you can see, I’m using a property of the WebAPI Transfer object called “allowSignals” and giving it a value of transferOver. This is the name of the external event we want to send to our script. When it is received, our Tropo script will end execution of the transfer and invoke the handler set up for the transferOver event.

In order to control a Tropo script with external events, we need to know the unique ID for the session the Tropo script is executing in. We can get this from the Session object which is sent to our script at the inception of the call.

$session = new Session($json);
$session_id = $session->getId();

We want to store this session ID somewhere so that we can access it when we want to end an outbound transfer that has gone on longer than some set time interval. For the purposes of this example, I’m just going to stick it into a running instance of CouchDB. Since the session ID for our Tropo script is globally unique, we can use it as the document ID for our CouchDB document.

In this example, I’ using the very handy Sag CouchDB library for PHP. It’s dead simple, and makes working with CouchDB from PHP a snap.

For this example, I’m using a fresh CouchDB database named “sessions.” Because we want to insert a CouchDB document with a specific document ID, we’re going to do an HTTP PUT – we do this by simply invoking the put() method of the sag object:

$sag = new Sag();
$sag->setDatabase("sessions");
$sag->put($session_id, $json);	

Now we can send a transferOver event to the session running our Tropo script. This is easy to do with the new sendEvent() method of the Tropo class.

Here is a simple script that uses this method to send an event to a running script:

#! /usr/bin/php
<?php

if(empty($argv[1])) {
	die("*** You must use a Session ID with this script ***\n");
}

$session_id = $argv[1];
$event_name = $argv[2];
$path_to_classes = $argv[3];

require $path_to_classes.'/tropo.class.php';
$tropo = new Tropo();

try{

	if($tropo->sendEvent($session_id, $event_name)) {
		echo "Event { $event_name } successfully queued.\n";
	}
	else {
		echo "ERROR: Could not queue event { $event_name }.\n";
	}

}

catch(TropoException $ex) {
	die("*** There is big trouble in River City: ".$ex->getMessage()." ***");
}

After you make this script executable, you simply invoke it by:

  • Giving it the id of the session to send an event to;
  • The name of the event to send, and;
  • The path to the Tropo WebAPI library files.

When invoked, it will generate a response like this:

{"status": "QUEUED"}

This means that the event is queued and will be delivered to the session that is running our script.

When the event is delivered to the script, it interrupts the ongoing transfer and causes a Result object to be sent to the URL specified in the transferOver event handler. The JSON for the Result object looks like this:

{
    "result": {
        "sessionId": "bc9fe7edf356cfa045cf6d814ff07bf1",
        "callId": "b7feb41c8e50768733a8875713d5541e",
        "state": "ANSWERED",
        "sessionDuration": 94,
        "sequence": 1,
        "complete": true,
        "error": null,
        "actions": {
            "disposition": "EXTERNAL_EVENT"
        }
    }
}

Note the disposition value in this object – EXTERNAL_EVENT – this lets your application know that the result was caused by an external event being injected into the Tropo session.

This functionality opens up a host of new avenues for Tropo developers to build sophisticated applications.

We’ll be adding this functionality to other Tropo libraries in the days ahead, and if you use Tropo scripting it’s already available to you.

Have fun!

Python Tropo WebAPI Library Now Available in PyPI for Easy Installation

Wednesday, January 5th, 2011

Python logoI’m pleased to announce that we’ve made it even easier for people to install the Tropo WebAPI library for python. (This lets you build apps that are hosted on your local system that communicate with Tropo for voice/SMS/IM/Twitter connectivity.)

Last night I uploaded the module to PyPI, the python package index, and as a result you can now simply type this command to install the latest version:

easy_install tropo-webapi-python

This assumes, of course, that you have the setuptools package installed, but that should be available in most python installations. (And if you don’t have it, you can get setuptools from PyPI and follow the instructions there.)

Alternatively, if you prefer to use the newer pip replacement for easy_install, you can type this command:

pip install tropo-webapi-python

(And pip is also available from PyPI if you want to trying using it versus easy_install.)

If you want to see the PyPI page describing the Tropo WebAPI library, it is at:

http://pypi.python.org/pypi/tropo-webapi-python/0.1.0

We’ll make sure to upload a new version after there have been any real changes to the python library. The definitive source will of course always be at the tropo-webapi-python Github page, but we’ll aim to make sure that the PyPI version tracks closely.

Many thanks to developer Randall Degges who raised an issue on Github asking if we could upload the library to PyPI. Thanks, Randall, for the suggestion!

P.S. Feel free to raise issues on Github with your suggestions (or fixes), too!

Naked Node.JS

Tuesday, December 14th, 2010

Mark Headd recorded an awesome screencast on getting Tropo running on Node.js using the Tropo Node.js library.  While libraries make code easier to write, I wanted to see what was happening under the covers when writing a Tropo application using Node.js without any magic.

This experiment was easier that you may think!  Since Tropo speaks JSON natively, all you need to do is spin up a node.js server like the hello world demo on the node.js home page. Next substitute “application/json” for Content-Type and send Tropo JSON text in place of hello world as shown below:

var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'application/json'});
  res.end('{"tropo":[{"say":[{"value":"This call is running from node J.S. Have a nice day. Goodbye."}]},{"hangup":null}]}');
}).listen(3000, "127.0.0.1");
console.log('Server running at http://127.0.0.1:3000/');

Next, deploy this script to your node.js hosting provider or run Tunnlr as demonstrated by Mark and create a new Tropo WebAPI application pointing at the deployed URL.  Now call your application and listen to Node.js in action.

There you have it – Naked Node.JS!

Get Your Node on with Tropo and Node.js

Thursday, December 9th, 2010

Node.js is a framework for writing server side JavaScript applications.

This video will provide an overview of how you can use Node.js, Tunnlr and the Tropo Node.js module to quickly and easy create powerful, sophisticated multi-channel communication applications.

Building communication apps in pure JavaScript has never been easier!

New tropo-webapi-ruby Gem Released

Friday, October 15th, 2010

We have just released the latest tropo-webapi-ruby v0.1.9 gem to RubyGems.org. This release includes the following updates:

  • Fixed the start_recording so it does not require a ‘name’ parameter
  • Aliased start_call_recording -> start_recording
  • Aliased stop_call_recording -> stop_recording
  • Fixes to the README
  • Fixed the yardoc install
  • The Tropo::Generator.parse method will now take a JSON string or a Ruby hash.
  • Fixed the start_recording so it does not require a ‘name’ parameter- Aliased start_call_recording -> start_recording- Aliased stop_call_recording -> stop_recording
  • Fixes to the README- Fixed the yardoc install- The Tropo::Generator.parse method will now take a JSON string or a Ruby hash.

To install the latest gem simply do ‘sudo gem install tropo-webapi-ruby’.

Tropo Now Speaks Asterisk Gateway Interface (AGI)

Friday, October 1st, 2010

The Asterisk community is a vibrant one, one that we actively support through our sponsorship and advocacy of Adhearsion. We have decided to take it a step further and created a Tropo Scripting application that turns Tropo into a giant Asterisk application platform in the cloud.   You can now run just about any Asterisk AGI application on Tropo.

Tropo AGItate was started on the Nerd Bird (good to have in-flight WiFi) from San Jose to Austin, on my way to LoneStar Ruby Conference. Jim Freeze – the organizer of LSRC – had recently been to AdhearsionConf in San Francisco; I wanted to be able to show something extra special during my talk there. On that one flight, I was able to get the basics working and show Tropo emitting AGI during my talk, just like that. (For those non-Asterisk folks out there, AGI is an API that lets external applications connect in to Asterisk and fully control it).

Since then, it’s been fun working on the application and expanding its capabilities. With Tropo AGItate, you could build your own interactive art display, a full blown cloud PBX like OpenVoice, or add Tropo capabilities to your own Asterisk server. The key features coming out today are:

  • Tropo can now speak AGI over TCP to any FastAGI server, including Adhearsion, PHPAGI, Asterisk-Java, etc.
  • A long list of Asterisk commands are supported, and of course all the Tropo ones.
  • While the script is written in Ruby, no Ruby knowledge is necessary to use it. Just point your Tropo application to the Ruby script on Github, upload a configuration file via FTP or WebDAV to your Tropo account, and you are ready.
  • Full support of Tropo Speech-Synthesis (TTS) and Speech-Recognition (ASR), but also for Asterisk sound files. Yes, tt-monkeys works!
  • Fail over to a SIP URI, in case your FastAGI server does not respond. This could be to another Tropo application, another Asterisk box, or anything that supports SIP.
  • You get all of the Tropo channels over AGI, including SMS, Instant Messaging and Twitter, all using the same application.
  • Support for custom SIP Headers in and out of Tropo.
  • And much more, with more to come…

Not only can you use AGI to write an entire cloud communications application, but you can also seamlessly integrate Tropo services into existing Asterisk systems using the interface you already know and love; after-all, its all SIP to us.

If you want to hear a Tropo AGItate ‘hello world’, give it a ring:

  • Phone/SMS: (408) 641-4410
  • Skype: +990009369991456829
  • SIP: sip:9991456829@sip.tropo.com
  • Jabber/XMPP: tropo_agitate@tropo.im

While this is great for all of the Asterisk developers out there, it also gave us the opportunity to showcase the power of the Tropo Scripting API. Tropo AGItate is 100% Tropo Scripting, no special libraries, no tricks, its all right there in the script. Tropo Scripting allows you to bend the Tropo cloud to your will; this is what we believe is truly innovative about our platform.

Stay tuned for more! We will be providing howtos, screencasts and more features soon.