-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
51 lines (37 loc) · 1.2 KB
/
server.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
'use strict';
const APIAI_TOKEN = process.env.APIAI_TOKEN;
const APIAI_SESSION_ID = process.env.APIAI_SESSION_ID;
const express = require('express');
const app = express();
app.use(express.static(__dirname + '/views')); // html
app.use(express.static(__dirname + '/public')); // js, css, images
const server = app.listen(process.env.PORT || 8080, () => {
console.log('server listening on port %d in %s mode', server.address().port, app.settings.env);
});
const io = require('socket.io')(server);
io.on('connection', function(socket){
console.log('a user connected');
});
const apiai = require('apiai')(APIAI_TOKEN);
// Web UI
app.get('/', (req, res) => {
res.sendFile('index.html');
});
io.on('connection', function(socket) {
socket.on('chat message', (text) => {
console.log('Message: ' + text);
// Get a reply from API.ai
let apiaiReq = apiai.textRequest(text, {
sessionId: APIAI_SESSION_ID
});
apiaiReq.on('response', (response) => {
let aiText = response.result.fulfillment.speech;
console.log('Bot reply: ' + aiText);
socket.emit('bot reply', aiText);
});
apiaiReq.on('error', (error) => {
console.log(error);
});
apiaiReq.end();
});
});