|
| 1 | +import urllib3 |
| 2 | +import urllib |
| 3 | +import simplejson as json |
| 4 | +import re |
| 5 | + |
| 6 | + |
| 7 | +class Jokes: |
| 8 | + def __init__(self): |
| 9 | + self.http = urllib3.PoolManager() |
| 10 | + print("Sv443's JokeAPI") |
| 11 | + |
| 12 | + def build_request( |
| 13 | + self, |
| 14 | + category=[], |
| 15 | + blacklist=[], |
| 16 | + response_format="json", |
| 17 | + type=None, |
| 18 | + search_string=None, |
| 19 | + id_range=None, |
| 20 | + amount=1, |
| 21 | + lang="en" |
| 22 | + ): |
| 23 | + r = "https://sv443.net/jokeapi/v2/joke/" |
| 24 | + |
| 25 | + if len(category): |
| 26 | + for c in category: |
| 27 | + if not c.lower() in ["programming", "miscellaneous", "dark", "pun"]: |
| 28 | + raise ValueError( |
| 29 | + f'''Invalid category selected. |
| 30 | + You selected {c}. |
| 31 | + Available categories are: |
| 32 | + "programming" |
| 33 | + "miscellaneous" |
| 34 | + "dark" |
| 35 | + "pun". |
| 36 | + Leave blank for any.''' |
| 37 | + ) |
| 38 | + |
| 39 | + cats = ",".join(category) + "?" |
| 40 | + else: |
| 41 | + cats = "Any?" |
| 42 | + |
| 43 | + if len(blacklist) > 0: |
| 44 | + for b in blacklist: |
| 45 | + if b not in [ |
| 46 | + "nsfw", |
| 47 | + "religious", |
| 48 | + "political", |
| 49 | + "racist", |
| 50 | + "sexist" |
| 51 | + ]: |
| 52 | + raise ValueError( |
| 53 | + '''\n\n |
| 54 | + You have blacklisted flags which are not available or you have not put the flags in a list. |
| 55 | + Available flags are: |
| 56 | + "racist" |
| 57 | + "religious" |
| 58 | + "political" |
| 59 | + "sexist" |
| 60 | + "nsfw" |
| 61 | + ''' |
| 62 | + ) |
| 63 | + return |
| 64 | + blacklistFlags = ",".join(blacklist) |
| 65 | + else: |
| 66 | + blacklistFlags = None |
| 67 | + |
| 68 | + if response_format not in ["json", "xml", "yaml", "txt"]: |
| 69 | + raise Exception( |
| 70 | + "Response format must be either json, xml, txt or yaml." |
| 71 | + ) |
| 72 | + if type: |
| 73 | + if type not in ["single", "twopart"]: |
| 74 | + raise ValueError( |
| 75 | + '''Invalid joke type. |
| 76 | + Available options are "single" or "twopart".''' |
| 77 | + ) |
| 78 | + return |
| 79 | + else: |
| 80 | + type = "Any" |
| 81 | + |
| 82 | + if search_string: |
| 83 | + if not isinstance(search_string, str): |
| 84 | + raise ValueError("search_string must be a string.") |
| 85 | + return |
| 86 | + else: |
| 87 | + search_string = urllib.parse.quote(search_string) |
| 88 | + if id_range: |
| 89 | + |
| 90 | + response = self.http.request( |
| 91 | + 'GET', |
| 92 | + "https://sv443.net/jokeapi/v2/info" |
| 93 | + ) |
| 94 | + dict = json.loads(response.data) |
| 95 | + range_limit = dict["jokes"]["totalCount"] |
| 96 | + |
| 97 | + if len(id_range) > 2: |
| 98 | + raise ValueError("id_range must be no longer than 2 items.") |
| 99 | + elif id_range[0] < 0: |
| 100 | + raise ValueError( |
| 101 | + "id_range[0] must be greater than or equal to 0." |
| 102 | + ) |
| 103 | + elif id_range[1] > range_limit: |
| 104 | + raise ValueError( |
| 105 | + f"id_range[1] must be less than or equal to {range_limit-1}." |
| 106 | + ) |
| 107 | + |
| 108 | + r += cats |
| 109 | + |
| 110 | + r += f"?format={response_format}" |
| 111 | + |
| 112 | + if blacklistFlags: |
| 113 | + r += f"&blacklistFlags={blacklistFlags}" |
| 114 | + |
| 115 | + |
| 116 | + r += f"&type={type}" |
| 117 | + |
| 118 | + if search_string: |
| 119 | + r += f"&contains={search_string}" |
| 120 | + if id_range: |
| 121 | + r += f"i&dRange={id_range[0]}-{id_range[1]}" |
| 122 | + if amount > 10: |
| 123 | + raise ValueError( |
| 124 | + f"amount parameter must be no greater than 10. you passed {amount}." |
| 125 | + ) |
| 126 | + r += f"&amount={amount}" |
| 127 | + |
| 128 | + r += f"&lang={lang}" |
| 129 | + |
| 130 | + return r |
| 131 | + |
| 132 | + def send_request(self, |
| 133 | + request, |
| 134 | + response_format, |
| 135 | + return_headers, |
| 136 | + auth_token, |
| 137 | + user_agent |
| 138 | + ): |
| 139 | + returns = [] |
| 140 | + |
| 141 | + if auth_token: |
| 142 | + r = self.http.request('GET', |
| 143 | + request, |
| 144 | + headers={'Authorization': str(auth_token), |
| 145 | + 'user-agent': str(user_agent), |
| 146 | + 'accept-encoding': 'gzip' |
| 147 | + } |
| 148 | + ) |
| 149 | + else: |
| 150 | + r = self.http.request('GET', request, headers={'user-agent': str(user_agent)}) |
| 151 | + |
| 152 | + data = r.data |
| 153 | + |
| 154 | + if response_format == "json": |
| 155 | + try: |
| 156 | + data = json.loads(data) |
| 157 | + except: |
| 158 | + print(data) |
| 159 | + raise |
| 160 | + else: |
| 161 | + data = str(data)[2:-1].replace(r'\n', '\n').replace('\\', '') |
| 162 | + if len(' '.join(re.split("error", data.lower().replace("\n", "NEWLINECHAR"))[0:][1:]).replace( |
| 163 | + '<', '').replace('/', '').replace(' ', '').replace(':', '').replace('>', '').replace('NEWLINECHAR', '\n')) == 4: |
| 164 | + return [Exception(f"API returned an error. Full response: \n\n {data}")] |
| 165 | + |
| 166 | + headers = str(r.headers).replace(r'\n', '').replace( |
| 167 | + '\n', '').replace(r'\\', '').replace(r"\'", '')[15:-1] |
| 168 | + |
| 169 | + returns.append(data) |
| 170 | + if return_headers: |
| 171 | + returns.append(headers) |
| 172 | + |
| 173 | + if auth_token: |
| 174 | + returns.append({"Token-Valid": bool(int(re.split(r"Token-Valid", headers)[1][4]))}) |
| 175 | + |
| 176 | + return returns |
| 177 | + |
| 178 | + def get_joke( |
| 179 | + self, |
| 180 | + category=[], |
| 181 | + blacklist=[], |
| 182 | + response_format="json", |
| 183 | + type=None, |
| 184 | + search_string=None, |
| 185 | + id_range=None, |
| 186 | + amount=None, |
| 187 | + lang=None, |
| 188 | + auth_token=None, |
| 189 | + user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:77.0) Gecko/20100101 Firefox/77.0", |
| 190 | + return_headers=False |
| 191 | + ): |
| 192 | + r = self.build_request( |
| 193 | + category, blacklist, response_format, type, search_string, id_range, amount, lang |
| 194 | + ) |
| 195 | + |
| 196 | + response = self.send_request(r, response_format, return_headers, auth_token, user_agent) |
| 197 | + return response |
0 commit comments