-
Notifications
You must be signed in to change notification settings - Fork 123
/
fizz3.py
76 lines (59 loc) · 2.12 KB
/
fizz3.py
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
# Interactive python client for fizzbot
import json
import urllib.request
import urllib.error
domain = 'https://api.noopschallenge.com'
def print_sep(): print('----------------------------------------------------------------------')
# print server response
def print_response(dict):
print('')
print('message:')
print(dict.get('message'))
print('')
for key in dict:
if key != 'message':
print('%s: %s' % (key, json.dumps(dict.get(key))))
print('')
# try an answer and see what fizzbot thinks of it
def try_answer(question_url, answer):
print_sep()
body = json.dumps({ 'answer': answer })
print('*** POST %s %s' % (question_url, body))
try:
req = urllib.request.Request(domain + question_url, data=body.encode('utf8'), headers={'Content-Type': 'application/json'})
res = urllib.request.urlopen(req)
response = json.load(res)
print_response(response)
print_sep()
return response
except urllib.error.HTTPError as e:
response = json.load(e)
print_response(response)
return response
# keep trying answers until a correct one is given
def get_correct_answer(question_url):
while True:
answer = input('Enter your answer:\n')
response = try_answer(question_url, answer)
if (response.get('result') == 'interview complete'):
print('congratulations!')
exit()
if (response.get('result') == 'correct'):
input('press enter to continue')
return response.get('nextQuestion')
# do the next question
def do_question(domain, question_url):
print_sep()
print('*** GET %s' % question_url)
request = urllib.request.urlopen( ('%s%s' % (domain, question_url)) )
question_data = json.load(request)
print_response(question_data)
print_sep()
next_question = question_data.get('nextQuestion')
if next_question: return next_question
return get_correct_answer(question_url)
def main():
question_url = '/fizzbot'
while question_url:
question_url = do_question(domain, question_url)
if __name__ == '__main__': main()