-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathxkcd.py
39 lines (35 loc) · 1.3 KB
/
xkcd.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import click
import json
from PIL import Image
import requests
from io import BytesIO
from random import randint
@click.command()
@click.option('--random', flag_value='random', default=False, help='Get Random Comic!')
def cli(random):
"""XKCD Terminal Tool"""
try:
from sh import lolcat, figlet # Hacky fix for Build to pass system packages
print(lolcat(figlet("-c", "X K C D")))
except ImportError:
print("Welcome to xkcd Comics!")
try:
with requests.Session() as s:
content = s.get("https://xkcd.com/info.0.json").content.decode()
data = json.loads(content)
HighestNumber = data["num"]
if random == 'random':
rand_digits = randint(1, HighestNumber)
endpoint = "https://xkcd.com/{}/info.0.json".format(rand_digits)
content = s.get(endpoint).content.decode()
data = json.loads(content)
res = s.get(data["img"])
img = Image.open(BytesIO(res.content))
img.show()
else:
res = s.get(data["img"])
img = Image.open(BytesIO(res.content))
img.show()
except requests.ConnectionError:
error_image = Image.open("assets/xkcd_404.jpg")
error_image.show()