-
Notifications
You must be signed in to change notification settings - Fork 72
/
bot.js
74 lines (62 loc) · 1.7 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
72
73
74
'use strict'
var Config = require('./config')
var wit = require('./services/wit').getWit()
// LETS SAVE USER SESSIONS
var sessions = {}
var findOrCreateSession = function (fbid) {
var sessionId
// DOES USER SESSION ALREADY EXIST?
Object.keys(sessions).forEach(k => {
if (sessions[k].fbid === fbid) {
// YUP
sessionId = k
}
})
// No session so we will create one
if (!sessionId) {
sessionId = new Date().toISOString()
sessions[sessionId] = {
fbid: fbid,
context: {
_fbid_: fbid
}
}
}
return sessionId
}
var read = function (sender, message, reply) {
if (message === 'hello') {
// Let's reply back hello
message = 'Hello yourself! I am a chat bot. You can say "show me pics of corgis"'
reply(sender, message)
} else {
// Let's find the user
var sessionId = findOrCreateSession(sender)
// Let's forward the message to the Wit.ai bot engine
// This will run all actions until there are no more actions left to do
wit.runActions(
sessionId, // the user's current session by id
message, // the user's message
sessions[sessionId].context, // the user's session state
function (error, context) { // callback
if (error) {
console.log('oops!', error)
} else {
// Wit.ai ran all the actions
// Now it needs more messages
console.log('Waiting for further messages')
// Based on the session state, you might want to reset the session
// Example:
// if (context['done']) {
// delete sessions[sessionId]
// }
// Updating the user's current session state
sessions[sessionId].context = context
}
})
}
}
module.exports = {
findOrCreateSession: findOrCreateSession,
read: read,
}