Friday, September 18, 2009

Python - Back to Basics: Accessing Online Content

Many of the different scripts that I write in Python deal with accessing content online. I thought that it might be a good idea to go over some of the different methods Python provides, and give some examples of their every day uses.

Most of the functionality you may ever want to access online content can be found in one of two modules (and often you need to use both) : urllib and urllib2.

First situation: You want to download the content of some page, perhaps to scrape the page for information for later processing. You want the content to be stored in a single variable (a string) so that you can do some regular expression matching on it, or some other form of parsing. A few simple lines:


import urllib2

page_contents = urllib2.urlopen("http://www.google.com").read()

print page_contents


Notice how on the second line I have the ".read()" method call. If you leave this off, you will have just the socket file object, which you can later call ".read()" on to get the contents. I like to do it all in one line however. Once you do this, it is a regular string and you can do whatever you want to/with it.

Now, lets say that you don't want to just download the page contents - you want to download an actual file, like an image, video, Power Point Presentation, PDF or anything else. Also, just a few lines:


# Download the Python image from http://python.org
import urllib

# File will be called "Python-Logo.gif",and will be contained in the folder
# where the script was executed
urllib.urlretrieve("http://python.org/images/python-logo.gif", "Python-Logo.gif")


You can use the "urlretrive" method to download pretty much any file you want - you just need to know it's URL and what you want to call it when you download it. Keep in mind that if you don't specify anything but the name of the file, it will be downloaded to the folder where you run the script. You can put things like "C:\images\Python-Logo.gif" in there if you want it to go somewhere else.

Using what we have gone over in the first two example, we can write some useful scripts. W can get the page source, find all of the PDF files linked to on it, and download them all to a folder. I do this very thing for one of the classes that I am currently taking. Here is that script:


import urllib
import re
import os

# Specifiy where I want to download my files
download_folder = "C:\DropBox\My Dropbox\School\CS479\Slides\\"

# Download page contents
# Note: I am using urllib, not urllib2, but only because urlretrieve does not exist in urllib2
# Both have this method, and do pretty much the same thing (for this kind of usage, that is)
page_contents = urllib.urlopen("https://cswiki.cs.byu.edu/cs479/index.php/Lecture_slides").read()

# Use regular expression to find all pdf files on site.
# match.group(1) will contain the link to the file
# match.group(2) will contain the name of the file
for match in re.finditer(r'<a href="(.*?\.pdf)"[^>]+>([^<]+)', page_contents):
file_url = match.group(1)
# Remove any characters that files cannot contain
file_name = re.sub(r'(\\|/|:|\*|\?|"|<|>|\|)', "", match.group(2))
# Check and see if I have already downloaded the file or not
if not os.path.exists(download_folder + file_name + '.pdf'):
print "Downloading new file {0}...".format(file_name)
urllib.urlretrieve(file_url, download_folder + file_name + '.pdf')


Lets make things more interesting - lets say that you want to get the content of a page, but you must be logged in to get at it. You can handle this just fine as well. Lets say that you want to get into your Google Voice account and scrape the page for the ever so important "_rnr_se" value. (I know that I have shown this a few times before, but many people still wonder how to do this, and it is a good, practical example).

Here are the steps we need to do to make this happen:
  1. Create an "opener" with the urllib2 module, through which all of our requests will be made. The opener will be created with a HTTPCookieProcessor that will handle all the Cookies from request to request (This allows us to stay "logged in").
  2. Install the opener, so whenever we make a request, our opener that we created will be used (and any Cookie data that has been received by previous requests will be sent along and updated when necessary)
  3. Prepare our login credentials, and URL encode them.
  4. Post them to the login page
  5. Do whatever we need once we are logged in.
This might seem like a lot, but it really isn't and it is very simple to do. Here is the script for that:



import urllib, urllib2
import re
from getpass import getpass

email = raw_input("Enter your Gmail username: ")
password = getpass("Enter your password: ")

opener = urllib2.build_opener(urllib2.HTTPCookieProcessor())
urllib2.install_opener(opener)

# Set up login credentials for Google Accounts
# The 'continue' param redirects us to the Google Voice
# homepage, and gives us necessary cookie info
login_params = urllib.urlencode( {
'Email' : email,
'Passwd' : password,
'continue' : 'https://www.google.com/voice/account/signin'
})

# Perform the login. Cookie info sent back will be saved, so we remain logged in
# for future requests when using the opener.
# Once we log in, we will be redirected to a page that contains the _rnr_se value on it.
gv_home_page_contents = opener.open( 'https://www.google.com/accounts/ServiceLoginAuth', login_params).read()

# Go through the home page and grab the value for the hidden
# form field "_rnr_se", which must be included when sending texts and dealing with calls
match = re.search(r"'_rnr_se':\s*'([^']+)'", gv_home_page_contents)

if not match:
logged_in = False
else:
logged_in = True
_rnr_se = match.group(1)

if logged_in is True:
print "Loggin successful! _rnr_se value: {0}".format(_rnr_se)
else:
print "Loggin was unsuccessful"



If you are looking to open up a browser and automatically post form data, look at my other post here where I go into more detail.

Hope this helps!

If you want to download all of the examples here, here is a zip-file.

Wednesday, September 2, 2009

Python + Jquery: Open Browser and POST data

A few entries ago I talked about how I used Python to run some tests on a web page that I was creating. Python has a 'webbrowser' module that can open up your default web browser and point it to a specific URL. For the tests that I was running this worked well since the page expected a GET request - all parameters were passed in the URL, which I could change dynamically in my Python source. I didn't need to POST anything to the page with an HTML form.

I wanted a way to open up pages in my web browser with Python, but perform a POST request, sending data along with it. This functionality is not supported by the webbrowser module, nor do I see how it could. So, I came up with solution that meets my needs. It involves jQuery and creating then deleting a temporary file.

For those of you who do not know, jQuery is a JavaScript library that makes programming in JavaScript downright enjoyable, and provides easy solutions to common problems. Google has a Javascript API that lets you easily download stable versions of many different JavaScript libraries, including jQuery. You can do this wherever you would like, and makes it so you don't have to keep the source local (there are many benefits to this approach).

So, these are the steps we take to open a page with Python, and post our predefined (hard-coded or dynamic) form data to a page our our liking:
  1. Dynamically create a complete HTML file.
  2. Include jQuery on the page (this makes it much easier to know when the form is ready for submission).
  3. Create a form on the page with the appropriate action and method.
  4. Insert hidden form elements with their corresponding names and values.
  5. Submit the form when the DOM is finished (jQuery helps with that).
  6. Delete the file when we are done.
There are lots of ways that you could use this, but I made it as a way to test web pages I am working on. Just as an example, here is a script that you could use to open up a page after having entered your Gmail login credentials:


import os
import webbrowser

# Set up form elements - these will become the input elements in the form
input_value = {
'Passwd' : 'YOUR PASSWORD HERE',
'Email' : 'YOUR USER NAME',
'continue': 'https://mail.google.com'
}
action='https://www.google.com/accounts/ServiceLoginAuth?service=mail'
method='post'

#Set up javascript form submition function.
# I am using the 'format' function on a string, and it doesn't like the { and } of the js function
# so I brought it out to be inserted later
js_submit = '$(document).ready(function() {$("#form").submit(); });'

# Set up file content elements
input_field = '<input type="hidden" name="{0}" value="{1}" />'

base_file_contents = """
<script src='http://www.google.com/jsapi'></script>
<script>
google.load('jquery', '1.3.2');
</script>

<script>
{0}
</script>

<form id='form' action='{1}' method='{2}' />
{3}
</form>
"""

# Build input fields
input_fields = ""

for key, value in input_value.items():
input_fields += input_field.format(key, value)

# Open web page
with open('temp_file.html', "w") as file:
file.write(base_file_contents.format(js_submit,action, method, input_fields))
file.close()
webbrowser.open(os.path.abspath(file.name))
os.remove(os.path.abspath(file.name))


Let me know if you find this useful!

Tuesday, September 1, 2009

Python - Kronos Workforce Management Clock In/Out

I have been working on the Web Team of the BYU Marriott School for almost a year now. Overall it has been a very enjoyable experience, except for one thing: Kronos. Kronos is an online time management software solution that we must use to keep track of the hours that we work - you clock in when you come in, and you clock out when you leave. Pretty simple problem with a simple solution, but they have complicated this process by providing many unnecessary levels of navigation with unintuitive and inconvenient controls.

If you have two campus jobs (which I do) then it makes matters worse as the means of clocking in requires additional steps. Even though I only ever clock into one job through this website, there is no way for me to tell the system I want to use this job as my default job. It has hardwired itself to always use this other job as the default - there is no way to change that. I must explicitly tell it every time I clock in that I am clocking if for "Job 2". Also, there is also no way to quickly and easily check if you are clocked in (sometimes I forget if I clocked in). I have to go through 3 levels of navigation to find my time card and check if there is a clock-in time without a clock-out time next to it. The system won't even tell me - I have to determine my status by inspecting my time card personally.

There are many other shortcomings, but these are my biggest complaints. (I am not just a complainer, I already implemented my own time-tracker/management system that handles all of these problems in PHP that unfortunately I can't use at work for payroll purposes.)

So, I wrote a script in Python that will clock in and out of Kronos for me. It isn't too sophisticated, but it works well for my purposes. The script actually does not check to see if you are logged in or out, but based on the name of the file it will perform either the clock in or clock out actions. For example - if the name of the file is "Kronos Login.py" then it will clock you in, giving Kronos the correct job code (you hard-code that in, so I made my clock in job code "Job 2" since that is the only one I ever use). After it has done this, the script will change the name of the file it is in to "Kronos Logout.py". The next time it is run, is sees that it is named "Kronos Logout.py" and will clock out, then change it's name back to "Kronos Login.py". Like I said - not sophisticated, but it solves my problems: No clumsy navigation, and I can just check my Desktop for the script to see my clocked in/out status. I have been using it for a few days now without any problems.

Here is the source (or download it directly):


import sys, os
import urllib2, urllib

# Set up useful variables
file_name = os.path.basename(sys.argv[0])
full_path = os.path.abspath(file_name)
current_directory = os.getcwd() + '\\'

username = 'YOUR USERNAME'
password =

# URLS
kronos_home_page = 'https://kronprod.byu.edu/wfc/applications/suitenav/navigation.do?ESS=true'
kronos_login = 'https://kronprod.byu.edu/wfc/portal'
kronos_timestamp = 'https://kronprod.byu.edu/wfc/applications/wtk/html/ess/timestamp-record.jsp'

# If you have more than one job, set the number of the job you want to clock into here
# Example: '2' or '1' ('1' Kronos will assume you want job 1 by default, so you don't need to set that one)
# Leave blank if you only have one job.
job_number = '2'

# Create our opener
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor())
urllib2.install_opener(opener)

login_credentials = urllib.urlencode({
'password': password,
'username': username
})

# Open home page to get cookies
opener.open(kronos_home_page)

# Login
opener.open(kronos_login, login_credentials)

#Clock in or clock out
if ('Logout' in file_name):
transfer = '' # Logging out - transfer parameter must be blank
else:
if job_number != '':
transfer = '////Job ' + job_number + '/'
else:
transfer = ''

time_stamp_parameters = urllib.urlencode({
'transfer' : transfer
})

opener.open(kronos_timestamp, time_stamp_parameters)

if ('Login' in file_name):
os.rename(full_path, current_directory + 'Kronos Logout.py')
else:
os.rename(full_path, current_directory + 'Kronos Login.py')


I hope to later turn this into a Windows sidebar gadget - if I am successful, I will post that code as well.

Thursday, August 20, 2009

Google App Engine - Cookie Handling with URL Fetch

I started working on creating a web based solution (on Google App Engine, using the Python API of course) to send mass SMS messages through your Google Voice account this week, but ran into a couple of problems right off the bat during some initial testing. The problem was that I could not log into my Google Account - the response always included a message that my "browser" didn't have cookies enabled. I was confused by this since I was using the exact method and code that I use in my Google Voice Command Line Script, which works perfectly:

self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor())
urllib2.install_opener(self.opener)


Doing this will allow you to use the newly created "opener" object to open any URLs, and any Cookie data that is sent from the server is saved and resubmitted in the headers of each additional request. So, if you are visiting a site that requires authorization, you can send your credentials to the login page, and each subsequent request made with that opener will contain the Cookie info. This lets you access the protected areas/privileges of the site (such as sending SMS messages or making calls with your GV account) without much effort at all - it really is a nice feature of the language.

Well, I set this up in my app, but no luck. So I looked around for a bit and found out that the urllib2, urllib and httplib libraries perform requests using Google's URL fetch service (read more here). This isn't terrible, but the important thing is, is that the "urlfetch" service does NOT handle Cookies, even if you use a HTTPCookieProcessor, or a CookieJar (read more about that here).

This entry isn't a lesson on what Cookie's really are and how they work, but you should know that Cookie information is sent back from the server, and sent to the server in the headers portion of the request/response. Although the urlfetch service does not handle Cookie automatically, it does give you full access to process the header information received from a server, and also what information to send in the headers when making a request to the server. So, I built a separate class that I could use to open up URL's that would handle all Cookie information for me, as well as handle any redirects. The Google Account login system uses redirects when logging in - they forward you to a bunch of different sites to make sure you are actually logged in and that you have the right Cookie info.

Here is the class:

import urllib, urllib2, Cookie
from google.appengine.api import urlfetch

class URLOpener:
def __init__(self):
self.cookie = Cookie.SimpleCookie()

def open(self, url, data = None):
if data is None:
method = urlfetch.GET
else:
method = urlfetch.POST

while url is not None:
response = urlfetch.fetch(url=url,
payload=data,
method=method,
headers=self._getHeaders(self.cookie),
allow_truncated=False,
follow_redirects=False,
deadline=10
)
data = None # Next request will be a get, so no need to send the data again.
method = urlfetch.GET
self.cookie.load(response.headers.get('set-cookie', '')) # Load the cookies from the response
url = response.headers.get('location')

return response

def _getHeaders(self, cookie):
headers = {
'Host' : 'www.google.com',
'User-Agent' : 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2 (.NET CLR 3.5.30729)',
'Cookie' : self._makeCookieHeader(cookie)
}
return headers

def _makeCookieHeader(self, cookie):
cookieHeader = ""
for value in cookie.values():
cookieHeader += "%s=%s; " % (value.key, value.value)
return cookieHeader



The class is simple, but works for my purposes. The class really has only one method that you should worry about: "open". Lets walk through that method: First, it checks to see if you are posting any data, and if not it makes it a GET request. Then, it starts into it's main loop. The first loop sends the data (if there is any) and some basic header information in the request, then saves the Cookie info it received in the response, then changes the request method to GET. It checks the headers for the "location" value to see if it needs to be redirected - if it does, it keeps going, saving and sending the received Cookie information along the way. Once it is done, it returns the response of the final location. Once you return the response, you can access the content by calling ".content" on the returned value.

Currently, it doesn't support GET requests with data, but mainly because I didn't need that for this project. It would be trivial to implement, however.

Here is an example on how to log in to your Google Voice account, then parse out the ever-so-important "_rnr_se" value using the URLOpener class:


opener = URLOpener()

loginParams = urllib.urlencode({
'Email' : email,
'Passwd' : password,
'continue' : 'https://www.google.com/voice/account/signin'
})

opener.open( 'https://www.google.com/accounts/ServiceLoginAuth', loginParams)

googleVoiceHomePage= opener.open('https://www.google.com/voice/#inbox').content

match = re.search('name="_rnr_se".*?value="(.*?)"', googleVoiceHomePage)

_rnr_se = match.group(1)

Hope this helps!

Monday, August 17, 2009

Python - Boggle Solver

I have been a long time fan of the game Boggle. Last year in one of my CS classes we were required to create a program in Java that would find all the words on any given Boggle board - a very fun project, and one that I found useful for a number of reasons. The other day I was messing around with my old Java implementation, and thought it would be good practice to convert it to Python. During the process, I learned a few new tricks about Python and also some other solutions to problems that may come up in other places.

The first useful thing I learned how to do was to create a class that acted as if it had two __init__ functions, which of course Python cannot handle. There are a couple of ways to do it, but my favorite implementation uses the "@classmethod" decorator. The "@classmethod" decorator makes the method static (not like in Java or C++ - use @staticmethod for that) - so within the method you can initialize a new object, set the instance variables then return the newly created object once you are done. Here is a code snippet from my Word class where I used this:


class Word:
def __init__(self):
self.letter_sequence = ""
self.used_board_coordinates = set()

@classmethod
def new(cls, row, column):
word = cls()
word.used_board_coordinates.add((row, column))
return word

@classmethod
def new_from_word(cls, word):
new_word = cls()
new_word.letter_sequence += word.letter_sequence
new_word.used_board_coordinates.update(word.used_board_coordinates)
return new_word



One of the constructors (called "new") accepts two parameters - the originating coordinates. It is called like so:


word = Word.new(row, column)


The second takes one parameter - another word. It creates a new word, and then copies over the data it needs. You call it much like the first:

wordCopy = Word.new_from_word(word)

Another problem I had to solve was prefix look-up. I have a large dictionary, and while searching for words on the board I only wanted to pursue directions that could potentially lead to actual words - so I needed to be able to quickly see if a letter sequence is a valid word prefix. I considered implementing a Trie or something similar, or using a modified Binary Search like I did in my Java program. I didn't really like either solution, so I came up with a solution that can take up a lot of memory, but runs extremely quickly - a simple set(). For each word loaded from my dictionary, I run a for loop that adds incrementing amounts of the word into my prefix set.


for index in xrange(len(word.strip()) + 1):
self.prefixes.add(word[:index]


So, when I receive the word "python" from my dictionary, I add "p", "py", "pyt", "pyth"...etc to my prefix set. I was first afraid at how long it would take to do this, since the dictionary I have has 170,000+ words in it. It takes less than 1 second, and the look-up times are top-notch.

I also found a use for a generator - it could have been done without it, but I like how it cleans up the code. I use one in the BoggleSolver class - it helps me loop through all of the valid moves (coordinates) for a given word. The rules are this for Boggle - you can only use each letter (coordinate) once when constructing a word, and you can only move to adjacent spaces that are on the board. Here an example from my code:


for row, column in self._get_valid_coodinates_for_word(word, row, column):
if(self.dictionary.contains_prefix(word.letter_sequence + self.board[row][column])):
self._find_words(Word.new_from_word(word), row, column)

def _get_valid_coodinates_for_word(self, word, row, column):
for r in range(row - 1, row + 2):
for c in range(column - 1, column + 2):
if r >= 0 and r < self.board.side_length and c >= 0 and c < self.board.side_length:
if ((r, c) not in word.used_board_coordinates):
yield r, c




There are a lot of "for"s and "if" statements there, I know - but I thought it made it more readable, and it doesn't affect the performance. So, to get the coordinates for the word, simply pass the word and the current coordinates to the _get_valid_coordinates_for_word generator, and you can iterate over the returned row, column values. Pretty slick, if you ask me.

The actual problem that this script solves may not be too interesting to others, but some of the problems it solves within itself might, so I am posting the source. If you want to use it, it is ready to be used at the command line. Type "python pyBoggle.py" then a space separated list of the letters on your board. The board must be a square - 3x3, 4x4, 5x5...etc for it to word (it checks).

Example:

python pyBoggle.py a d e g n u p t e m l p w e f t

You can download the source here.
Be sure to grab the dictionary here (Place it in the same folder as the script).

Here is the source if you wish to just view it:


import sys

class BoggleSolver:
def __init__(self, letter_list):
self.dictionary = Dictionary("C:\\Dropbox\\Programming Projects\\Python\\PyBoggle\\dictionary.txt")
self.board = Board(letter_list)
self.min_length = 4
self.found_words = set()

# Find all words starting from each coordinate position
for row in xrange(self.board.side_length):
for column in xrange(self.board.side_length):
self._find_words(Word.new(row, column), row, column)

def _find_words(self, word, row, column):
word.add_letter(self.board[row][column], row, column)

if (self._can_add_word(word)):
self.found_words.add(word.letter_sequence)

for row, column in self._get_valid_coodinates_for_word(word, row, column):
if(self.dictionary.contains_prefix(word.letter_sequence + self.board[row][column])):
self._find_words(Word.new_from_word(word), row, column)

def _can_add_word(self, word):
return len(word) >= self.min_length and self.dictionary.contains_word(word.letter_sequence)

def _get_valid_coodinates_for_word(self, word, row, column):
for r in range(row - 1, row + 2):
for c in range(column - 1, column + 2):
if r >= 0 and r < self.board.side_length and c >= 0 and c < self.board.side_length:
if ((r, c) not in word.used_board_coordinates):
yield r, c

class Board:
def __init__(self, letter_list):
self.side_length = len(letter_list) ** .5
if (self.side_length != int(self.side_length)):
raise Exception("Board must have equal sides! (4x4, 5x5...)")
else:
self.side_length = int(self.side_length)

self.board = []

index = 0
for row in xrange(self.side_length):
self.board.append([])
for column in xrange(self.side_length):
self.board[row].append(letter_list[index])
index += 1

def __getitem__(self, row):
return self.board[row]

class Word:
def __init__(self):
self.letter_sequence = ""
self.used_board_coordinates = set()

@classmethod
def new(cls, row, column):
word = cls()
word.used_board_coordinates.add((row, column))
return word

@classmethod
def new_from_word(cls, word):
new_word = cls()
new_word.letter_sequence += word.letter_sequence
new_word.used_board_coordinates.update(word.used_board_coordinates)
return new_word

def add_letter(self, letter, row, column):
self.letter_sequence += letter
self.used_board_coordinates.add((row, column))

def __str__(self):
return self.letter_sequence

def __len__(self):
return len(self.letter_sequence)

class Dictionary:
def __init__(self, dictionary_file):
self.words = set()
self.prefixes = set()
word_file = open(dictionary_file, "r")

for word in word_file.readlines():
self.words.add(word.strip())
for index in xrange(len(word.strip()) + 1):
self.prefixes.add(word[:index])

def contains_word(self, word):
return word in self.words

def contains_prefix(self, prefix):
return prefix in self.prefixes

if __name__ == "__main__":
boggleSolver = BoggleSolver(sys.argv[1:])
words = boggleSolver.found_words
print words



Enjoy.

Saturday, August 8, 2009

Python + Google Voice. Mass SMS and Iterative Calling at the Command Line

EDIT (Jan 2011): Google changed the way contacts are downloaded. Many of the scripts below will break. Use the updated version here.

EDIT (Oct 3 2009): Google changed a few things on their login page which broke my old scripts. I have updated the scripts in this post, including those that you can download. If you have been receiving "Could not log in with provided credentials" errors, these new scripts should fix that problem.

You can download a ready-to-use-no-Python-installation-required Windows executable version of the program
here. Just download, unzip, find the GVMassContact.exe file and double click to use. This version's source is identical to those of scripts located below.

Click here to navigate to the downloadable Python scripts.


I have already written twice about Google Voice (here and here), but the scripts in this installment are an improvement over both of the scripts provided the other posts.

I wanted to create an interactive command line script that would allow me to either send an SMS message or call everyone in one of my Google Contacts Groups. Google Voice does not yet let you send mass text messages, or call people in an iterative fashion, so I came up with a script to let me do just that.

Instead of using Googles gdata Python API to access my Google Contacts, I decided to use Pythons "csv" module to parse an exported csv file downloaded from my GMail account. Doing this lets you run the script without needing to download any other libraries, assuming you are using a version of Python that has all the features used in this script (I use 2.6.2 currently).

The first thing I did was create a "gvoice.py" module with several helpful classes. These allow you to:
  1. Log in
  2. Gather all Google Contacts into separate groups
  3. Selectively narrow down the contacts in a group
  4. Gather the phone numbers that you have entered
  5. Send SMS messages
  6. Place Calls
I am by no means a seasoned Python developer, but what I have created works well for my purposes. I tried to make the classes as loosely coupled with the UI as possible in case I want to put a GUI around it sometime, but for now I am doing everything at the command line (which I often prefer).

The GoogleVoiceLogin class will allow you to log in, get the "opener" which lets you keep your log in cookie data for subsequent requests, and gives you access to the _rnr_se value (the "key") that is used when sending SMS messages or placing a call. Most of the other classes in the "gvoice" module will accept the opener and key as parameters to their constructors.

I created a sample script that uses the classes in my "gvoice" module to:
  1. Prompt the user for his/her Google Account credentials
  2. Allow the user to select a Group from his/her Google Contacts Groups.
  3. Allow the user to narrow down the contact list of the Group (nothing permanent is done to the Contacts)
  4. Choose whether to send an SMS message or call everyone in the list
  5. If calling, it allows you to choose a number from your phone list, or enter a custom number (like the Google Voice site does when placing calls)
The script that I wrote assumes I always want to use the contact's mobile phone (the first one) to send SMS messages and place calls, but that is easy to change.

There are two files needed for this to work - here is the main driver program (gvMassContact.py):


from gvoice import *
import getpass
import sys
import re
import os

# Function used to create a separator
def separator():
return '-' * 25

def get_numeric_input(prompt):
try:
return int(raw_input(prompt))
except:
pass

# Function to clear the screen
def clear_screen():
if os.name == "posix":
# *nix systems
os.system('clear')
elif os.name in ("nt", "dos", "ce"):
# Windows
os.system('CLS')

# Main method to be run
def main():
# Log in
print "Please enter your Google Account credentials"
email = raw_input("User name: ")
password = getpass.getpass("Password: ")

gv = GoogleVoiceLogin(email, password)
if not gv.logged_in:
print "Could not log in with provided credentials"
sys.exit(1)
else:
print "Login successful!"

# Use the ContactLoader to download Google Contacts
contact_loader = ContactLoader(gv.opener)

# Use the ContactSelector to select the group and
# final list of contacts to contact
contact_selector = ContactSelector(contact_loader.contacts_by_group_list)

clear_screen()
group_list = contact_selector.get_group_list()
selected_group = None
while selected_group not in range(1, len(group_list)+1):
print "Your Google Groups"
print separator()
for group_item in group_list:
print "{0}: {1}".format(group_item[0], group_item[1])
print separator()
selected_group = get_numeric_input("Enter the index of the group to select: ")

clear_screen()
# Now that a group is selected, narrow down the list of people in the group
contact_selector.set_selected_group(selected_group)
removing = True
while removing:
print "Contact List"
print separator()
for contact_item in contact_selector.get_contacts_list():
print "{0}: {1}".format(contact_item[0], contact_item[1])
print separator()
try:
input_list = raw_input("Enter a list of the indexes (coma, space or otherwise delimeted)\nof those contacts you do not wish to contact this session.\nPress enter when finished: ")
if input_list != '':
contacts_to_remove_list = [int(match.group(1)) for match in re.finditer(r"(\d+)", input_list)]
contact_selector.remove_from_contact_list(contacts_to_remove_list)
else:
removing = False
except:
pass

clear_screen()
# Print final list
clear_screen()
print "Final List:"
print separator()
for contact_item in contact_selector.get_contacts_list():
print "{0}".format(contact_item[1])
selected_option = None
while selected_option not in [1, 2]:
print separator()
print "Options: "
print "1: Send Text"
print "2: Call"
print separator()
selected_option = get_numeric_input("Select which action to take: ")

# Send texts to all people in contact list
if (selected_option == 1):
print separator()
text_sender = TextSender(gv.opener, gv.key)
text = raw_input("Enter text message. Press enter when finished: ")
text_sender.text = text
for contact in contact_selector.get_contacts_list():
number = contact[1].mobile
if number == '':
print "{0} does not have a mobile number".format(contact[1])
else:
print "Sending message to {0} at {1}...".format(contact[1], contact[1].mobile),
text_sender.send_text(contact[1].mobile)
if text_sender.response:
print "Success!"
else:
print "Failed!!"

# Call all people in contact list
elif (selected_option == 2):
print separator()
number_dialer = NumberDialer(gv.opener, gv.key)

number_retriever = NumberRetriever(gv.opener)
phone_number_items = number_retriever.get_phone_numbers()

clear_screen()
# Get the forwarding number
forwarding_number_input = None
while forwarding_number_input not in range(1, len(phone_number_items) + 2):
print "Select forwarding number"
print separator()
for phone_number_item in phone_number_items:
print "{0}: {1}".format(phone_number_item[0], phone_number_item[1][0])
print "{0}: {1}".format(len(phone_number_items) + 1, "Other")
print separator()
forwarding_number_input = get_numeric_input("Choose from your previously entered numbers, or select \"Other\": ")

if forwarding_number_input in range(1, len(phone_number_items) + 1):
forwarding_number = phone_number_items[forwarding_number_input - 1][1]
else:
forwarding_number = ''
while not re.match(r"\(?\b[0-9]{3}\)?[-. ]?[0-9]{3}[-. ]?[0-9]{4}\b\Z", forwarding_number):
forwarding_number = raw_input("Enter the forwarding number to dial: ")
number_dialer.forwarding_number = forwarding_number

print separator()
# Loop through and make the calls
for contact in contact_selector.get_contacts_list():
number = contact[1].mobile
if number == '':
print "{0} does not have a mobile number".format(contact[1])
else:
input = None
while input not in ['', 'n','N', 'q', 'Q'] :
input = raw_input("Press enter to call {0} at {1} ('n' to skip, 'q' to quit): ".format(contact[1], contact[1].mobile))
if input == '':
print "Calling {0}....".format(contact[1]),
number_dialer.place_call(number)
if number_dialer.response:
print "Success!"
else:
print "Failed!!"
elif input .upper() == 'N':
pass
elif input.upper() == 'Q':
print "Call chain aborted."
break

if __name__ == "__main__":
main()



And here is the other required script (must be named "gvoice.py"):


import csv
import sys
import re
import urllib
import urllib2

class GoogleVoiceLogin:
def __init__(self, email, password):
# Set up our opener
self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor())
urllib2.install_opener(self.opener)

# Define URLs
self.loing_page_url = 'https://www.google.com/accounts/ServiceLogin'
self.authenticate_url = 'https://www.google.com/accounts/ServiceLoginAuth'
self.gv_home_page_url = 'https://www.google.com/voice/#inbox'

# Load sign in page
login_page_contents = self.opener.open(self.loing_page_url).read()

# Find GALX value
galx_match_obj = re.search(r'name="GALX"\s*value="([^"]+)"', login_page_contents, re.IGNORECASE)

galx_value = galx_match_obj.group(1) if galx_match_obj.group(1) is not None else ''

# Set up login credentials
login_params = urllib.urlencode( {
'Email' : email,
'Passwd' : password,
'continue' : 'https://www.google.com/voice/account/signin',
'GALX': galx_value
})

# Login
self.opener.open(self.authenticate_url, login_params)

# Open GV home page
gv_home_page_contents = self.opener.open(self.gv_home_page_url).read()

# Fine _rnr_se value
key = re.search('name="_rnr_se".*?value="(.*?)"', gv_home_page_contents)

if not key:
self.logged_in = False
else:
self.logged_in = True
self.key = key.group(1)

class ContactLoader():
def __init__(self, opener):
self.opener = opener
self.contacts_csv_url = "http://mail.google.com/mail/contacts/data/export"
self.contacts_csv_url += "?groupToExport=^Mine&exportType=ALL&out=OUTLOOK_CSV"

# Load ALL Google Contacts into csv dictionary
self.contacts = csv.DictReader(self.opener.open(self.contacts_csv_url))

# Create dictionary to store contacts and groups in an easier format
self.contact_group = {}
# Assigned each person to a group that we can get at later
for row in self.contacts:
if row['First Name'] != '':
for category in row['Categories'].split(';'):
if category == '':
category = 'Ungrouped'
if category not in self.contact_group:
self.contact_group[category] = [Contact(row)]
else:
self.contact_group[category].append(Contact(row))

# Load contacts into a list of tuples...
# [(1, ('group_name', [contact_list])), (2, ('group_name', [contact_list]))]
self.contacts_by_group_list = [(id + 1, group_contact_item)
for id, group_contact_item in enumerate(self.contact_group.items())]

class Contact():
def __init__(self,contact_detail):
self.first_name = contact_detail['First Name'].strip()
self.last_name = contact_detail['Last Name'].strip()
self.mobile = contact_detail['Mobile Phone'].strip()
self.email = contact_detail['E-mail Address'].strip()

def __str__(self):
return self.first_name + ' ' + self.last_name

# Class to assist in selected contacts by groups
class ContactSelector():
def __init__(self, contacts_by_group_list):
self.contacts_by_group_list = contacts_by_group_list
self.contact_list = None

def get_group_list(self):
return [(item[0], item[1][0]) for item in self.contacts_by_group_list]

def set_selected_group(self, group_id):
self.contact_list = self.contacts_by_group_list[group_id - 1][1][1]

# Return the contact list so far
def get_contacts_list(self):
return [(id + 1, contact) for id, contact in enumerate(self.contact_list)]

# Accept a list of indexes to remove from the current contact list
# Assumes 1 based list being passed in
def remove_from_contact_list(self, contacts_to_remove_list):
if self.contact_list == None:
return
for id in contacts_to_remove_list:
if id in range(0, len(self.contact_list)+1):
self.contact_list[id - 1] = None
self.contact_list = [contact for contact in self.contact_list if contact is not None]

class NumberRetriever():
def __init__(self, opener):
self.opener = opener
self.phone_numbers_url = 'https://www.google.com/voice/settings/tab/phones'
phone_numbers_page_content = self.opener.open(self.phone_numbers_url).read()

# Build list of all numbers and their aliases
self.phone_number_items = [(match.group(1), match.group(2))
for match
in re.finditer('"name":"([^"]+)","phoneNumber":"([^"]+)"',
phone_numbers_page_content)]

def get_phone_numbers(self):
return [(id + 1, (phone_number_item))
for id, phone_number_item
in enumerate(self.phone_number_items)]

class TextSender():
def __init__(self, opener, key):
self.opener = opener
self.key = key
self.sms_url = 'https://www.google.com/voice/sms/send/'
self.text = ''

def send_text(self, phone_number):
sms_params = urllib.urlencode({
'_rnr_se': self.key,
'phoneNumber': phone_number,
'text': self.text
})
# Send the text, display status message
self.response = self.opener.open(self.sms_url, sms_params).read()

class NumberDialer():
def __init__(self, opener, key):
self.opener = opener
self.key = key
self.call_url = 'https://www.google.com/voice/call/connect/'
self.forwarding_number = None

def place_call(self, number):
call_params = urllib.urlencode({
'outgoingNumber' : number,
'forwarding_number' : self.forwarding_number,
'subscriberNumber' : 'undefined',
'remember' : '0',
'_rnr_se': self.key
})

# Send the text, display status message
self.response = self.opener.open(self.call_url, call_params).read()


For the "gvMassContact.py" script to work, you need to have the "gvoice.py" file located in the same folder.

If you would rather not copy and paste, you can download the files here:

If you don't care about having the files separated, and would rather have to deal with just one script that you can keep on your desktop, you can download this file:
Here is a new, ready-to-use-no-Python-installation-required Windows executable version. Just download, unzip, find GVMassContact.exe in the GVMassContact folder, double click and go.

The only difference between the "allInOne.py" script and the others is that all of the classes contained in the "gvoice.py" file are located at the top of the file.

If you download the "gvAllInOne.py" script, you can keep it on your desktop and simply double click it to get the interactive command line session to come up.

Enjoy!

Easier Python script execution in Widows

While this post does not contain a sample script as all previous posts do, it can make creating and executing scripts easier if you are working on a Windows machine. There are two things that I like to set up to accomplish this:

1) Make widows execute scripts at the command line without needing to type "python" before the name of the script, or the letters ".py" after the name of the script.
2) Put the folder that contains all of my commonly used scripts on the system Path.

To accomplish the first step, do this:
Control Panel -> System -> Advanced System Settings -> Environments Variables
In the new window that shows up, scroll down in the bottom list to find PATHEXT. Double click on it and add ";.PY" to the end.

























Once you are done with that, double click on the "Path". Append ";[FULL PATH TO YOUR SCRIPT FOLDER]" to what is already there.


























Done!

If you have a script in your folder that you just added to your Path called "helloWorld.py" you can now simply type "helloWorld" and it will be run. It isn't that much better than "python helloWorld.py", but I prefer this method.