-
Notifications
You must be signed in to change notification settings - Fork 0
/
interpreter.coffee
334 lines (277 loc) · 10.7 KB
/
interpreter.coffee
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
Kefir = require 'kefir'
async = require 'async'
moment = require 'moment-timezone'
moment.tz('America/Los_Angeles')
util = require 'util'
commands = require './commands'
somata = require 'somata'
nalgene = require '../nalgene-js/src'
{asSentence} = require '../nalgene-js/src/helpers'
fs = require 'fs'
grammar = nalgene.parse fs.readFileSync './grammar.nlg', 'utf8'
request = require 'request'
{randomString, formatPrice, inspect, flatten, trimObj} = require './helpers'
CHECK_COMPARISONS_EVERY = 1000 * 60
CHECK_TIMERS_EVERY = 1000
# Helpers
# ------------------------------------------------------------------------------
findChild = (key, children) ->
for child in children
if child.key == key
return child.children
objectToChildren = (obj) ->
children = []
for key, value of trimObj obj
if typeof value == 'string'
value = value.replace(/_/g, ' ')
children.push {key: '$' + key, children: value}
return children
asValueArray = (o) ->
vs = []
for k, v of trimObj o
vs.push '$' + k
vs.push v
return vs
parseNumber = (n) ->
Number n.replace(/\s+/g, '')
Array.remove = (list, item) ->
index = list.indexOf item
list.splice(index, 1)
# Message sending
# ------------------------------------------------------------------------------
generateResponse = (response) ->
console.log 'response', response
# TODO
# response.mapLeaves (leaf) ->
# if typeof leaf == 'number'
# console.log 'number', leaf
# return formatPrice leaf
# else
# return leaf
if response.key == '%sequence'
for child in response.children
if child.key == '%action'
if child.children[0].key == '%getPrice'
getPrice = child.children[0]
console.log 'getPrice', getPrice
for gc in getPrice.children
if typeof gc.children == 'number'
console.log 'number', gc.children
gc.children = formatPrice gc.children
context = {key: "%parsed", children: [response]}
body = nalgene.generate grammar, '%response', context
body = asSentence body
console.log '[generateResponse]', body
return body
sendResponse = (context, err, data) ->
console.log '[sendResponse]', err or data
context.error = err
context.data = data
if context.message?.callback_url?
sendPostResponse context
else if context.message?.session_id?
sendChatResponse context
else if context.cb?
context.cb err, context
sendPostResponse = (context) ->
console.log '[sendPostResponse]', context
{error, data, parsed, message} = context
body = error or generateResponse data
post_body = {
error, data, parsed, body,
type: if error then 'error' else 'message'
receiver: message.sender?.username
}
console.log 'post_body', post_body
request.post {uri: message.callback_url, json: post_body}
sendChatResponse = (context) ->
console.log '[sendChatResponse]', context
{error, data, parsed, message} = context
body = error or generateResponse data
response = {
error, data, parsed, body
_id: randomString()
type: if error then 'error' else 'message'
sender: 'maia'
}
console.log '[response]', response
client.remote 'maia:chat', 'sendResponse', message.session_id, response, ->
# Timer %timer commands
# ------------------------------------------------------------------------------
now = -> new Date().getTime()
checkTimer = (timer) ->
if now() >= timer.time
{sequence, context} = timer
console.log '[checkTimer] Timer done at', moment().toISOString()
Array.remove(timers, timer)
runSequence context, sequence, sendResponse.bind(null, context)
timers = []
checkTimers = -> timers.map checkTimer
setInterval checkTimers, CHECK_TIMERS_EVERY
# Comparisons for %if commands
# ------------------------------------------------------------------------------
operatorFn = (operator) ->
if operator == 'greater_than'
return (a, b) -> a > b
else if operator == 'less_than'
return (a, b) -> a < b
else
return (a, b) -> a == Math.floor b
checkComparison = (comparison) ->
{action, operator, number, sequence, context, callback_url} = comparison
runCommand context, action, (err, response) ->
value = findChild('$value', response)
if operatorFn(operator)(value, number)
console.log '[checkComparison]', comparison, 'is true'
runSequence context, sequence, sendResponse.bind(null, callback_url)
Array.remove(comparisons, comparison)
comparisons = []
checkComparisons = -> comparisons.map checkComparison
setInterval checkComparisons, CHECK_COMPARISONS_EVERY
# ------------------------------------------------------------------------------
runIf = (context, args, cb) ->
condition = findChild('%condition', args)
sequence = findChild('%sequence', args)
if getValue = findChild('%getValue', condition)
operator = findChild('%operator', condition)[0]?.key?.slice(1)
number = findChild('$number', condition)[0]
number = parseNumber number
inspect 'getValue', getValue
inspect 'operator', operator
inspect 'number', number
action = getValue[0]
comparisons.push {action, operator, number, sequence}
else if checkValue = findChild('%checkValue', condition)
inspect 'checkValue', checkValue
cb null, {key: '%if', children: []}
runTimer = (context, args, cb) ->
absolute_time = findChild('%absolute_time', args)
relative_time = findChild('%relative_time', args)
sequence = findChild('%sequence', args)
if absolute_time?
time_str = findChild('$time', absolute_time).join(' ')
for matcher in ['H a', 'H : mm a', 'H : mm']
if moment(time_str, matcher, true).isValid()
time = moment(time_str, matcher, true)
break
if !time?
return cb "Could not parse time #{time_str}"
if time.isBefore(moment())
console.log '(absolute time) adjust +1 day'
time.add(1, 'day')
inspect 'absolute time', {time}
timeout = time.diff(moment())
else if relative_time?
number = findChild('$number', relative_time)
number = parseNumber number.join('')
time_unit = findChild('%time_unit', relative_time)
time_unit = time_unit[0].key.slice(1)
inspect 'relative time', {number, time_unit}
if time_unit == 'seconds'
timeout = number * 1000
else if time_unit == 'minutes'
timeout = number * 1000 * 60
else if time_unit == 'hours'
timeout = number * 1000 * 60 * 60
console.log '[runTimer] Starting timer', timeout, 'at', moment().toISOString(), '...\n'
time = now() + timeout
timers.push {time, sequence, context}
from_now = moment(time).fromNow()
cb null, {key: '%timer', children: objectToChildren {from_now}}
argsFromChildren = (children) ->
inspect 'argsFromChildren', children
args = {}
for child in children
child_key = child.key.slice(1)
child_value = child.children[0]
if child_value?.key?[0] == '@'
child_value = child_value.key.slice(1)
args[child_key] = child_value
else if child_value?.key?[0] == '$'
child_value = argsFromChildren child.children
args[child_key] = child_value
inspect 'argsFromChildren args =', args
return args
runCommand = (context, {key, children}, cb) ->
if command = commands[key.slice(1)]
args = argsFromChildren children
command args, (err, response) ->
return cb err if err?
cb null, objectToChildren response
else
cb "Unknown command: #{key}"
runAction = (context, {key, children}, cb) ->
console.log '[runAction]', key, children
action = children[0]
runCommand context, action, (err, response) ->
if err?
cb err
else
key = action.key
inspect 'runAction response', response
cb null, {key: '%action', children: [{key, children: response}]}
runSequence = (context, args, cb) ->
inspect 'runSequence args', args
async.mapSeries args, runAction.bind(null, context), (err, responses) ->
if err
cb err
else
inspect 'runSequence responses', responses
cb null, {key: '%sequence', children: responses}
runners =
'%timer': runTimer
'%if': runIf
'%sequence': runSequence
passthrough =
'%greeting': true
'%thanks': true
runPhrase = (context, {key, children}, cb) ->
inspect 'runPhrase', {key, children, context}
if run = runners[key]
run context, children, cb
else if passthrough[key]
cb null, {key, children}
else if command = commands[key.slice(1)]
args = argsFromChildren children
command args, (err, response) ->
return cb err if err?
cb null, {
key: '%sequence'
children: [
{
key: '%action'
children: [
{
key: key
children: objectToChildren response
}
]
}
]
}
else
cb "No handler for #{key}"
# Running service
# ------------------------------------------------------------------------------
client = new somata.Client
command = (message, cb) ->
context = {}
Object.assign context, {message}
console.log '[command]', message
context.cb = cb
client.remote 'maia:parser', 'parse', message.body, (err, response) ->
if err or err = response.error
console.log "ERROR", err
return sendResponse context, err
inputs = response.parsed.children[0]
context.parsed = response.parsed
runPhrase context, inputs, sendResponse.bind(null, context)
# Test
# c = 'in 7 seconds please turn on the kitchen light and turn off the living room light'
# c = 'when the price of bitcoin is above 100 please turn on the kitchen light'
# c = 'please turn on the kitchen light and turn off the living room light'
# c = 'when the price of bitcoin is above 2650 turn the office light green'
# c = 'what is the price of bitcoin?'
# callback_url = 'http://webhooks.nexus.dev/events/bot/kihu1tze'
# command {body: c, callback_url, sender: {username: 'jones'}}, (err, got) -> console.log err or got
new somata.Service 'maia:command', {command}