Thursday, March 12, 2009

Twilio Responses made Super Easy

In case you haven't heard of it, Twilio is a super cool, super easy to use and program voice service started last year. It is basically a full on PBX system that you can program very easily with and can scale to handle any demand you can throw at it, as it is built using Amazon's cloud infrastructure.

(Side node: I'm very jealous of it. This is exactly the kind of cool yet simple thing I wish I could think of!)

While the Twilio folks have provided libraries for their REST API, the "response" side of the equation is left completely up to you to form. This is very easy to do; the easy with which you can do this is, in fact, key to how simple the service is to use in general. However, I don't like writing code that concatenates xml strings together, nor do I want to use the heavy-handed xml libraries that are out there to simply print results like "Doggies are cute!". One key thing on "hand crafting" the xml responses is that you have to remember to encode any special xml characters. If you are using any sort of user-input values to generate this xml, then you have to be constantly aware of this and escape everything.

So, to the point, I wrote a simple PHP class (2 classes, really) and dropped them over on the ledscripts google code page. This basically allows you to general the xml needed in a fashion similar to the "flow" you are outputting yourself. Let's look at an example.

To generate a simple response, you can do something like this:


$response = new TwilioResponse();
$response->Say('Doggies are Cute');
$response->Respond();


(I know it is more lines, but it makes more sense and gets cooler).

Let's look at a better example (easier to read here):

$response = new TwilioResponse();

$response->Say('this is a test, my friend',
array('voice' => 'woman', 'loop' => 2)
);

// Gather, with the alternate method of doing verbs (as a "get" that can be passed as sub-verbs)
$response->Gather(
array(
$response->GetVerb(TwilioResponse::V_SAY, 'Thank you for calling. Please press 1 for more options'),
$response->GetVerb(TwilioResponse::V_PAUSE),
$response->GetVerb(TwilioResponse::V_SAY, 'Go on. Press something')
),
array(
'action' => '/handle-response.php?a=b&c=d', // note that the & here must be encoded... the library takes care of it!
'numDigits' => 1
)
);
$response->Respond();

You can find out more in the examples folder in the repository. This may not be a perfect library, as I put it together in the course of about 1 hour, but it has worked very well for what I've done.

Let me know if any bugs are found, or if you have any requests/suggestions for improvements!

Here is the SVN page on google code. To check out just this library and the examples:
svn checkout http://ledscripts-opensource.googlecode.com/svn/trunk/libraries/php/twilio .

Labels: , , ,