Created
August 3, 2014 23:48
-
-
Save Skirmisher/6dae9ebc6b611b998010 to your computer and use it in GitHub Desktop.
A little Python script that posts the latest xkcd comic to Tumblr, given the right conditions. Mostly by Physicynicism ( http://physicynicism.com ), edited and cleaned up by me. And now has more things to be fixed!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import pytumblr, json, requests, datetime, io, sys | |
#get XKCD info with json | |
class Xkcd: | |
'''stores comic metadata | |
num -- the comic number as a string (default "''" for latest comic) | |
''' | |
def __init__(self,num=''): | |
r=requests.get('http://xkcd.com/'+num+'/info.0.json') | |
self.json=json.loads(str(r.text)) | |
self.num=self.json['num'] | |
self.url='http://xkcd.com/'+str(self.num)+'/' | |
self.title=str(self.json['title']) | |
self.alttext=str(self.json['alt']) | |
self.img=str(self.json['img']) | |
self.date=datetime.date(int(self.json['year']),int(self.json['month']),int(self.json['day'])) | |
def getUrl(self): | |
return self.url | |
def getTitle(self): | |
return self.title | |
def getAltText(self): | |
return self.alttext | |
def getImg(self): | |
return self.img | |
def getDate(self): | |
return self.date | |
def getNum(self): | |
return self.num | |
latest = Xkcd() | |
#check num | |
with io.open('lastnum', 'r') as file: | |
lastnum=int(file.readline()) | |
if lastnum == latest.getNum(): | |
sys.exit() | |
#if all good, post to Tumblr | |
client = pytumblr.TumblrRestClient( | |
'I', | |
'am not', | |
'stupid', | |
'this time' | |
) | |
client.info() | |
#actual post function | |
def PostLatest(): | |
return client.create_photo('xkcds', | |
source=latest.getImg(), | |
caption='<p><em>'+latest.getAltText()+'</em></p>\n<p><a href="'+latest.getUrl()+'">'+latest.getTitle()+'</a> '+ | |
'[<a href="http://www.explainxkcd.com/wiki/index.php/'+str(latest.getNum())+'">explained</a>]</p>', | |
link=latest.getUrl(), | |
tags=('xkcd','webcomic','comic') | |
) | |
response = PostLatest() | |
posted = (u'id' in response.keys()) | |
count = 1 | |
while not posted: | |
if count >= 5: | |
print '['+datetime.datetime.now()+'] Error. Max attempt count exceeded, exiting.' | |
sys.exit() | |
count += 1 | |
print '['+datetime.datetime.now()+'] Error. Trying again.' | |
response = PostLatest() | |
posted = (u'id' in response.keys()) | |
print '['+datetime.datetime.now()+'] Posted comic #'+str(latest.getNum())+' successfully.' | |
#store num for later comparison | |
with io.open('lastnum', 'wb') as file: | |
file.seek(0) | |
file.write(str(latest.getNum())) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment