1
1
import urllib3
2
2
import urllib
3
+ import urllib .request
3
4
import simplejson as json
4
5
import re
5
6
6
7
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
+
7
24
class Jokes :
8
25
def __init__ (self ):
9
26
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" )
11
29
self .info = data = json .loads (self .info .data .decode ('utf-8' ))["jokes" ]
12
30
13
31
def build_request (
@@ -26,7 +44,7 @@ def build_request(
26
44
if len (category ):
27
45
for c in category :
28
46
if not c .title () in self .info ["categories" ]:
29
- raise ValueError (
47
+ raise CategoryError (
30
48
f'''Invalid category selected.
31
49
You selected { c } .
32
50
Available categories are:
@@ -39,31 +57,34 @@ def build_request(
39
57
else :
40
58
cats = "Any"
41
59
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'''
47
66
48
67
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
57
78
else :
58
- blacklistFlags = None
79
+ raise BlacklistError ( f'''blacklist must be a list or tuple.''' )
59
80
60
81
if response_format not in ["json" , "xml" , "yaml" , "txt" ]:
61
- raise Exception (
82
+ raise ResponseTypeError (
62
83
"Response format must be either json, xml, txt or yaml."
63
84
)
64
85
if type :
65
86
if type not in ["single" , "twopart" ]:
66
- raise ValueError (
87
+ raise JokeTypeError (
67
88
'''Invalid joke type.
68
89
Available options are "single" or "twopart".'''
69
90
)
@@ -98,7 +119,6 @@ def build_request(
98
119
if blacklistFlags :
99
120
r += f"&blacklistFlags={ blacklistFlags } "
100
121
101
-
102
122
r += f"&type={ type } "
103
123
104
124
if search_string :
@@ -107,7 +127,7 @@ def build_request(
107
127
r += f"i&dRange={ id_range [0 ]} -{ id_range [1 ]} "
108
128
if amount > 10 :
109
129
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 } ."
111
131
)
112
132
r += f"&amount={ amount } "
113
133
@@ -121,19 +141,21 @@ def send_request(self,
121
141
return_headers ,
122
142
auth_token ,
123
143
user_agent
124
- ):
144
+ ):
125
145
returns = []
126
146
127
147
if auth_token :
128
148
r = self .http .request ('GET' ,
129
149
request ,
130
150
headers = {'Authorization' : str (auth_token ),
131
151
'user-agent' : str (user_agent ),
132
- # 'accept-encoding': 'gzip'
133
- }
152
+ 'accept-encoding' : 'gzip'
153
+ }
134
154
)
135
155
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' })
137
159
138
160
data = r .data .decode ('utf-8' )
139
161
@@ -156,7 +178,8 @@ def send_request(self,
156
178
returns .append (headers )
157
179
158
180
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 ]))})
160
183
161
184
if len (returns ) > 1 :
162
185
return returns
@@ -180,5 +203,58 @@ def get_joke(
180
203
category , blacklist , response_format , type , search_string , id_range , amount , lang
181
204
)
182
205
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 )
184
208
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