Posts Tagged ‘Python’

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.

LA .NET Hackathon 2011

Monday, December 5th, 2011

Tropo is partnering with the LA .NET Developers Group and Outlook Amusements to sponsor this weekend’s LA (Burbank) Hackathon at Outlook Amusements on Saturday, December 10, 2011 from 9:00 AM to 6:30 PM (PT).

Here’s the address: Outlook Amusements 2900 W. Alameda Ave suite 400 Burbank, CA 91505

The theme of the LA Hackathon is “Build Voice/SMS apps for Holidays”! Here are a few ideas to get you thinking:

  • Santa Caller (similar to http://santacall.us) – Build a website that allows a parent to schedule a call to their kids from Santa. Have Santa ask the kid what they would like for Christmas and then email the parents their kid’s recorded message and/or transcribe the message for the email.
  • Santa Tag (similar to http://www.bloggingbistro.com/jc-penney-comes-up-with-a-new-use-for-qr-codes-video/) – Build a website that calls someone to record a message then associates the message with a QR code that plays when scanned.
  • Holiday Greetings Hotline – Build a holiday greetings hot line where user can leave a voice message that will be transcribed into text and posted to “Holiday Greetings” twitter account.

Even though this event is sponsored by the .NET Developers Group, we will be supporting all development languages and will have Tropo expertise onsite in .NET, PHP, Ruby/Rails, and Javascript, and Node.JS!

Register today!

New Fax Library for Pythonistas

Thursday, September 22nd, 2011

Remember the post we did earlier this year with the Ruby gem written by Jason Goecke called pamfaxr for sending and receiving faxes? Well we are excited to announce that there is a new Python library by Jonathan Sweemer to do the same thing! Here’s the source code on GitHub too!

2 Lines of Code To Enable Calling 1 Phone Number And Ringing Multiple Phone Numbers (like Google Voice)

Monday, July 18th, 2011
Phone Home

Have you ever wanted to give out a single phone number that in turn dials multiple phone numbers? And whichever phone answers first speaks to the caller?

I had just this case recently when I wanted a phone number I could start putting on Voxeo news releases that would ring my multiple phones and also could conceivably also ring someone else’s phone number. The number is also not tied to a single person so that if someone else started handling press inquiries, the number could just be redirected to the other person’s phone number(s). (In the programming world, we would call this an “abstraction layer”.)

Here’s literally all you have to do in Tropo Scripting (outside of having a free developer account at Tropo.com)… it’s really just one line of code using the transfer command and provide an array of phone numbers to call. Here’s how it looks in python, my language of choice:

say("Please wait while we connect your call.")
transfer(["+14079678424","+16037566424","+14074555859"], {
    "playvalue":"http://www.phono.com/audio/holdmusic.mp3"})

All I had to do was:

  • login to Tropo.com
  • create a new application
  • create a new hosted file
  • copy / paste this code in and change the phone numbers
  • save the hosted file
  • save the application
  • add a new phone number to the application
  • wait a minute or two and start calling!

That’s literally it.

If python isn’t your thing, you scroll down the documentation page for the transfer command and see examples in JavaScript, Ruby, Groovy and PHP. They are all basically the same simple solution.

Now, what’s cool about Tropo is that because Tropo can work with IP communications / unified communications systems, I can tell the transfer command to also use a SIP address as one of the endpoints to call:

say("Please wait while we connect your call.")
transfer(["+14079678424","+16037566424","sip:dyork@corpsip.voxeo.com"], {
    "playvalue":"http://www.phono.com/audio/holdmusic.mp3"})

This simple version works really well… but I can make a few other changes to it. Here’s a version that:

  • speaks with a different text-to-speech voice
  • provides an option for the caller to cancel the call (although they could of course just hang up)
  • covers the error condition of no one answering any of the phone numbers

The code is:

say("Please wait while we connect your call. Press star to cancel the call.",
    {"voice":"simon"})
transfer(["+14079678424","+16037566424","sip:dyork@corpsip.voxeo.com"], {
    "playvalue":"http://www.phono.com/audio/holdmusic.mp3", 
    "terminator": "*",
    "onTimeout": lambda event : say("I'm sorry, but nobody answered.")})

That’s it! Short and simple… and able to ring all the phones you want.

What’s also great is that I can add more phone numbers to this application on the inbound side so that I could in fact have a phone number in the UK or 40 other countries that call into this application… and then are transferred out to whichever phone I want to take the call on.

P.S. Sure, you can do this with services like Google Voice, but there are limits with some of those services. For instance, a Google Voice number is tied to your Google Account, so you may need to create another Google Account if you want a new Google Voice number. And while yes, you can add another number to your GV account for $20, it’s still tied to that one account. With Tropo, you can make as many of these type of applications as you want…

Hello, Python World (Django Edition)

Sunday, May 29th, 2011

I’ve been doing my Python Tropo development on top of Google App Engine, for the past couple of years. Out of the box, App Engine uses the webapp framework. But for my current “Hello, World” project, I decided to leave my App Engine comfort zone, and gain a different perspective. I took up the task of writing a “Hello, World”, Tropo Web API app, using the Django framework for Python.

(more…)

Updated Version of the Python Module for the Tropo WebAPI

Friday, April 29th, 2011

Python logoFor you pythonistas out there, I merged in some changes today to the “tropo-webapi-python” module. My colleague Justin Dupree found and fixed an error where the “on” object was not included as an available option. With this fixed you can now send in events using the ‘on’ object.

To get the updated tropo-webapi-python library, you can download it (or git clone it) from:

https://github.com/tropo/tropo-webapi-python

… and if you already have a local clone of the git repo, odds are that you know how to update it ;-)

Alternatively you can also grab it from the PyPi repository:

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

Thanks to Justin for the fix and thanks to other pythonistas who have reported issues. Speaking of that, if you do find any issues with the library, please report them to the “Issues” area on Github. Many thanks… and please let us know how else we can help you build awesome python apps using Tropo!

Hey, Pythonistas! Tropo Just Got Upgraded To The Latest Jython

Wednesday, March 23rd, 2011

Python logoIf you like to create communications apps in python, as I do, we’ve got some great news for you… Tropo Scripting just got updated to the latest version 2.5.2 of Jython. What this means for you is that if you ever found that one of the python apps you uploaded to Tropo Scripting wouldn’t run because it needed one of the newer “standard” python libraries, you now have access to the latest that is available to us.

You can find out about what is in jython 2.5.2 at:

http://www.jython.org/docs/whatsnew/2.5.html

And the list of standard supported libraries is at:

http://www.jython.org/docs/library/indexprogress.html

(Note that not all of these libraries may be supported within Tropo’s cloud environment.)

You may or may not be aware, but the Tropo Scripting cloud uses the JSR 223 Scripting framework for Java to support the languages of Ruby, python, PHP, Groovy and JavaScript. For python this means that Tropo uses Jython, which only recently moved to 2.5.2, supporting most all of the features in regular python 2.5.

Among many other enhancements, the Jython team also indicates that Jython 2.5.2 includes a significant performance increase.

So what are you waiting for? Sign in to Tropo (or register for a free account), check out our tutorials and quickstart examples and start building voice, SMS, IM and Twitter apps today!

P.S. And if you want to access standard libraries found in the even newer python 2.6, 2.7 or 3.x – or if you want to use your own custom libraries or modules, you can simply run the application on your webserver instead of hosted in the Tropo cloud and use the Tropo WebAPI… we’ve even created a library, tropo-webapi-python to make that easy for you.

$40,000 in prizes up for grabs. Win with your source code.

Saturday, January 29th, 2011

Binpress is a new startup that’s built a marketplace for code. Sell your code, buy code from others. Whether you have a content management system, a plugin for WordPress or Drupal, or a great new UI widget built with jQuery, Binpress helps you market and sell your code. They take care of the license agreements, the ecommerce, and all the hassles associated with selling software.

To kick off their marketplace, they’re running a developer contest with $40,000 in prizes. They came to Tropo, wondering if we might be interested in providing a prize for the best code in one of the languages they support: PHP, Ruby, Javascript, Java, Python, or ASP.net.

Hmm, that list of languages looks pretty familiar. Tropo lets you host your code in PHP, Ruby, Javascript, Groovy (a Java-based scripting language), or Python. We have code libraries for our REST and WebAPI platforms using .Net, PHP, Ruby, Python, and Node.js.

We jumped right in and offered to sponsor not one language, but all of them. While we’re at it, we’re kicking in prizes for the rest of the contest, too.

Build the best app in one of Binpress’s languages and Binpress will give you $350 and a $100 Tropo credit for production usage. Win the Grand Prize — the best of show, as it were — and they’ll give you $1000 in Tropo credit. The second and third place winners will get $500 and $250 in Tropo credit, respectively.

There’s a whole lot of prizes totaling over $40,000, including service vouchers from Amazon Web Services, Media Temple, Sendgrid, Github, and Zencoder, cash from Conduit and Microsoft, and books from O’Reilly and Wrox.

Go jump in and build something awesome. You’ve got a month to create your masterpiece and win.

Tropo Powers PennApps Mobile Winner

Friday, January 28th, 2011

The recent PennApps Mobile competition, held at the University of Pennsylvania on January 14th through the 16th, brought together teams of students to work on the next generation of mobile applications.

Tropo was proud to be a sponsor of this event, and equally proud to see one of the event standouts use the Tropo platform.

A team of four Penn Computer Science Students (Lu Chen, Matt Croop, Gary Menezes and Ryan Menezes) used Tropo to build the Decider, one of the winners of the PennApps event with an interesting take on the contest theme – Serendipity.

We talked with the team to find out more about their project, and why they selected Tropo.

Briefly describe your project – what is it, what does it do?

What should we do tonight: watch a movie or play board games? Should I pull an all-nighter or get some sleep? These five desserts on the menu all look delicious… Which one should I order?

Instead of flipping a coin, why not let a stranger decide?

We used Tropo to build the Decider, which anonymously sends your question to a randomly chosen stranger who decides for you. You can send questions over SMS and IM, or with our Android app.

What technologies does your project use?

Decider is written in Python, hosted on Google App Engine, and reliant on Tropo’s WebAPI library for all of its SMS and IM needs. The Android app is built with Java.

Explain your decision to use the Tropo platform. Why did you choose Tropo?

We first considered Tropo because the demo given at the event convinced us that using it would be simple and free. A big bonus was the ability to seamlessly tie in IM: our original intent was to just handle SMS, but adding IM support was effortless.

Finally, Tropo’s scripting made it easy to quickly debug and test, while WebAPI gave us a lot of flexibility in choosing a backend.

What did you like best about using Tropo?

Tropo made it terrifically easy to get started. Even though we had no experience with messaging technologies, it took our team of four less than 6 hours to sign up, learn WebAPI, deploy an app, and test it over chat and sms. The docs and sample code were excellent.

What are your future plans? Any plans to take the project to a wider audience?

Right now, we still think of the Decider as a fun experiment — we aren’t actively searching for users, but we’ll definitely keep it up to speed as more people join.

This smart, talented bunch has a bright future.

We at Tropo wish them the best of luck in all their future endeavors and hope that our paths cross again soon.

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!