forked from noops-challenge/fizzbot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fizz2.py
74 lines (57 loc) · 2.02 KB
/
fizz2.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
# Interactive python 2 client for fizzbot
import json
import urllib2
domain = 'http://localhost:3004'
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 = urllib2.Request(domain + question_url, body, {'Content-Type': 'application/json'})
res = urllib2.urlopen(req)
response = json.load(res)
print_response(response)
print_sep()
return response
except urllib2.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 = raw_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'):
raw_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)
question_data = json.load(urllib2.urlopen( ('%s%s' % (domain, question_url)) ))
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()