-
Notifications
You must be signed in to change notification settings - Fork 6
/
app.js
54 lines (44 loc) · 1.31 KB
/
app.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
const express = require('express');
const cors = require('cors');
// Utils
const { getRandomDelay, getBotResponse, parseResponseDataset } = require('./utils');
// Constants
const {
PORT,
RESPONSES_FILE_PATH,
USER_MESSAGE_EVENT,
BOT_MESSAGE_EVENT,
BOT_TYPING_EVENT,
MIN_TYPING_S,
MAX_TYPING_S,
MIN_NATURAL_PAUSE_S,
MAX_NATURAL_PAUSE_S
} = require('./constants');
const app = express();
const http = require('http').createServer(app);
const router = express.Router();
const io = require('socket.io')(http);
let botResponses = null;
app.use(router);
app.use(cors({ origin: '*' }));
app.use(express.static(__dirname + '/public'));
io.on('connection', (socket) => {
socket.on(USER_MESSAGE_EVENT, (message) => {
setTimeout(() => {
// Don't emit a typing event if we've set typing seconds to 0
if(MAX_TYPING_S) { socket.emit(BOT_TYPING_EVENT); }
setTimeout(() => {
socket.emit(
BOT_MESSAGE_EVENT,
getBotResponse(message, botResponses)
);
}, getRandomDelay(MIN_TYPING_S, MAX_TYPING_S));
}, getRandomDelay(MIN_NATURAL_PAUSE_S, MAX_NATURAL_PAUSE_S));
});
});
parseResponseDataset(RESPONSES_FILE_PATH).then(parsedResponses => {
botResponses = parsedResponses;
});
http.listen(PORT, () => {
console.log(`Botty server listening on *:${PORT} 🚀`);
});