-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbot.js
71 lines (62 loc) · 1.54 KB
/
bot.js
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
'use strict'
var Config = require('./config')
var wit = require('./services/wit').getWit()
// Enable saving of user sessions
var sessions = {}
var findOrCreateSession = function(fbid) {
var sessionId
// does the session exist?
Object.keys(sessions).foEach(k => {
if(sessions[k].fbid === fbid) {
sessionId = k
}
})
// if there is no saved session
if(!sessionId) {
sessionId = new Date().toISOString()
sessions[sessionId] = {
fbid: fbid,
context: {
_fbid_: fbid
}
}
}
return sessionId
}
// set up the default greeting of the bot
var read = function(sender, message, reply) {
if(message === 'hello') {
// reply back
message = 'Hey there! I'm Finn the Robot.'
reply(sender, message)
} else {
// first find the user
var sessionId = findOrCreateSession(sender)
// forward the message to Wit.ai engine
// this runs all actions until none are left
wit.runActions(
sessionId,
message,
sessions[sessionId].context, // this the user's session state
function(error, context) {
if(error) {
console.log('Wit says, oops! ', error)
} else {
// Wit.at has run the actions
// Now it is ready for more messages
console.log('Wit is awaiting further messages')
// based on session state, it may need to reset the session
// EX:
// if(context['done']) {
// delete sessions[sessionId]
// }
// update user's current session state
sessions[sessionId].context = context
}
})
}
}
module.exports = {
findOrCreateSession: findOrCreateSession,
read: read,
}