importreimporturllibimportImageimportcStringIOfromoauth_hookimportOAuthHookimportrequests# This is the APOD index pageapodbaseurl='http://apod.nasa.gov/apod/{}'# This is how we look for the image on the pageregex=r'a href="(image.*)"'# You can adjust this but twitter only allows 800k uploadsimgsize=900,900# This our twitter API endpoint for changing the backgroundtwitter_endpoint='http://api.twitter.com/1/account/update_profile_background_image.json'# Create a twitter app: https://dev.twitter.com/apps/new# 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 requestoauth_hook=OAuthHook(access_token,access_token_secret,header_auth=True)defget_apod_image():# grab the mainpageapodpage=urllib.urlopen(apodbaseurl.format('astropix.html')).read()# find image urlapodurl=re.search(regex,apodpage).group(1)# open the image fileimgfile=urllib.urlopen(apodbaseurl.format(apodurl))# parse it into memory (cStringIO is faster than StringIO)imgstr=cStringIO.StringIO(imgfile.read())img=Image.open(imgstr)img.convert("RGB")# resize preserving aspect ratioimg.thumbnail(imgsize,Image.ANTIALIAS)# save it in the smallest size possibleimg.save("apod.png","PNG",optimize=True)defupdate_twitter():client=requests.session(hooks={'pre_request':oauth_hook})image=open('apod.png','rb')response=client.post(twitter_endpoint,'',params={'tile':True},files={'image':('apod.png',image)})# lets print and return some info for troubleshootingprintresponse.textreturnresponseif__name__=='__main__':get_apod_image()update_twitter()