-
Notifications
You must be signed in to change notification settings - Fork 258
/
bot.js
93 lines (80 loc) · 2.31 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
'use strict';
// Weather Example
// See https://wit.ai/sungkim/weather/stories and https://wit.ai/docs/quickstart
const Wit = require('node-wit').Wit;
const FB = require('./facebook.js');
const Config = require('./const.js');
const firstEntityValue = (entities, entity) => {
const val = entities && entities[entity] &&
Array.isArray(entities[entity]) &&
entities[entity].length > 0 &&
entities[entity][0].value;
if (!val) {
return null;
}
return typeof val === 'object' ? val.value : val;
};
// Bot actions
const actions = {
say(sessionId, context, message, cb) {
console.log(message);
// Bot testing mode, run cb() and return
if (require.main === module) {
cb();
return;
}
// Our bot has something to say!
// Let's retrieve the Facebook user whose session belongs to from context
// TODO: need to get Facebook user name
const recipientId = context._fbid_;
if (recipientId) {
// Yay, we found our recipient!
// Let's forward our bot response to her.
FB.fbMessage(recipientId, message, (err, data) => {
if (err) {
console.log(
'Oops! An error occurred while forwarding the response to',
recipientId,
':',
err
);
}
// Let's give the wheel back to our bot
cb();
});
} else {
console.log('Oops! Couldn\'t find user in context:', context);
// Giving the wheel back to our bot
cb();
}
},
merge(sessionId, context, entities, message, cb) {
// Retrieve the location entity and store it into a context field
const loc = firstEntityValue(entities, 'location');
if (loc) {
context.loc = loc; // store it in context
}
cb(context);
},
error(sessionId, context, error) {
console.log(error.message);
},
// fetch-weather bot executes
['fetch-weather'](sessionId, context, cb) {
// Here should go the api call, e.g.:
// context.forecast = apiCall(context.loc)
context.forecast = 'sunny';
cb(context);
},
};
const getWit = () => {
return new Wit(Config.WIT_TOKEN, actions);
};
exports.getWit = getWit;
// bot testing mode
// http://stackoverflow.com/questions/6398196
if (require.main === module) {
console.log("Bot testing mode.");
const client = getWit();
client.interactive();
}