Archive for December, 2011

Sending SMS to your Constant Contact list

Tuesday, December 27th, 2011

One of the nice things about Tropo is that it does a lot of the heavy lifting for you, letting you add amazing features to existing products. One very popular contact manager is Constant Contact. Since your contacts must opt-in to this service, combining this with Tropo provides you a nice way to keep in touch with them beyond simple email.

In this post I’ll describe how I created a Python script that retrieves your contact list from CC and sends them a text message using Tropo. I’m using a hosted file located on the cloud at Tropo.com for this.

What you’ll need:

Let’s start with the easy part, making a hosted Tropo application to send our users a message.

  1. Log in to tropo.com
  2. From “Your Applications”, click “Create New Application”
  3. Click “Tropo Scripting”
  4. Give your application a name
  5. For the URL, click “Hosted File” and then “Create a new hosted file for this application”
  6. Fill in the filename (in this example I’m going to use JavaScript on the Tropo side, so I chose test.js)
  7. Then just add the following 2 lines of code
call('+' + numberToDial, {
    network:"SMS"});
say(msg);

Then just click “Create File” and then “Create Application”. Once our magic monkey finishes creating your application, you will see the settings page for your application.

Next step is to add a phone number to this application. Click “Add a new phone number” and then choose your area code (Tropo only supports SMS from US and Canadian numbers at this time), then click the plus symbol to add this phone number to the application. Once your have completed these steps you’ll be taken back to the application settings page.

That’s almost all we need from Tropo. Let’s take a look at the Python code:

import urllib
import urllib2
from xml.dom import minidom
cc_url = 'https://api.constantcontact.com/ws/customers/{user_name}/contacts' cc_api_key = '{paste_your_api_key_inbetween_the_quotes}'
cc_username = '{user_name}'
cc_password = '{password}'

TROPO_URL = 'http://api.tropo.com/1.0/sessions?action=create&token={The Outbound Messaging Token goes here}'
SMS_MSG = 'Wishing you a happy holidays! - From the Tropo Team'

This first part, shown above, sets up our URLs – one for Constant Contact and one for Tropo. SMS_MSG will contain the content used as the body of your message.

#CC uses Basic Authentication for their API. This code sets up a password manager to take care of that for us
passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, cc_url, cc_api_key + '%' + cc_username, cc_password)
authhandler = urllib2.HTTPBasicAuthHandler(passman)
opener = urllib2.build_opener(authhandler) urllib2.install_opener(opener)

There's some heavy lifting going on here! Constant Contact is configured to require Basic Authentication for their API. Python provides us with a really nice password manager so we don't have to worry about encoding this into our HTTP request.

pagehandle = urllib2.urlopen(cc_url)
data = pagehandle.read()
dom = minidom.parseString(data)
entry_node = dom.getElementsByTagName("entry")

This code above sends a request to Constant Contact and parses the XML result. Each of your contacts is stored as an Entry in the XML data. What we want to do is loop over each one of these entries to get the unique ID:

for entry in entry_node:
	id = entry.getElementsByTagName("id")
	id = id[0].firstChild.nodeValue
	pagehandle = urllib2.urlopen(cc_url + '/' + id.rsplit('/', 1)[1])
	data = pagehandle.read()
	dom = minidom.parseString(data)
	contact_node = dom.getElementsByTagName("Contact")

Now we've iterated over all of our entries, and requested for the Constant Contact API to return the detailed record for each Contact. The field that we'll use to send our contacts an SMS is defined as "HomePhone" in the code below:

	for contact in contact_node:
		phone_num = contact.getElementsByTagName("HomePhone")
		phone_num = phone_num[0].firstChild.nodeValue
		url = TROPO_URL + '&numberToDial=' + phone_num + '&msg=' + urllib.quote(SMS_MSG)
		page = urllib2.urlopen(url)
		data = page.read()

Now we've parsed out the phone number for our users and requested that Tropo send them our season's greetings!

Note: If your phone numbers are not in a 10 digit format, this request will fail.
Note 2: The outbound messaging token can be found under the settings for your application.

This is something that could clearly be extended to a wide range of things: running specials, thanking customers, really the possibilities are only limited by your imagination. Also, if you wanted to have Tropo talk to the person instead of send a text message, just make the first line of your hosted application look like this:

call('+' + numberToDial);

To run this, take the script, edit it with your information and run it from a terminal window: python my_script_name.py

And here's the code in full:

import urllib
import urllib2
from xml.dom import minidom

cc_url = 'https://api.constantcontact.com/ws/customers/{user_name}/contacts' cc_api_key = '{paste_your_api_key_inbetween_the_quotes}'
cc_username = '{user_name}'
cc_password = '{password}'

TROPO_URL = 'http://api.tropo.com/1.0/sessions?action=create&token={The Outbound Messaging Token goes here}'
SMS_MSG = 'Wishing you a happy holidays! - From the Tropo Team'

#CC uses Basic Authentication for their API. This code sets up a password manager to take care of that for us
passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, cc_url, cc_api_key + '%' + cc_username, cc_password)
authhandler = urllib2.HTTPBasicAuthHandler(passman)
opener = urllib2.build_opener(authhandler) urllib2.install_opener(opener)

pagehandle = urllib2.urlopen(cc_url)
data = pagehandle.read()
dom = minidom.parseString(data)
entry_node = dom.getElementsByTagName("entry")
for entry in entry_node:
	id = entry.getElementsByTagName("id")
	id = id[0].firstChild.nodeValue
	pagehandle = urllib2.urlopen(cc_url + '/' + id.rsplit('/', 1)[1])
	data = pagehandle.read()
	dom = minidom.parseString(data)
	contact_node = dom.getElementsByTagName("Contact")
	for contact in contact_node:
		phone_num = contact.getElementsByTagName("HomePhone")
		phone_num = phone_num[0].firstChild.nodeValue
		url = TROPO_URL + '&numberToDial=' + phone_num + '&msg=' + urllib.quote(SMS_MSG)
		page = urllib2.urlopen(url)
		data = page.read()

Questions or comments? Post to our forums or send us an email to support@tropo.com.

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…

Dial and SMS your APIs with Tropo

Thursday, December 22nd, 2011

The number of APIs available are increasing by the day and so is the popularity of Node.JS, the server-side event-driven javascript framework. This got me thinking… How cool would it be to be able to call or sms an API with your phone using Node.JS?

This is a pretty simple thing to do with Tropo and Nodester. Tropo has an NPM module available for adding Voice, SMS, and Instant Messaging to Node.JS applications and Nodester has REST APIs available to report on the status of the platform. 25 lines of Node.JS code later, we now have an Node.JS application using the Tropo API to dial and sms the API to retrieve the status of the platform.

Here’s the phone number: (480) 428-8723 to call or SMS.

Install the Tropo WebAPI and Mikeal Rogers’ Request NPM modules:

npm install tropo-webapi -g
npm install request -g

Run this code on localhost or deploy it to a Node.JS hosting service like Nodester.

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

http.createServer(function (req, res) {

	// Create a new instance of the TropoWebAPI object.
	var tropo = new tropowebapi.TropoWebAPI(); 	

	// Fetch Nodester status -> http://api.nodester.com/status
	// returns {"status":"up","appshosted":2878,"appsrunning":1759}
	request('http://api.nodester.com/status', function (error, response, body) {
	     if (!error && response.statusCode == 200) {

	       // console.log(body) // Print status
	       var statusreq = JSON.parse(body);

	       tropo.say('nodester is ' + statusreq["status"] + ' and hosting ' + statusreq["appshosted"] + ' applications with '+ statusreq["appsrunning"] + ' running at the moment ');

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

}).listen(13151);

One of the really cool things about the Tropo API is that you can write your app one time and it automatically runs on multiple communications channels such as: Voice, SMS, and Instant Message.

Voice Texting With Tropo Speech & SMS Technology

Wednesday, December 21st, 2011

We all agree that texting while driving is very dangerous, right? Fred Wilson, VC and principal of Union Square Ventures thinks so too. He recently wrote a blog post that starts like this:

“As a parent of two young adult drivers and a third soon to hit the road, nothing scares me more than texting while driving.”

Fred continued his blog post envisioning a Voice Texting application as follows:

“Being an engineer at heart and by training, I’ve been looking for a solution to the problem. I know that the buzz of the phone and the unread/unresponded message is like a drug to many and that the best solution would be a “hands free” way to read and respond. And the bluetooth/hands free voice solution works so well on most cars and most phones now, so why can’t we do the same with texting?”

Having two kids of my own (1 already driving and 1 studying for a drivers permit) and having access to the Tropo API and platform, I felt compelled to build a quick Voice Texting application to share with Fred Wilson! Here is what Fred had to say upon me sharing it with him…

Here is how it works:

To send a text, call (415) 349-3120 and using Tropo speech recognition say the phone number that you would like to text and then speak your message. Tropo then transcribes the message and sends your text message to phone number you spoke without taking your eyes or hands off the road.

Disclaimer: We are not promoting texting while driving even with the proper tools that would keep your eyes on the road such as a bluetooth earpiece and autodial features.

The source code for this project is written in Ruby and open sourced on GitHub in case anyone would like to extend it or perhaps even create a new business around this idea and have a head start! Here’s a video of me demonstrating the technology in action:

Drive safely!

Tropo Customer Spotlight: Babelverse

Tuesday, December 20th, 2011

Babelverse founders Mayel de Borniol and Josef Dunne were working out of the Tropo HQ office in San Francisco when they received the call that they had been accepted to compete among 15 other startups in the Le Web 2011 Startup Competition.

With over 600 applicants and only two weeks to prepare for the competition in Paris, France, we were able to sit down with them over a few beers and discuss their game plan to win, their experience in the San Francisco and Silicon Valley for the first time, being a part of the  Start-Up Chile Program and how they used Tropo for Crisis Response to help victims of the Japan Earthquake in March 2011.

Our Babelverse boys won 3rd place in the Le Web 2011 Startup Competition and we couldn’t be more proud.  Clearly their motto of including alcoholic beverages to help their inspiration and creativity along with their faith in always somehow being in the right place at the right time helped them win in Paris.  Congratulations!

WebPulp.TV Interviews Tropo

Tuesday, December 20th, 2011

Jose de Castro, our Chief Architect, was recently interviewed by Josh Owens from WebPulp.TV on the interworkings of Tropo’s Webscale cloud communications platform.

Topics covered include:

  • scripting languages (ruby, python, php, groovy, and javascript)
  • scaling our data centers and APIs
  • message queues (rabbitMQ and activeMQ)
  • media server technology
  • VoIP and SIP QoS
  • redundant telco carriers and networks
  • speech recognition and text-to-speech in 24 languages
  • human vs. answering machine detection
  • virtualization
  • using DNS as key value stores
  • splunk logging
  • sponsorship of adhearsion, the ruby telephony framework
  • rayo, Voxeo Labs’ new realtime communication protocol

Webpulp.tv – Tropo – Jose De Castro from Gaslight Software on Vimeo.

Up in the Air with Tropo and ScraperWiki

Tuesday, December 20th, 2011

ScraperWiki is a powerful cloud-based service that lets you scrape data from online documents and websites.

When you write a scraper – a script to pull information from a web resource and then parse out the bits you want – it will execute inside the ScraperWiki environment.

SMS flight information

You can store the data that is scraped inside a data store and then access the data from outside the ScraperWiki environment using their API. Scrapers can be written in one of several different languages – Ruby, PHP and Python.

ScraperWiki and Tropo operate in a very similar way. The Tropo scripting environment allows you to write scripts in one of several different languages, including Ruby, PHP and Python (Groovy and JavaScript are also supported).

Your script executes inside the Tropo environment, which means you can make direct connections to external resources – like the ScraperWiki API – from within your executing script. There is no need for extra HTTP overhead, and the additional step of posting to a back end server to connect to other APIs or resources.

In the following screencast, I demonstrate how to use Tropo and ScraperWiki to quickly and easily build an airport information system for the Philadelphia International Airport.

All of the code for this example can be found here. If you’d like to view the actual scraper I wrote on ScraperWiki, you can find it here.

This is still a work in progress – I’d like to run this script multiple times per day (ideally, maybe once an hour) to get updates to flight information and ensure that the app has the most up to date flight status. The voice dialog could also use a little tweaking, and I’d like to offer the option of repeating the information.

But even with these refinements aside, it is evident how combining these two powerful cloud resources can generate a pretty useful application in a very short time.

Tropo and ScraperWiki are a powerful combination. Happy flying!

Tropo Jambox Megaphone

Monday, December 19th, 2011

After rocking out to a little White Stripes’ Icky Thump, Chris Matthieu shows you how to build a megaphone using a Jawbone Jambox, an iPhone, and the Tropo Scripting API!

Here’s the Ruby script used in the video:

say "Welcome to the Tropo megaphone app! Please turn on and pair your Jam box now."

while $currentCall.isActive do

record "Record your message at the beep and then switch audio to jam box.", {
        :beep => true,
        :timeout => 10,
        :silenceTimeout => 7,
        :maxTime => 60,
        :onRecord => lambda { |event|
            log "Recording result = " + event.recordURI
            say event.recordURI}
        }

end

Rock on!

Customer Spotlight: Zapier

Friday, December 16th, 2011

We are excited to feature Zapier on this week’s Tropo Customer Spotlight! Today I sat down with Wade Foster, one of the co-founders of Zapier, to discuss their business and learn more about how they are using Tropo for their Instant Messaging services.

What is Zapier?

Zapier allows you to “zap your apps!” You can build unique integrations between your favorite applications, one mouse click at a time without writing a single line of code!

  • Own Your Data: Zapier makes it easy to import and export data automagically with your favorite web apps. Don’t get locked in.
  • No Data Entry: Quit filling out the same information between different applications, and let Zapier do the heavy lifting for you.
  • Fill-in Missing Features: Never be at the mercy of vendors to build features or integrations. Use Zapier to add missing functionality.

Zapier uses Python, Django, and the Tropo Scripting API to deliver Instant Messaging services to users on AIM, GTalk, MSN, and Yahoo!

To learn more about Zapier, visit their website at http://zapier.com!

Here is a screencast of Zapier using Tropo for their Instant Messaging services:

Tropo Powers Apps for Communities Winners

Friday, December 16th, 2011

Yesterday, at the Andreessen Horowitz Offices in Silicon Valley, FCC Chairman Julius Genachowski announced the winners of the Apps for Communities challenge.

The challenge, a several months-long call to developers to build apps that connect people to their communities, culminated with the submission of 75 innovative applications. The idea behind the challenge, which was sponsored by The Knight Foundation and the FCC, was as follows:

“Using hyper-local government and other public data [entrants] should develop an app that enables Americans to benefit from broadband communications — regardless of geography, race, economic status, disability, residence on Tribal land, or degree of digital or English literacy — by providing easy access to relevant content.”

When the winners were announced, three inspiring, innovative applications built with Tropo and SMSified were among the winners, including the Grand Prize winner.

Here is a quick summary of the winning entries that used our platforms:

YAKB.us (Grand Prize Winner)

YAKB.us is a realtime bus notification service that provides information via phone and SMS. The service, which is available in both English and Spanish, provides transit information in three municipalites – Arlington County VA, Charlottesville VA and Santa Clarita CA. This innovative application was built by Code for America fellow Ryan Resella.

PhillySNAP (Honorable Mention)

PhillySNAP makes it easy to get information on retailers in Philadelphia that provide reimbursement for Supplemental Nutrition Assistance Program (SNAP) benefits. The service allows users to send an SMS message with their address and then it provides the addresses of retailers near them where they can use their benefits. This application was initially developed at the Random Hacks of Kindness hackathon in Philadelphia this past June.

PhillySNAP was also featured on the SMSified blog several weeks ago.

Off to Market (Bonus: English Literacy)

Off to Market is another SMS-based app that provides the locations of farmers markets, where users can go to find fresh produce. It’s written in Node.js and uses the Tropo WebAPI. The developer – another Code for America alum, John Mertens – wrote a fantastic post on his blog about how he obtained, refined and staged the farmer’s market data for this app.

Congratulations to everyone who participated in this outstanding challenge, and congratulations to all of the great apps that were honored as winners!