Last Updated: February 25, 2016
· ranman

Make your twitter background everyday

So I like space and I thought my twitter background should reflect that.

Wouldn't it be cool if this:


Could be this:




So you can probably just run (hopefully in a virtualenv):

pip install PIL requests requests-oauth

Next you'll want to use this script:

import re
import urllib
import Image
import cStringIO
from oauth_hook import OAuthHook
import requests

# This is the APOD index page
apodbaseurl = '{}'
# This is how we look for the image on the page
regex = r'a href="(image.*)"'
# You can adjust this but twitter only allows 800k uploads
imgsize = 900, 900
# This our twitter API endpoint for changing the background
twitter_endpoint = ''

# Create a twitter app:
# After creation and clicking the generate access token button, click through
# to the oauth tab and use the info from there in the variables below.
OAuthHook.consumer_key = 'blarg'
OAuthHook.consumer_secret = 'blarg'
access_token = 'blarg'
access_token_secret = 'blarg'
# Setup the hook to call before we make a request
oauth_hook = OAuthHook(access_token, access_token_secret, header_auth=True)

def get_apod_image():
    # grab the mainpage
    apodpage = urllib.urlopen(apodbaseurl.format('astropix.html')).read()
    # find image url
    apodurl =, apodpage).group(1)
    # open the image file
    imgfile = urllib.urlopen(apodbaseurl.format(apodurl))
    # parse it into memory (cStringIO is faster than StringIO)
    imgstr = cStringIO.StringIO(
    img =
    # resize preserving aspect ratio
    img.thumbnail(imgsize, Image.ANTIALIAS)
    # save it in the smallest size possible"apod.png", "PNG", optimize=True)

def update_twitter():
    client = requests.session(hooks={'pre_request': oauth_hook})
    image = open('apod.png', 'rb')
    response =, '', params={'tile': True},
                           files={'image': ('apod.png', image)})
    # lets print and return some info for troubleshooting
    print response.text
    return response

if __name__ == '__main__':

Now make a cronjob with something like:

0 23 * * * ~/.virtualenvs/apod/bin/python ~/apod/

AND BOOM! You're done.