Posts Tagged ‘SMS’

Outbound Apps – How They Work in Scripting vs WebAPI

Wednesday, May 23rd, 2012

Sending texts or making calls with Tropo can be a little counter intuitive if you’re accustomed to the pure REST implementations common to SMS APIs – POST the destination phone number and the message content to a specific URL, text goes out, end of story. With Tropo, you need a “launcher” app that handles the REST bits and a “catcher” app that actually sends the text, which adds a bit of complexity but also an immense amount of features.

The first app, the “launcher”, will create a REST request, either a GET or POST, that contains one of your application tokens and any parameters to pass over (such as the number to call). The token is your authentication, so no need for a user/pass or BASIC auth, and they’re found underneath the URLs for the actual Tropo app, a.k.a. the second “catcher” app. You’ll have two options:

Each token corresponds to one of the app URLs, so the Voice URL is linked to the Voice token, Messaging to Messaging. If your app has the same URL for both, either token will work fine.

The launcher app can be a plain URL dropped in a browser, like this:

https://api.tropo.com/1.0/sessions?action=create&token=TOKEN&numbertodial=14075551212&msg=test+Tropo+message

which is essentially a GET, or it can be a fully realized app using various languages and REST clients, like curl for PHP:

<?php
$token = 'TOKEN';
$numbertodial = '14075551212';
$msg = 'test+Tropo+message';

$curl_handle = curl_init();
curl_setopt($curl_handle,CURLOPT_URL,'http://api.tropo.com/1.0/sessions?action=create&token='.$token.'&numbertodial='.$numbertodial.'&msg='.$msg);
curl_setopt($curl_handle,CURLOPT_CONNECTTIMEOUT,2);
curl_exec($curl_handle);
curl_close($curl_handle);

?>

That app uses POST, though you could use a GET with the app just as easily. The launcher app would reside on your server, tied to be triggered by some criteria, potentially when someone clicks a button on a webpage.

Note that the message needs to have all spaces encoded, which is why the + sign is shown. You can also use:

curl_setopt($curl_handle,CURLOPT_URL,'http://api.tropo.com/1.0/sessions?action=create&token='.$token.'&numbertodial='.$numbertodial.'&msg='.urlencode($msg));

Ruby has a library called net/http that would work, Python has the urllib and urllib2 libraries, whatever you want to use would be fine as long as it can send a GET or a POST.

Your second app would look like the apps in one of these examples:

Scripting:

https://www.tropo.com/docs/scripting/passing_in_parameters_voice.htm

https://www.tropo.com/docs/scripting/passing_in_parameters_text.htm

WebAPI:

https://www.tropo.com/docs/webapi/passing_in_parameters_voice.htm

https://www.tropo.com/docs/webapi/passing_in_parameters_text.htm

The first set of examples are for apps created for the Scripting API – a Scripting app uses a script hosted on our servers (conveniently called “Hosted File” when creating a Scripting app); your launcher app would trigger it to run using the token, and everything else happens on our side. The sequence of events would look like this, if your launcher app was tied to a webpage:

  1. User loads your webpage, clicks a “send text” button or something similar
  2. Your serverside launcher app is triggered and sends the REST request to our servers
  3. Your Tropo app launches and sends the text message

The second set of examples is an app using the WebAPI; this API communicates with an app that’s actually running on your server, but sends instructions to our servers using back and forth JSON. This sequence of events for this one would look like this:

  1. User loads your webpage, clicks a “send text” button or something similar
  2. Your launcher app is triggered and sends the REST request to our servers
  3. The Tropo app launches and sends session JSON to your catcher app, also hosted on your server, asking for instructions
  4. Your second app replies with JSON that tells Tropo to send the text message
  5. Tropo sends the text message

Many developers using the WebAPI get stuck at this spot – it seems overly complex, and for a very basic SMS app that’s a legitimate thought. If all you want to do is send plain texts without any need to process responses, capture input, anything except deliver the text, then the Scripting option is often easier. Copy one of the examples from the docs, add a Scripting app and then build the launcher app in whatever language you want.

Hope that helps clarify the different processes; as always, if you get stuck, please don’t hesitate to post in our forums and ask for help.

Timeless SMS – Using CouchDB to Track Two Way SMS Conversations

Wednesday, March 28th, 2012

Tropo includes an “ask” method, which allows you to ask a question and wait for a response.  On a voice call, the user is actually on the phone and typically responds quickly; with SMS, they might receive your text with the question but wait to respond until they have the free time.  If your ask has a timeout of 30 seconds, and your user responds in a couple hours, how do you manage it? The absolute maximum timeout you can set is 2 hours – what if they respond the next day?

The best way to work around this limitation is by storing and reading the progress of an SMS conversation in a database, effectively eliminating any timeout concerns. This blog will discuss – and show – how to start, save and work with CouchDB to accomplish this. For the sake of simplity in this sample code, we’re getting back all the users. Realize that in a production system, you’ll probably want to tune this lookup so instead of getting back the couch documents for every user, you should search for the callerID and get only the documents for a particular user.

(more…)

SMS Voting App in 10 Minutes with Tropo and CouchDB

Wednesday, February 8th, 2012

Lat fall, I attended CouchConf NYC and gave a presentation on using Tropo with CouchDB.

It only recently occurred to me that I never did a proper screencast and blog post about my presentation, which struck me as a bit odd – I constantly get asked how to set up an SMS voting app with Tropo.

The good news is that setting up this type of app is incredibly easy with Tropo and CouchDB. The even better news is that I’ve finally gotten around to recording a screencast on how to do it – watch below.

A vote for the Rolling Stones.

All of the code used in this demo can be obtained from GitHub.

To install the CouchApp utility, go to the CouchApp project page.

If you’re looking for an easy way to set up a CouchDB instance, have a look at IrisCouch.

By pairing Tropo with CouchDB and a CouchApp running in IrisiCouch, you can have an SMS and phone voting app running entirely in the cloud in about 10 minutes. It should actually take you longer to write up the categories for your voting app than it should to deploy this solution.

Tropo + CouchDB, FTW!

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.

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!

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 SMS Wolfram Alpha Mashup

Tuesday, December 13th, 2011

Tim Strimple joined us at the LA Holiday Hackathon to get in on the competition of building Tropo applications for prizes and won a $50 Tropo Production credit for his Tropo SMS and Wolfram Alpha mashup!

You can ask the application virtually any question via SMS using the following phone number 661-206-2681 and it responds to your inquiry via SMS using Wolfram Alpha’s search results. Here’s a video of Tim demonstrating his application in action!

Here’s the code behind Tim’s Tropo SMS Wolfram Alpha mashup! It’s written in PHP and uses the Tropo Scripting API.

<?php  

function CheckForShortcut($request)
{
    if(stripos($request, "siri") !== false)
    {
        return "I don't like to talk about her.";
    }

    if(stripos($request, "remind") !== false)
    {
        return "I am not your personal assistant.";
    }

    if(stripos($request, "tropo") !== false)
    {
        return "Tropo is great, I love it!";
    }

	return false;
}

function ParseResponse($response)
{	
	//	Replace with real XML parsing
	$min = strpos($response, "</plaintext>");    
	$startPos = strpos($response, "<plaintext>", $min) + 11;
    $endPos = strpos($response, "</plaintext>", $startPos);
	$length =  $endPos - $startPos;

	if($min > 0)
	{
		return substr($response, $startPos, $length);	
	}
	else
	{
		return "Go ask Siri...";
	}
}

function GetResults($request)
{
    $shortcut = CheckForShortcut($request);

    if($shortcut)
    {
        return $shortcut;
    }

    $request = str_replace (" ", "%20",$request);
	$wolframApiKey = "XXXXXX-XXXXXXXXXX";
    $url = "http://api.wolframalpha.com/v2/query?appid=" . $wolframApiKey . "&input=" . $request;
    $response = file_get_contents($url);

	return ParseResponse($response);
}

if($currentCall->channel == "TEXT")
{
    $result = GetResults($currentCall->initialText);
    say($result);
}
else
{
    say("I do not support voice currently. Try sending me a text message instead.");
}
?>

Happy Hacking!

LA Holiday Hackathon :: Results

Monday, December 12th, 2011

Approximately 30 Los Angeles .NET, Ruby, PHP, and Javascript developers attended this Saturday’s LA Holiday Hackathon at Outlook Amusements sponsored by RightNow Technologies and Tropo. The theme of the event consisted of building a Voice, SMS, or Instant Messaging holiday application based on the Tropo Scripting or Web API. Here is a photo of everyone hard at work hacking on their holiday Tropo application.

I love the sound of phones ringing in the morning! By noon, the applications were starting to take shape with some definite front runners in the competition. In addition to Tropo APIs, many of the teams also used Phono, SMSified, RightNow, Wolfram Alpha, and Google’s Shopping APIs to deliver their new applications.

Here are the winners of the LA Holiday Hackathon listed in order:

First place goes to Gift Finder winning an iPad2 compliments of RightNow Technologies. This application allows the user to enter a phone number, name, and email address to place an outbound call to someone to recommend gifts for loved ones. Speech recognition was used to ask the user for their zip code, gender, price range range, and category of the gift. The application uses the Google Shopping API to find gifts in their area for the gender and age of the recipient and reads them off one by one using text to speech. This application was built using Ruby and Sinatra and hosted on Heroku as well as using the Javascript Tropo Scripting API.

Second place goes to Santa’s Book winning a Kindle Fire compliments of RightNow Technologies. This application asks for two phone numbers and starts by calling the first number to ask a series of five questions using speech recognition to determine if the person is naughty or nice along with asking them to record the present that they would like to receive. The application proceeds to call the second number to relay the naughty/nice determination and playback their gift recording. The application also sends an SMS text message to the second number with the naughty/nice determination along with the transcribed gift request. This application also used RightNow’s CRM API to log the call and data related to the surveys. This application was built using PHP and the Tropo WebAPI along with RightNow’s CRM API.

Third place goes to Santa Hack winning a $75 Fry’s Electronics gift card compliments of Outlook Amusements. This application used Phono and Tropo to schedule and bridge appointments to speak with Santa. This application was built using C# and the Tropo WebAPI.

Fourth place goes to Tropo WA (Wolfram Alpha) winning a $50 Tropo production credit. This application was a Wolfram Alpha and Tropo SMS mashup written in PHP using the Tropo Scripting API. You can ask the application various questions via SMS on the following number 661-206-2681.

Tropo + Ushahidi = Awesome

Friday, December 9th, 2011

Ushahidi is a platform for crowdsourcing information. Members of the public submit reports that are geo-located and then put on a map. The platform is used in disaster relief, election monitoring and just about any other situation where people need to learn things from one another quickly and concisely. Out of the box, Ushahidi allows people to submit reports via the web, mobile applications, Twitter, Facebook with support for a few SMS APIs as well.

We have created an easy-to-use application that lets people use Tropo to input data into Ushahidi via SMS. We’ve put the code up on Github and you’re welcome to submit pull requests if you find bugs or add features.

To use the code, you don’t have to install anything on Ushahidi. Here are the steps:

  1. In Ushahidi, create a user with “Admin” privileges.
  2. check out the code from Github
  3. edit the configuration lines at the top with your Ushahidi credentials and URL
  4. create a new Scripting API Application on Tropo.com.
  5. Once your Tropo app is created, you can add an SMS-enabled number (US and Canada currently) and optionally configure it to talk on any IM networks or Twitter.

Now, when you send a message to any of your configured numbers the application will attempt to geo-locate the message based on its contents. The app then submits a report via the Ushahidi API in an unverified state. Admins of the site can then verify the reports and publish them to the web.

In our example here, we simulated a flood in Milwaukee. The instance pulls in feeds from local media and disaster response community, accepts reports via the web and accepts reports from a Tropo app I created. We sent a message to the number configured in the app with the following content:

 

Columbia St. Mary’s Hospital Milwaukee WI is flooded. Power is out.

This was submitted to Ushahidi in an unverified state. The reviewer then added text to flush out the report based on other incoming data and then published the report:

Columbia hospital has been without power for the past 16 hours. Two of the three emergency diesel generators are operating normally. Generator number 2 is scheduled to be functional within the next 6 hours. Fuel supplies are at nominal levels with an estimated 48 hours remaining. Inundation levels are currently low but may begin rising at high tide.

This sort of crowdsourced data, gathered at the source, is valuable for many reasons. It gets the word to responders and the public more quickly so that people can act appropriately (e.g. by not going to that hospital, go to another one.) First responders become aware of the weight of a problem when more people report the same thing or when the first report comes in of a very big event.

Watervoices.ca, developed this past weekend at RHoK, will be going live with this application soon and we hope to see others using it to help the world soon. Over time, we will be adding support for Voice, PhoneGap within Ushahidi and many other features.