-
Notifications
You must be signed in to change notification settings - Fork 224
Expand file tree
/
Copy pathconversation.py
More file actions
71 lines (53 loc) · 1.49 KB
/
conversation.py
File metadata and controls
71 lines (53 loc) · 1.49 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
import sys, json, time
ended = False
def is_json(myjson):
try:
json_object = json.loads(myjson)
except ValueError, e:
return False
return True
def makeError(reason):
ended = True
return {
'action': 'error',
'reason': reason
}
def handleKnockKnock(obj):
response = {
'action': 'knockknockjoke'
};
message = obj['message'];
if (message == 'Knock, knock.'):
response['message'] = "Who's there?"
return response;
if (message == 'Orange.'):
response['message'] = "Orange who?"
return response;
if (message == "Orange you glad I didn't say, 'banana'?"):
response['message'] = "Ha ha."
ended = True
return response;
return makeError('Unrecognised knock-knock phase.')
def handleAction(obj):
if 'action' not in obj:
return makeError("Unsupported input; expected 'action' key.")
action = obj['action']
if action == 'knockknockjoke':
return handleKnockKnock(obj)
return makeError("Unrecognised action: {0}".format(action))
def handleLine(line):
if not is_json(line):
return makeError('Malformed input could not be parsed as JSON: {0}'.format(line))
parsed = json.loads(line)
if type (parsed) != type({}):
return makeError('Malformed input: expected JSON object; received JSON primitive instead: {0}'.format(parsed))
return handleAction(parsed)
# simple JSON echo script
while not ended:
line = sys.stdin.readline()
if not line:
break
# for line in sys.stdin:
response = handleLine(line)
print json.dumps(response)
sys.stdout.flush()