Add Twitter Profile Images to Lion Address Book with AppleScript

The famous Cabel Sasser of Panic put out a tweet the other day regarding Lion’s Address Book’s new Twitter username support:

@cabel: Dear Lion, Since there's a 'Twitter' field in Address Book, get the user picture! Then Mail's "Show contact photos in message list" = great.

I thought I’d take up the challenge and I hobbled together an AppleScript to pull this information down.

set twitterJSONField to "<profile_image_url>"
set twitterProfileImagePath to "/tmp/twitterProfileImage"

tell application "Contacts"
    set theSelection to selection
    repeat with thePerson in theSelection
        set twitterUsername to (user name of first social profile of thePerson whose service name is "Twitter")
        set twitterProfileJSON to do shell script "curl http://twitter.com/users/show/" & twitterUsername

        set theStart to offset of twitterJSONField in twitterProfileJSON
        set theRest to (characters (theStart + (length of twitterJSONField)) through (length of twitterProfileJSON) of twitterProfileJSON) as text
        set theSize to offset of "_normal" in theRest
        set theEnd to offset of "<" in theRest
        set theImageURL to (characters 1 through (theSize - 1) of theRest) & (characters (theSize + 7) through (theEnd - 1) of theRest) as text

        tell me to set AppleScript's text item delimiters to "\\"
        set theImageURLChunks to every text item of theImageURL
        tell me to set AppleScript's text item delimiters to ""
        set theImageURL to theImageURLChunks as text

        do shell script "curl -s '" & theImageURL & "' > " & twitterProfileImagePath
        set the twitterImageFile to (POSIX file twitterProfileImagePath) as alias
        set theImage to (read twitterImageFile as "TIFF")
        do shell script "rm " & twitterProfileImagePath

        set image of thePerson to theImage
        save
    end repeat
end tell

The script is a bit rough around the edges… has some clunky text parsing code, and no error checking code. It works off the user’s selection. So, select one user who has a Twitter username set in their address book card, and run the script. Assuming that all works well for you, you can make a Smart Group for people with Twitter info in their profile:

"Card Contains Twitter" Smart Group

Select every person in the group, and then run the script.

Lastly, to make the script feel like a more natural piece of Address Book, I recommend activating the AppleScript menu (inside AppleScript Editor’s preferences), and storing the script in ~/Library/Scripts/Applications/Address Book.

Using the script via the AppleScript menu

If there’s enough demand, I’ll update the script to be a bit more clever, loop through the entire address book, and report on what it was and wasn’t able to do.

Tuesday, August 2, 2011   ()