forked from qbreader/python-module
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathasynchronous.py
More file actions
719 lines (603 loc) · 25.7 KB
/
asynchronous.py
File metadata and controls
719 lines (603 loc) · 25.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
"""Directly access the qbreader API asynchronously."""
from __future__ import annotations
from typing import Optional, Self, Type
import aiohttp
import qbreader._api_utils as api_utils
from qbreader._consts import BASE_URL
from qbreader.types import (
AnswerJudgement,
Bonus,
Packet,
QueryResponse,
QuestionType,
SearchType,
Tossup,
UnnormalizedAlternateSubcategory,
UnnormalizedCategory,
UnnormalizedDifficulty,
UnnormalizedSubcategory,
Year,
)
class Async:
"""The asynchronous qbreader API wrapper."""
session: aiohttp.ClientSession
@classmethod
async def create(
cls: Type[Self], session: Optional[aiohttp.ClientSession] = None
) -> Self:
"""Create a new Async instance. `__init__()` is not async, so this is necessary.
Parameters
----------
session : aiohttp.ClientSession, optional
The aiohttp session to use for requests. If none is provided, a new session
will be created.
Returns
-------
Async
The new Async instance.
"""
self = cls()
self.session = session or aiohttp.ClientSession()
return self
async def close(self: Self) -> None:
"""Close the aiohttp session."""
await self.session.close()
async def __aenter__(self: Self) -> Self:
"""Enter an async context."""
return self
async def __aexit__(self: Self, exc_type, exc_val, exc_tb) -> None:
"""Exit an async context."""
await self.close()
async def query(
self: Self,
questionType: QuestionType = "all",
searchType: SearchType = "all",
queryString: Optional[str] = "",
exactPhrase: Optional[bool] = False,
ignoreDiacritics: Optional[bool] = False,
ignoreWordOrder: Optional[bool] = False,
regex: Optional[bool] = False,
randomize: Optional[bool] = False,
setName: Optional[str] = None,
difficulties: UnnormalizedDifficulty = None,
categories: UnnormalizedCategory = None,
subcategories: UnnormalizedSubcategory = None,
alternate_subcategories: UnnormalizedAlternateSubcategory = None,
maxReturnLength: Optional[int] = 25,
tossupPagination: Optional[int] = 1,
bonusPagination: Optional[int] = 1,
min_year: int = Year.MIN_YEAR,
max_year: int = Year.CURRENT_YEAR,
) -> QueryResponse:
"""Query the qbreader database for questions.
Original API doc at https://www.qbreader.org/api-docs/query.
Parameters
----------
questionType : qbreader.types.QuestionType
The type of question to search for. Can be either a string or a question
class type.
searchType : qbreader.types.SearchType
Where to search for the query string. Can only be a string.
queryString : str, optional
The string to search for.
exactPhrase : bool, default = False
Ensure that the query string is an exact phrase.
ignoreDiacritics : bool, default = False
Ignore or transliterate diacritical marks in `queryString`.
ignoreWordOrder : bool, default = False
Treat `queryString` as a set of keywords that can appear in any order.
regex : bool, default = False
Treat `queryString` as a regular expression.
randomize : bool, default = False
Randomize the order of the returned questions.
setName : str, optional
The name of the set to search in.
difficulties : qbreader.types.UnnormalizedDifficulty, optional
The difficulties to search for. Can be a single or an array of `Difficulty`
enums, strings, or integers.
categories : qbreader.types.UnnormalizedCategory, optional
The categories to search for. Can be a single or an array of `Category`
enums or strings.
subcategories : qbreader.types.UnnormalizedSubcategory, optional
The subcategories to search for. Can be a single or an array of
`Subcategory` enums or strings. The API does not check for consistency
between categories and subcategories.
alternate_subcategories : qbreader.types.UnnormalizedAlternateSubcategory,\
optional
The alternate subcategories to search for. Can be a single or an array of
`AlternateSubcategory` enums or strings. The API does not check for
consistency between categories and subcategories
maxReturnLength : int, default = 25
The maximum number of questions to return.
tossupPagination : int, default = 1
The page of tossups to return.
bonusPagination : int, default = 1
The page of bonuses to return.
min_year : int, default = Year.MIN_YEAR
The earliest year to search.
max_year : int, default = Year.CURRENT_YEAR
The latest year to search.
Returns
-------
QueryResponse
A `QueryResponse` object containing the results of the query.
"""
# normalize and type check parameters
if questionType == Tossup:
questionType = "tossup"
elif questionType == Bonus:
questionType = "bonus"
if questionType not in ["tossup", "bonus", "all"]:
raise ValueError("questionType must be either 'tossup', 'bonus', or 'all'.")
if searchType not in ["question", "answer", "all"]:
raise ValueError(
"searchType must be either 'question', 'answer', or 'all'."
)
if not isinstance(queryString, str):
raise TypeError(
f"queryString must be a string, not {type(queryString).__name__}."
)
for name, param in tuple(
zip(
(
"exactPhrase",
"ignoreDiacritics",
"ignoreWordOrder",
"regex",
"randomize",
),
(exactPhrase, ignoreDiacritics, ignoreWordOrder, regex, randomize),
)
):
if not isinstance(param, bool):
raise TypeError(
f"{name} must be a boolean, not {type(param).__name__}."
)
if setName is not None and not isinstance(setName, str):
raise TypeError(f"setName must be a string, not {type(setName).__name__}.")
for name, param in tuple( # type: ignore
zip(
("maxReturnLength", "tossupPagination", "bonusPagination"),
(maxReturnLength, tossupPagination, bonusPagination),
)
):
if not isinstance(param, int):
raise TypeError(
f"{name} must be an integer, not {type(param).__name__}."
)
elif param < 1:
raise ValueError(f"{name} must be at least 1.")
for name, year in {
"minYear": min_year,
"maxYear": max_year,
}.items():
if not isinstance(year, int):
raise TypeError(
f"{name} must be an integer, not {type(param).__name__}."
)
url = BASE_URL + "/query"
(
normalized_categories,
normalized_subcategories,
normalized_alternate_subcategories,
) = api_utils.normalize_cats(categories, subcategories, alternate_subcategories)
data = {
"questionType": questionType,
"searchType": searchType,
"queryString": queryString,
"exactPhrase": api_utils.normalize_bool(exactPhrase),
"ignoreDiacritics": api_utils.normalize_bool(ignoreDiacritics),
"ignoreWordOrder": api_utils.normalize_bool(ignoreWordOrder),
"regex": api_utils.normalize_bool(regex),
"randomize": api_utils.normalize_bool(randomize),
"setName": setName,
"difficulties": api_utils.normalize_diff(difficulties),
"categories": normalized_categories,
"subcategories": normalized_subcategories,
"alternateSubcategories": normalized_alternate_subcategories,
"maxReturnLength": maxReturnLength,
"tossupPagination": tossupPagination,
"bonusPagination": bonusPagination,
"minYear": min_year,
"maxYear": max_year,
}
data = api_utils.prune_none(data)
async with self.session.get(url, params=data) as response:
if response.status != 200:
raise Exception(str(response.status) + " bad request")
json = await response.json()
return QueryResponse.from_json(json)
async def random_tossup(
self: Self,
difficulties: UnnormalizedDifficulty = None,
categories: UnnormalizedCategory = None,
subcategories: UnnormalizedSubcategory = None,
alternate_subcategories: UnnormalizedAlternateSubcategory = None,
number: int = 1,
min_year: int = Year.MIN_YEAR,
max_year: int = Year.CURRENT_YEAR,
) -> tuple[Tossup, ...]:
"""Get random tossups from the database.
Original API doc at https://www.qbreader.org/api-docs/random-tossup.
Parameters
----------
difficulties : qbreader.types.UnnormalizedDifficulty, optional
The difficulties to search for. Can be a single or an array of `Difficulty`
enums, strings, or integers.
categories : qbreader.types.UnnormalizedCategory, optional
The categories to search for. Can be a single or an array of `Category`
enums or strings.
subcategories : qbreader.types.UnnormalizedSubcategory, optional
The subcategories to search for. Can be a single or an array of
`Subcategory` enums or strings. The API does not check for consistency
between categories and subcategories.
alternate_subcategories : qbreader.types.UnnormalizedAlternateSubcategory,\
optional
The alternate subcategories to search for. Can be a single or an array of
`AlternateSubcategory` enums or strings. The API does not check for
consistency between categories and subcategories
number : int, default = 1
The number of tossups to return.
min_year : int, default = Year.MIN_YEAR
The oldest year to search for.
max_year : int, default = Year.CURRENT_YEAR
The most recent year to search for.
Returns
-------
tuple[Tossup, ...]
A tuple of `Tossup` objects.
"""
# normalize and type check parameters
for name, param in tuple(
zip(
("number", "min_year", "max_year"),
(number, min_year, max_year),
)
):
if not isinstance(param, int):
raise TypeError(
f"{name} must be an integer, not {type(param).__name__}."
)
elif param < 1:
raise ValueError(f"{name} must be at least 1.")
url = BASE_URL + "/random-tossup"
(
normalized_categories,
normalized_subcategories,
normalized_alternate_subcategories,
) = api_utils.normalize_cats(categories, subcategories, alternate_subcategories)
data = {
"difficulties": api_utils.normalize_diff(difficulties),
"categories": normalized_categories,
"subcategories": normalized_subcategories,
"alternateSubcategories": normalized_alternate_subcategories,
"number": number,
"minYear": min_year,
"maxYear": max_year,
}
data = api_utils.prune_none(data)
async with self.session.get(url, params=data) as response:
if response.status != 200:
raise Exception(str(response.status) + " bad request")
json = await response.json()
return tuple(Tossup.from_json(tu) for tu in json["tossups"])
async def random_bonus(
self: Self,
difficulties: UnnormalizedDifficulty = None,
categories: UnnormalizedCategory = None,
subcategories: UnnormalizedSubcategory = None,
alternate_subcategories: UnnormalizedAlternateSubcategory = None,
number: int = 1,
min_year: int = Year.MIN_YEAR,
max_year: int = Year.CURRENT_YEAR,
three_part_bonuses: bool = False,
) -> tuple[Bonus, ...]:
"""Get random bonuses from the database.
Original API doc at https://www.qbreader.org/api-docs/random-bonus.
Parameters
----------
difficulties : qbreader.types.UnnormalizedDifficulty, optional
The difficulties to search for. Can be a single or an array of `Difficulty`
enums, strings, or integers.
categories : qbreader.types.UnnormalizedCategory, optional
The categories to search for. Can be a single or an array of `Category`
enums or strings.
subcategories : qbreader.types.UnnormalizedSubcategory, optional
The subcategories to search for. Can be a single or an array of
`Subcategory` enums or strings. The API does not check for consistency
between categories and subcategories.
alternate_subcategories: qbreader.types.UnnormalizedAlternateSubcategory, \
optional
The alternates subcategories to search for. Can be a single or an array of
`AlternateSubcategory` enum variants or strings. The API does not check for
consistency between categories, subcategories, and alternate subcategories.
number : int, default = 1
The number of bonuses to return.
min_year : int, default = Year.MIN_YEAR
The oldest year to search for.
max_year : int, default = Year.CURRENT_YEAR
The most recent year to search for.
three_part_bonuses : bool, default = False
Whether to only return bonuses with 3 parts.
Returns
-------
tuple[Bonus, ...]
A tuple of `Bonus` objects.
"""
# normalize and type check parameters
for name, param in tuple(
zip(
("number", "min_year", "max_year"),
(number, min_year, max_year),
)
):
if not isinstance(param, int):
raise TypeError(
f"{name} must be an integer, not {type(param).__name__}."
)
elif param < 1:
raise ValueError(f"{name} must be at least 1.")
if not isinstance(three_part_bonuses, bool):
raise TypeError(
"three_part_bonuses must be a boolean, not "
+ f"{type(three_part_bonuses).__name__}."
)
url = BASE_URL + "/random-bonus"
(
normalized_categories,
normalized_subcategories,
normalized_alternate_subcategories,
) = api_utils.normalize_cats(categories, subcategories, alternate_subcategories)
data = {
"difficulties": api_utils.normalize_diff(difficulties),
"categories": normalized_categories,
"subcategories": normalized_subcategories,
"alternateSubcategories": normalized_alternate_subcategories,
"number": number,
"minYear": min_year,
"maxYear": max_year,
}
data = api_utils.prune_none(data)
async with self.session.get(url, params=data) as response:
if response.status != 200:
raise Exception(str(response.status) + " bad request")
json = await response.json()
return tuple(Bonus.from_json(b) for b in json["bonuses"])
async def random_name(self: Self) -> str:
"""Get a random adjective-noun pair that can be used as a name.
Original API doc at https://www.qbreader.org/api-docs/random-name.
Returns
-------
str
A string containing the random name.
"""
url = BASE_URL + "/random-name"
async with self.session.get(url) as response:
if response.status != 200:
raise Exception(str(response.status) + " bad request")
json = await response.json()
return json["randomName"]
async def packet(self: Self, setName: str, packetNumber: int) -> Packet:
"""Get a specific packet from a set.
Original API doc at https://www.qbreader.org/api-docs/packet.
Parameters
----------
setName : str
The name of the set. See `set_list()` for a list of valid set names.
packetNumber : int
The number of the packet in the set, starting from 1.
Returns
-------
Packet
A `Packet` object containing the packet's tossups and bonuses.
"""
# normalize and type check parameters
if not isinstance(setName, str):
raise TypeError(f"setName must be a string, not {type(setName).__name__}.")
if not isinstance(packetNumber, int):
raise TypeError(
f"packetNumber must be an integer, not {type(packetNumber).__name__}."
)
if packetNumber < 1 or packetNumber > await self.num_packets(setName):
raise ValueError(
f"packetNumber must be between 1 and {await self.num_packets(setName)} "
+ f"inclusive for {setName}."
)
url = BASE_URL + "/packet"
data: dict[str, str | int] = {"setName": setName, "packetNumber": packetNumber}
data = api_utils.prune_none(data)
async with self.session.get(url, params=data) as response:
if response.status != 200:
raise Exception(str(response.status) + " bad request")
json = await response.json()
return Packet.from_json(json=json, number=packetNumber)
async def packet_tossups(
self: Self, setName: str, packetNumber: int
) -> tuple[Tossup, ...]:
"""Get only tossups from a packet.
Original API doc at https://www.qbreader.org/api-docs/packet-tossups.
Parameters
----------
setName : str
The name of the set. See `set_list()` for a list of valid set names.
packetNumber : int
The number of the packet in the set, starting from 1.
Returns
-------
tuple[Tossup, ...]
A tuple of `Tossup` objects.
"""
# normalize and type check parameters
if not isinstance(setName, str):
raise TypeError(f"setName must be a string, not {type(setName).__name__}.")
if not isinstance(packetNumber, int):
raise TypeError(
f"packetNumber must be an integer, not {type(packetNumber).__name__}."
)
if packetNumber < 1 or packetNumber > await self.num_packets(setName):
raise ValueError(
f"packetNumber must be between 1 and {await self.num_packets(setName)} "
+ f"inclusive for {setName}."
)
url = BASE_URL + "/packet-tossups"
data: dict[str, str | int] = {"setName": setName, "packetNumber": packetNumber}
data = api_utils.prune_none(data)
async with self.session.get(url, params=data) as response:
if response.status != 200:
raise Exception(str(response.status) + " bad request")
json = await response.json()
return tuple(Tossup.from_json(tu) for tu in json["tossups"])
async def packet_bonuses(
self: Self, setName: str, packetNumber: int
) -> tuple[Bonus, ...]:
"""Get only bonuses from a packet.
Original API doc at https://www.qbreader.org/api-docs/packet-bonuses.
Parameters
----------
setName : str
The name of the set. See `set_list()` for a list of valid set names.
packetNumber : int
The number of the packet in the set, starting from 1.
Returns
-------
tuple[Bonus, ...]
A tuple of `Bonus` objects.
"""
# normalize and type check parameters
if not isinstance(setName, str):
raise TypeError(f"setName must be a string, not {type(setName).__name__}.")
if not isinstance(packetNumber, int):
raise TypeError(
f"packetNumber must be an integer, not {type(packetNumber).__name__}."
)
if packetNumber < 1 or packetNumber > await self.num_packets(setName):
raise ValueError(
f"packetNumber must be between 1 and {await self.num_packets(setName)} "
+ f"inclusive for {setName}."
)
url = BASE_URL + "/packet-bonuses"
data: dict[str, str | int] = {"setName": setName, "packetNumber": packetNumber}
data = api_utils.prune_none(data)
async with self.session.get(url, params=data) as response:
if response.status != 200:
raise Exception(str(response.status) + " bad request")
json = await response.json()
return tuple(Bonus.from_json(b) for b in json["bonuses"])
async def num_packets(self: Self, setName: str) -> int:
"""Get the number of packets in a set.
Original API doc at https://www.qbreader.org/api-docs/num-packets.
Parameters
----------
setName : str
The name of the set to search. Can be obtained from set_list().
Returns
-------
int
The number of packets in the set.
"""
url = BASE_URL + "/num-packets"
data = {
"setName": setName,
}
async with self.session.get(url, params=data) as response:
if response.status != 200:
if response.status == 404:
raise ValueError(f"Requested set, {setName}, not found.")
raise Exception(str(response.status) + " bad request")
json = await response.json()
return json["numPackets"]
async def set_list(self: Self) -> tuple[str, ...]:
"""Get a list of all the sets in the database.
Original API doc at https://www.qbreader.org/api-docs/set-list.
Returns
-------
tuple[str, ...]
A tuple containing the names of all the sets in the database, sorted in
reverse alphanumeric order.
"""
url = BASE_URL + "/set-list"
async with self.session.get(url) as response:
if response.status != 200:
raise Exception(str(response.status) + " bad request")
json = await response.json()
return json["setList"]
async def room_list(self: Self) -> tuple[dict, ...]:
"""Get a list of public rooms.
Original API doc at https://www.qbreader.org/api-docs/multiplayer/room-list.
Returns
-------
tuple[dict, ...]
A tuple containing the room data for all the public rooms.
"""
url = BASE_URL + "/multiplayer/room-list"
async with self.session.get(url) as response:
if response.status != 200:
raise Exception(str(response.status) + " bad request")
json = await response.json()
return json["roomList"]
async def check_answer(
self: Self, answerline: str, givenAnswer: str
) -> AnswerJudgement:
"""Judge an answer to be correct, incorrect, or prompt (can be directed).
Original API doc at https://www.qbreader.org/api-docs/check-answer.
Parameters
----------
answerline : str
The answerline to check against. Preferably including the HTML tags <b> and
<u>, if they are present.
givenAnswer : str
The answer to check.
Returns
-------
AnswerJudgement
A `AnswerJudgement` object containing the response.
"""
return await AnswerJudgement.check_answer_async(
answerline, givenAnswer, self.session
)
async def tossup_by_id(self: Self, id: str) -> Tossup:
"""Get a tossup by its ID.
Original API doc at https://www.qbreader.org/api-docs/tossup-by-id.
Parameters
----------
id : str
The ID of the tossup to get.
Returns
-------
Tossup
A `Tossup` object.
"""
url = BASE_URL + "/tossup-by-id"
data = {
"id": id,
}
async with self.session.get(url, params=data) as response:
if response.status != 200:
if response.status == 400:
raise ValueError(f"Invalid tossup ID: {id}")
raise Exception(str(response.status) + " bad request")
json = await response.json()
return Tossup.from_json(json["tossup"])
async def bonus_by_id(self: Self, id: str) -> Bonus:
"""Get a bonus by its ID.
Original API doc at https://www.qbreader.org/api-docs/bonus-by-id.
Parameters
----------
id : str
The ID of the bonus to get.
Returns
-------
Bonus
A `Bonus` object.
"""
url = BASE_URL + "/bonus-by-id"
data = {
"id": id,
}
async with self.session.get(url, params=data) as response:
if response.status != 200:
if response.status == 400:
raise ValueError(f"Invalid bonus ID: {id}")
raise Exception(str(response.status) + " bad request")
json = await response.json()
return Bonus.from_json(json["bonus"])