11import urllib3
22import urllib
3+ import urllib .request
34import simplejson as json
45import re
56
67
8+ class CategoryError (Exception ):
9+ pass
10+
11+
12+ class BlacklistError (Exception ):
13+ pass
14+
15+
16+ class ResponseTypeError (Exception ):
17+ pass
18+
19+
20+ class JokeTypeError (Exception ):
21+ pass
22+
23+
724class Jokes :
825 def __init__ (self ):
926 self .http = urllib3 .PoolManager ()
10- self .info = self .http .request ('GET' , "https://sv443.net/jokeapi/v2/info" )
27+ self .info = self .http .request (
28+ 'GET' , "https://sv443.net/jokeapi/v2/info" )
1129 self .info = data = json .loads (self .info .data .decode ('utf-8' ))["jokes" ]
1230
1331 def build_request (
@@ -26,7 +44,7 @@ def build_request(
2644 if len (category ):
2745 for c in category :
2846 if not c .title () in self .info ["categories" ]:
29- raise ValueError (
47+ raise CategoryError (
3048 f'''Invalid category selected.
3149 You selected { c } .
3250 Available categories are:
@@ -39,31 +57,34 @@ def build_request(
3957 else :
4058 cats = "Any"
4159
42- if len (blacklist ) > 0 :
43- for b in blacklist :
44- if b not in self .info ["flags" ]:
45- raise ValueError (
46- f'''
60+ if type (blacklist ) in [list , tuple ]:
61+ if len (blacklist ) > 0 :
62+ for b in blacklist :
63+ if b not in self .info ["flags" ]:
64+ raise BlacklistError (
65+ f'''
4766
4867
49- You have blacklisted flags which are not available or you have not put the flags in a list.
50- Available flags are:
51- { """
52- """ .join (self .info ["flags" ])}
53- '''
54- )
55- return
56- blacklistFlags = "," .join (blacklist )
68+ You have blacklisted flags which are not available.
69+ Available flags are:
70+ { """
71+ """ .join (self .info ["flags" ])}
72+ '''
73+ )
74+ return
75+ blacklistFlags = "," .join (blacklist )
76+ else :
77+ blacklistFlags = None
5778 else :
58- blacklistFlags = None
79+ raise BlacklistError ( f'''blacklist must be a list or tuple.''' )
5980
6081 if response_format not in ["json" , "xml" , "yaml" , "txt" ]:
61- raise Exception (
82+ raise ResponseTypeError (
6283 "Response format must be either json, xml, txt or yaml."
6384 )
6485 if type :
6586 if type not in ["single" , "twopart" ]:
66- raise ValueError (
87+ raise JokeTypeError (
6788 '''Invalid joke type.
6889 Available options are "single" or "twopart".'''
6990 )
@@ -98,7 +119,6 @@ def build_request(
98119 if blacklistFlags :
99120 r += f"&blacklistFlags={ blacklistFlags } "
100121
101-
102122 r += f"&type={ type } "
103123
104124 if search_string :
@@ -107,7 +127,7 @@ def build_request(
107127 r += f"i&dRange={ id_range [0 ]} -{ id_range [1 ]} "
108128 if amount > 10 :
109129 raise ValueError (
110- f"amount parameter must be no greater than 10. you passed { amount } ."
130+ f"amount parameter must be no greater than 10. you passed { amount } ."
111131 )
112132 r += f"&amount={ amount } "
113133
@@ -121,19 +141,21 @@ def send_request(self,
121141 return_headers ,
122142 auth_token ,
123143 user_agent
124- ):
144+ ):
125145 returns = []
126146
127147 if auth_token :
128148 r = self .http .request ('GET' ,
129149 request ,
130150 headers = {'Authorization' : str (auth_token ),
131151 'user-agent' : str (user_agent ),
132- # 'accept-encoding': 'gzip'
133- }
152+ 'accept-encoding' : 'gzip'
153+ }
134154 )
135155 else :
136- r = self .http .request ('GET' , request , headers = {'user-agent' : str (user_agent )})
156+ r = self .http .request ('GET' , request , headers = {
157+ 'user-agent' : str (user_agent ),
158+ 'accept-encoding' : 'gzip' })
137159
138160 data = r .data .decode ('utf-8' )
139161
@@ -156,7 +178,8 @@ def send_request(self,
156178 returns .append (headers )
157179
158180 if auth_token :
159- returns .append ({"Token-Valid" : bool (int (re .split (r"Token-Valid" , headers )[1 ][4 ]))})
181+ returns .append (
182+ {"Token-Valid" : bool (int (re .split (r"Token-Valid" , headers )[1 ][4 ]))})
160183
161184 if len (returns ) > 1 :
162185 return returns
@@ -180,5 +203,58 @@ def get_joke(
180203 category , blacklist , response_format , type , search_string , id_range , amount , lang
181204 )
182205
183- response = self .send_request (r , response_format , return_headers , auth_token , user_agent )
206+ response = self .send_request (
207+ r , response_format , return_headers , auth_token , user_agent )
184208 return response
209+
210+ def submit_joke (self , category , joke , flags , lang = "en" ):
211+ request = {"formatVersion" : 3 }
212+
213+ if category not in self .info ["categories" ]:
214+ raise CategoryError (
215+ f'''Invalid category selected.
216+ You selected { category } .
217+ Available categories are:
218+ { """
219+ """ .join (self .info ["categories" ])} ''' )
220+ request ["category" ] = category
221+
222+ if type (joke ) in [list , tuple ]:
223+ if len (joke ) > 1 :
224+ request ["type" ] = "twopart"
225+ request ["setup" ] = joke [0 ]
226+ request ["delivery" ] = joke [1 ]
227+ else :
228+ request ["type" ] = "single"
229+ request ["joke" ] = joke [0 ]
230+ else :
231+ request ["type" ] = "single"
232+ request ["joke" ] = joke
233+
234+ for key in flags .keys ():
235+ if key not in self .info ["flags" ]:
236+ raise BlacklistError (
237+ f'''
238+ You have blacklisted flags which are not available.
239+ Available flags are:
240+ { """
241+ """ .join (self .info ["flags" ])}
242+ ''' )
243+ request ["flags" ] = flags
244+ request ["lang" ] = lang
245+
246+ data = str (request ).replace ("'" , '"' )
247+ data = data .replace (": True" , ": true" ).replace (": False" , ": false" )
248+ data = data .encode ('ascii' )
249+ url = "https://sv443.net/jokeapi/v2/submit"
250+
251+ try :
252+ response = urllib .request .urlopen (url , data = data )
253+ data = response .getcode ()
254+
255+ return data
256+ except urllib .error .HTTPError as e :
257+ body = e .read ().decode () # Read the body of the error response
258+
259+ _json = json .loads (body )
260+ return _json
0 commit comments