all repos — python-meme-bot @ ee18ea77890feb2d14eb445366f8c6c3e07d5b9f

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,s"
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": rating + tags,
43    }
44    
45    if tags != "":
46        max_pages = 50
47        
48    count = 0
49    while count < max_tries:
50        params['page'] = random.randint(1, max_pages)
51        page = requests.get(base_url + page_suffix, params).json()
52        n = random.randint(0, params['limit'] - 1)
53        
54        #print("Page: " + str(params['page']))
55        #print("File: " + str(n))
56        try:
57            file_url = page[n]['file_url']
58            if not _valid_extension(file_url):
59                raise Exception
60            r = requests.get(file_url)
61            img = Image.open(BytesIO(r.content))
62            link = base_url + post_suffix + str(page[n]['id'])
63            return img, link
64            
65        except (KeyError, IndexError, Exception):
66            logging.warning("Can't display image.")
67        except UnidentifiedImageError:
68            logging.warning("Unidentified image: " + file_url)
69        
70        count += 1
71        logging.warning(f"Try #{count} failed.\n")
72        #time.sleep(sleep_seconds)
73    logging.error(f"Reached {count} tries. Giving up.")
74    return None, None