-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
523 lines (388 loc) · 13.7 KB
/
index.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
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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
'use strict';
var express = require('express');
var bodyParser = require('body-parser');
var request = require('request');
var app = express();
var apiai = require('apiai');
const pg = require('pg');
const PORT = process.env.PORT;
var googleai = apiai(process.env.APIAI_TOKEN);
// Optional. You will see this name in eg. 'ps' or 'top' command
process.title = 'luzbot';
// websocket and http servers
var webSocketServer = require('websocket').server;
var http = require('http');
/**
* Global variables
*/
// latest 100 messages
var history = [ ];
// list of currently connected clients (users)
var clients = [ ];
let Wit = null;
let log = null;
try {
// if running from repo
Wit = require('../').Wit;
log = require('../').log;
} catch (e) {
Wit = require('node-wit').Wit;
log = require('node-wit').log;
}
// Variables are defined in Heroku
const WIT_TOKEN = process.env.WIT_TOKEN;
const FB_PAGE_ACCESS_TOKEN = process.env.PAGE_ACCESS_TOKEN;
const MY_BOT_ID = process.env.LUZBOT_ID || 123;
//Needs feature Dyno Metadata (https://stackoverflow.com/questions/7917523/how-do-i-access-the-current-heroku-release-version-programmatically)
const VERSION = process.env.HEROKU_RELEASE_VERSION;
//const { Client } = require('pg');
/**
* Helper function for escaping input strings
*/
function htmlEntities(str) {
return String(str).replace(/&/g, '&').replace(/</g, '<')
.replace(/>/g, '>').replace(/"/g, '"');
}
// Array with some colors
var colors = [ 'green', 'blue', 'magenta', 'purple', 'plum', 'orange' ];
// ... in random order
colors.sort(function(a,b) { return Math.random() > 0.5; } );
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
//app.listen(PORT);
app.use(express.static(__dirname + "/"))
//console.log('Listening on :' + PORT + '...');
/**
* HTTP server
*/
/*var server = http.createServer(function(request, response) {
// Not important for us. We're writing WebSocket server, not HTTP server
});
*/
//initialize a simple http server
var server = http.createServer(app);
server.listen(PORT, function() {
console.log((new Date()) + " Server is listening on port " + PORT);
});
/**
* WebSocket server
*/
var wsServer = new webSocketServer({
// WebSocket server is tied to a HTTP server. WebSocket request is just
// an enhanced HTTP request. For more info http://tools.ietf.org/html/rfc6455#page-6
httpServer: server
});
// Server frontpage
/*app.get('/', function (req, res) {
res.send('This is TestBot Server');
});*/
// Facebook Webhook
app.get('/webhook', function (req, res) {
if (req.query['hub.verify_token'] === 'luzbot_hans') {
res.send(req.query['hub.challenge']);
} else {
res.send('Invalid verify token');
}
});
// handler receiving messages
app.post('/webhook', function (req, res) {
var events = req.body.entry[0].messaging;
for (var i = 0; i < events.length; i++) {
var event = events[i];
if (event.message && event.message.text) {
// Yay! We got a new message!
// We retrieve the Facebook user ID of the sender
const sender = event.sender.id;
// We retrieve the user's current session, or create one if it doesn't exist
// This is needed for our bot to figure out the conversation history
const sessionId = findOrCreateSession(sender);
var question = event.message.text;
console.log('New message detected, json: ' + JSON.stringify(events));
console.log('New message detected, text: ' + question);
console.log('New message detected, sender: ' + sender);
sendBotAnswer(2, sender, question, 0, 2);
}
}
res.sendStatus(200);
});
// This callback function is called every time someone tries to connect to the WebSocket server
wsServer.on('request', function(request) {
console.log((new Date()) + ' Connection from origin ' + request.origin + '.');
// accept connection - you should check 'request.origin' to make sure that
// client is connecting from your website
// (http://en.wikipedia.org/wiki/Same_origin_policy)
var connection = request.accept(null, request.origin);
// we need to know client index to remove them on 'close' event
var index = clients.push(connection) - 1;
var userName = false;
var userColor = false;
console.log((new Date()) + ' Connection accepted.');
// user sent some message
connection.on('message', function(message) {
if (message.type === 'utf8') { // accept only text
if (userName === false) { // first message sent by user is their name
// remember user name
userName = htmlEntities(message.utf8Data);
// get random color and send it back to the user
userColor = colors.shift();
connection.sendUTF(JSON.stringify({ type:'color', data: userColor }));
console.log((new Date()) + ' User is known as: ' + userName
+ ' with ' + userColor + ' color.');
} else { // log and broadcast the message
console.log((new Date()) + ' Received Message from '
+ userName + ': ' + message.utf8Data);
//Eingegeben Nachricht ausgeben...
sendMessageNativeBot(message.utf8Data, userName, userColor, index);
//Sende Bot Anwort...
var question = message.utf8Data;
sendBotAnswer(1, userName, question, index, 2);
}
}
});
// user disconnected
connection.on('close', function(connection) {
if (userName !== false && userColor !== false) {
console.log((new Date()) + " Peer "
+ connection.remoteAddress + " disconnected.");
// remove user from the list of connected clients
clients.splice(index, 1);
// push back user's color to be reused by another user
colors.push(userColor);
}
});
});
// ----------------------------------------------------------------------------
// Messenger API specific code
// See the Send API reference
// https://developers.facebook.com/docs/messenger-platform/send-api-reference
const fbMessage = (id, text) => {
const body = JSON.stringify({
recipient: { id },
message: { text },
});
const qs = 'access_token=' + encodeURIComponent(FB_PAGE_ACCESS_TOKEN);
return fetch('https://graph.facebook.com/me/messages?' + qs, {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body,
})
.then(rsp => rsp.json())
.then(json => {
if (json.error && json.error.message) {
throw new Error(json.error.message);
}
return json;
});
};
// ----------------------------------------------------------------------------
// Wit.ai bot specific code
// This will contain all user sessions.
// Each session has an entry:
// sessionId -> {fbid: facebookUserId, context: sessionState}
const sessions = {};
const findOrCreateSession = (fbid) => {
let sessionId;
// Let's see if we already have a session for the user fbid
Object.keys(sessions).forEach(k => {
if (sessions[k].fbid === fbid) {
// Yep, got it!
sessionId = k;
}
});
if (!sessionId) {
// No session found for user fbid, let's create a new one
sessionId = new Date().toISOString();
sessions[sessionId] = {fbid: fbid, context: {}};
}
return sessionId;
};
// Our bot actions
const actions = {
send({sessionId}, {text}) {
console.log('Our bot has something to say!');
// Our bot has something to say!
// Let's retrieve the Facebook user whose session belongs to
const recipientId = sessions[sessionId].fbid;
console.log('Our bot has something to say!' + recipientId);
if (recipientId) {
console.log('// Yay, we found our recipient!');
// Yay, we found our recipient!
// Let's forward our bot response to her.
// We return a promise to let our bot know when we're done sending
return fbMessage(recipientId, text)
.then(() => null)
.catch((err) => {
console.error(
'Oops! An error occurred while forwarding the response to',
recipientId,
':',
err.stack || err
);
});
} else {
console.error('Oops! Couldn\'t find user for session:', sessionId);
// Giving the wheel back to our bot
return Promise.resolve()
}
},
};
// Setting up our bot
const wit = new Wit({
accessToken: WIT_TOKEN,
actions,
logger: new log.Logger(log.INFO)
});
//Process JSON for correct answer
function sendAnswer(botType, recipientId, nlpJson, question, index) {
//TODO: Implement connection pool
//TODO: parametrized query
if(question.toUpperCase() == "HI") {
var answer = "Hi. How are you?";
sendMessage(botType, recipientId, answer, index);
}
else if(question.toUpperCase() == "VERSION") {
var answer = "Aktuelle Version ist " + VERSION;
sendMessage(botType, recipientId, answer, index);
}
else if(nlpJson.hasOwnProperty('entities') && Object.keys(nlpJson.entities).length > 0){
console.log('property entities exists and has at least one entity');
var intent = nlpJson['entities']['intent']['0']['value'];
var pgClient = new pg.Client({
connectionString: process.env.DATABASE_URL,
ssl: true,
});
pgClient.connect();
/*
var sql = "SELECT resultname FROM results res LEFT OUTER JOIN category cat ON res.idcategory = cat.idcategory LEFT OUTER JOIN subcategory scat ON res.idsubcategory = scat.idsubcategory WHERE LOWER(category) = LOWER('" + intent + "')";
*/
var sql = "SELECT r.resultname AS resultname FROM resultalpha r WHERE LOWER(r.category) = LOWER($1)";
pgClient.query(sql,[intent], (err, res) => {
if (err) throw err;
var answer = "I suggest the following: ";
for (let row of res.rows) {
answer += row.resultname + "; ";
}
pgClient.end();
if(question.lastIndexOf('data', 0) === 0) {
//if question starts with data show the wit.ai json
var result = 'Category: ' + intent + ", json:" + JSON.stringify(nlpJson);
sendMessage(botType, recipientId, result, index);
}
else {
sendMessage(botType, recipientId, answer, index);
}
});
}
else {
var answer = "Ich verstehe deine Anfrage nicht. Sorry.";
sendMessage(botType, recipientId, answer, index);
}
}
function sendBotAnswer(botType, recipientId, question, index, aiengine) {
if(aiengine == 1) {
//forward question to wit framework --> Facebok
wit.message(question, {})
.then((data) =>
{
var body = JSON.stringify(data);
console.log('Wit.ai response: ' + body);
sendAnswer(botType, recipientId, data, question, index);
})
.catch(console.error);
}
else if (aiengine == 2) {
//Google API.ai (dialogflow)
var request = googleai.textRequest(question, {
sessionId: recipientId
});
request.on('response', function(response) {
var body = JSON.stringify(response);
console.log('API.ai response: ' + body);
//sendAnswer(botType, recipientId, response, question, index);
sendAnswerFromAPIAI(botType, recipientId, response, question, index);
});
request.on('error', function(error) {
console.log(error);
});
request.end();
}
}
function sendMessage(botType, recipientId, msg, index) {
if(botType == 1) {
//Native Chat
sendMessageNativeBot(msg, 'Luzbot', 'red', index);
}
else if(botType == 2) {
//Facebook Chat
sendMessageFacebook(recipientId, msg);
}
}
function sendMessageNativeBot(msg, userName, userColor, index) {
// we want to keep history of all sent messages
var obj = {
time: (new Date()).getTime(),
text: htmlEntities(msg),
author: userName,
color: userColor
};
history.push(obj);
history = history.slice(-100);
// broadcast message to all connected clients
var json = JSON.stringify({ type:'message', data: obj });
//Only for the specific client
for (var i=0; i < clients.length; i++) {
if(i == index) {
clients[i].sendUTF(json);
}
}
}
// ----------------------------------------------------------------------------
// Facebook Messenger specific code
//Sends a Message in Facebook Chat
function sendMessageFacebook(recipientId, msg) {
console.log("my bot id: " + MY_BOT_ID);
console.log("fbMessage id: " + recipientId);
if(recipientId != MY_BOT_ID) {
var message = {text: msg};
request({
url: 'https://graph.facebook.com/v2.10/me/messages',
qs: {access_token: FB_PAGE_ACCESS_TOKEN},
method: 'POST',
json: {
recipient: {id: recipientId},
message: message,
}
}, function(error, response, body) {
if (error) {
console.log('Error sending message: ', error);
} else if (response.body.error) {
console.log('Error on sendMessageFacebook: ', response.body.error);
}
});
}
};
//Process JSON for correct answer
function sendAnswerFromAPIAI(botType, recipientId, nlpJson, question, index) {
if(question.toUpperCase() == "HI") {
var answer = "Hi. How are you?";
sendMessage(botType, recipientId, answer, index);
}
else if(question.toUpperCase() == "VERSION") {
var answer = "Aktuelle Version ist " + VERSION;
sendMessage(botType, recipientId, answer, index);
}
else if(nlpJson.hasOwnProperty('result') && Object.keys(nlpJson.result).length > 0){
console.log('property result exists and has at least one entity');
var result = nlpJson['result'];
console.log('result: ' + JSON.stringify(result));
var fulfillment = nlpJson['result']['fulfillment'];
console.log('fulfillment: ' + JSON.stringify(fulfillment));
var speech = nlpJson['result']['fulfillment']['speech'];
console.log('speech: ' + JSON.stringify(speech));
sendMessage(botType, recipientId, speech, index);
}
else {
var answer = "Ich verstehe deine Anfrage nicht. Sorry.";
sendMessage(botType, recipientId, answer, index);
}
}