Last active
September 19, 2024 13:25
-
-
Save maciekmm/3868d531d081b51f6e52 to your computer and use it in GitHub Desktop.
Small python script for downloading comic info from xkcd, primarily made for xfce genmon plugin.
This file contains hidden or 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
#!/usr/bin/python | |
import sys | |
import urllib2 | |
import json | |
import os | |
import argparse | |
from PIL import Image | |
from random import randint | |
def get_random_comic(): | |
return get_comic_for_id(randint(1, get_comic_for_id(-1)["num"])) | |
def get_comic_for_id(id): | |
url = "http://xkcd.com/" | |
if id > 0: | |
url += str(id) + "/" | |
url += "info.0.json" | |
res = urllib2.urlopen(url) | |
if res.getcode() != 200: | |
raise ValueError("XKCD.com seems to be down") | |
return json.loads(res.read()) | |
def main(): | |
parser = argparse.ArgumentParser( | |
description='Gets information about xkcd comics') | |
parser.add_argument( | |
'-i', '--id', help='Gets comic connected with given identifier\nIf negative or no value is provided, random comic will be displayed.') | |
parser.add_argument( | |
'-o', '--option', help='Extracts certain parameter from comic i.e. url.', type=str) | |
parser.add_argument( | |
'-g', '--genmon', help='Downloads file and styles output for xfce genmon plugin', action='store_true') | |
args = parser.parse_args() | |
id = args.id | |
if not id: | |
id = -1 | |
try: | |
comic = get_comic_for_id(id) if id >= 0 else get_random_comic() | |
if args.genmon: | |
max_width, max_height = 1000, 900 | |
response = urllib2.urlopen(comic["img"]) | |
filePath = os.path.dirname(os.path.realpath(__file__)) + '/xkcd.png' | |
with open(filePath, 'w') as file: | |
file.write(response.read()) | |
file.close() | |
im = Image.open(filePath) | |
image_width, image_height = im.size | |
ratio = min(max_width/float(image_width), max_height/float(image_height)) | |
if ratio < 1: | |
newsize = image_width*ratio, image_height*ratio | |
im.thumbnail(newsize, Image.ANTIALIAS) | |
im.save(filePath, "PNG") | |
print '<tool>#' + str(comic["num"]) + " " + comic["title"] + '</tool>' | |
print '<img>' + os.path.dirname(os.path.realpath(__file__)) + '/xkcd.png</img>' | |
# print '<click>xdg-open http://xkcd.com/'+str(comic["num"])+'/</click>' | |
# opens comic in default browser - looks terrible due to hover background | |
elif args.option: | |
print comic[args.option] | |
else: | |
print json.dumps(comic) | |
except Exception as e: | |
print(e) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment