forked from nortti/tea_cah
58 lines
1.8 KiB
Python
58 lines
1.8 KiB
Python
|
import json
|
||
|
import random
|
||
|
import urllib.request
|
||
|
|
||
|
base_url = 'https://api.cardcastgame.com/v1/decks/'
|
||
|
|
||
|
class CodeValidationError(Exception): pass
|
||
|
|
||
|
def check_code(code):
|
||
|
def accepted_character(char):
|
||
|
# Upper case letters and numbers are allowed
|
||
|
return ord('A') <= ord(char) <= ord('Z') or ord('0') <= ord(char) <= ord('9')
|
||
|
|
||
|
if len(code) != 5:
|
||
|
raise CodeValidationError('Code %s not 5 characters long' % code)
|
||
|
elif any(not accepted_character(char) for char in code):
|
||
|
raise CodeValidationError('Code %s contains disallowed characters (0-9 and A-Z are allowed' % code)
|
||
|
|
||
|
def request(additional, timeout):
|
||
|
url = base_url + additional
|
||
|
with urllib.request.urlopen(url, timeout = timeout) as r:
|
||
|
return json.loads(r.read())
|
||
|
|
||
|
def info(code, *, timeout = 10):
|
||
|
check_code(code)
|
||
|
return request(code, timeout)
|
||
|
|
||
|
def cards(code, *, timeout = 10):
|
||
|
check_code(code)
|
||
|
|
||
|
data = request(code + '/cards', timeout)
|
||
|
|
||
|
calls = [i['text'] for i in data['calls']]
|
||
|
responses = [i['text'] for i in data['responses']]
|
||
|
|
||
|
# Both calls and responses are stored as a list of parts
|
||
|
# For calls, the blanks go between the parts so that ['foo', 'bar'] is
|
||
|
# "foo _ bar", but for resposes there is never more than one part
|
||
|
# Therefore, remove the additional layer of list
|
||
|
responses = [i for (i,) in responses]
|
||
|
|
||
|
return (calls, responses)
|
||
|
|
||
|
def random_code(*, timeout = 10, count = None):
|
||
|
|
||
|
if count is None:
|
||
|
# Get number of cards
|
||
|
results = request('?category=&direction=desc&limit=1&sort=rating&offset=0', timeout)
|
||
|
count = results['results']['count']
|
||
|
|
||
|
# Generate a random number [0, count[
|
||
|
offset = random.randint(0, count - 1)
|
||
|
|
||
|
# Get the data on the selected deck
|
||
|
results = request('?category=&direction=desc&limit=1&sort=rating&offset=%i' % offset, timeout)
|
||
|
|
||
|
return (results['results']['data'][0]['code'], count)
|