all repos — python-meme-bot @ 527645384b084fc8e88633dd3057b8a05140a4d6

Telegram Bot that uses PIL to compute light image processing.

Api.py (view raw)

 1
 2from PIL import Image, UnidentifiedImageError
 3from io import BytesIO
 4import requests, random, time, logging
 5
 6base_url = "https://danbooru.donmai.us/"
 7base_url_test = "https://testbooru.donmai.us/"
 8
 9ratings = [
10    'g', # general
11    's', # sensitive
12    'q', # questionable
13    'e', # explicit
14]
15
16rating_normal = "rating:g"
17rating_lewd = "rating:s,q"
18
19supported_file_types = [
20    ".jpg",
21    ".jpeg",
22    ".png"
23]
24
25def _valid_extension(fname: str):
26    for t in [".jpg", ".jpeg", ".png"]:
27        if fname.lower().endswith(t):
28            return True
29    return False
30
31def get_random_image(rating=rating_normal, tags=""):
32    page_suffix = "post/index.json"
33    post_suffix = "posts/"
34    
35    limit = 100
36    max_pages = 1000
37    sleep_seconds = 3
38    max_tries = 5
39
40    params = {
41        "limit": limit,
42        #"tags": "order:change_desc rating:" + rating,
43        "tags": rating + tags,
44    }
45    
46    if tags != "":
47        max_pages = 50
48        
49    count = 0
50    while count < max_tries:
51        params['page'] = random.randint(1, max_pages)
52        page = requests.get(base_url + page_suffix, params).json()
53        n = random.randint(0, params['limit'] - 1)
54        
55        #print("Page: " + str(params['page']))
56        #print("File: " + str(n))
57        try:
58            file_url = page[n]['file_url']
59            if not _valid_extension(file_url):
60                raise Exception
61            r = requests.get(file_url)
62            img = Image.open(BytesIO(r.content))
63            link = base_url + post_suffix + str(page[n]['id'])
64            return img, link
65            
66        except (KeyError, IndexError, Exception):
67            logging.warning("Can't display image.")
68        except UnidentifiedImageError:
69            logging.warning("Unidentified image: " + file_url)
70        
71        count += 1
72        logging.warning(f"Try #{count} failed.\n")
73        #time.sleep(sleep_seconds)
74    logging.error(f"Reached {count} tries. Giving up.")
75    return None, None