Auto-updating Twitter background image

Posted: Aug 19, 2013

If you look at my Twitter profile you may notice the background is an (almost) live shot of the Washington, DC skyline.

First, the source of the image: I used Weatherbug to track down an appropriate camera. Right-click and Copy Image Source shows that it's a very simple system: a static JPG image URL (you can ignore the ?rnd=... bit; it's just for cache busting.)

OK, so I've got the source for my background image, how to automate updating it? Twitter has an appropriate API and Python's Tweepy already has a wrapper for it.

In order to use this API call, you need to create a Twitter app and get it's access credentials (and OAUTH token and secret) and then authorize the app to be able to read/write to your profile (another token/secret pair). You can do this here: https://dev.twitter.com/app

The script I hacked together is below. Annoyingly, Tweepy.update_profile_background_image expects a filename, not a File object, so it seems I have to actually save the image to a temp file first.

import tweepy
import tempfile
import urllib

url = 'http://wwc.instacam.com/instacamimg/KDCA/KDCA_l.jpg'

# The consumer keys can be found on your application's Details
# page located at https://dev.twitter.com/apps (under "OAuth settings")
auth = tweepy.OAuthHandler('consumer key goes here', 'consumer secret goes here')

# The access tokens can be found on your applications's Details
# page located at https://dev.twitter.com/apps (located 
# under "Your access token")
auth.set_access_token('access token goes here', 'access secret goes here')

api = tweepy.API(auth)

try:
    (filename, headers) = urllib.urlretrieve(url) # download image
    api.update_profile_background_image(filename, use=1, tile=0) # update profile
    # This may fail. See updated script below.
finally:
    os.remove(filename)

Next up is to fix two problems: first, abstract out the secret tokens (they have write access to your Twitter account!). Storing these secrets in enviornment values also makes it much easier to deploy to Heroku. Next is that for some unknown reason the Twitter API call fails with error 131 very, very frequently for no apparent reason.

My updated script is available here: https://gist.github.com/elidickinson/6237607

Now here's the trick to getting it to run periodically for free: Deploy it as a Heroku app with an empty Procfile and zero processes. Then add Heroku Scheduler to your account and via the web interface, set it to run your script every hour. Ta da!

Next steps: Making it a web service that anybody can use!

Questions? Comments? Tweet me.