-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
135 lines (115 loc) · 4.61 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
const express = require('express');
const app = express();
const dialogflow = require('dialogflow');
const uuid = require('uuid');
const request = require('request');
require('dotenv').config();
let port = process.env.PORT || 3000;
let server = app.listen(port, () => {
console.log("Server started, listening to port: "+port);
});
const socket = require('socket.io');
let io = socket(server);
app.use(express.static('./test'));
let users = {};
io.on('connection', socket => {
console.log(`a User joined with socket id: ${socket.id}`);
socket.join('General');
socket.on('data', data => {
if(!data.username) return socket.emit('err', { code: 0, msg: "Invalid username" });
let usersKey = Object.keys(users);
let allowed = true;
usersKey.forEach((a) => {
if(users[a].username == data.username) {
allowed = false;
return socket.emit('err', { code: 1, msg: "user already used"});
}
});
if(allowed) {
socket.to('General').broadcast.emit('userJoin', data.username);
let id = genId();
if(usersKey.find(a => a == id)) id = genId();
users[id] = {
username: data.username,
socketId: socket.id,
id: id
}
socket.emit("clientData", {
id: id
});
socket.on('message', async message => {
let msgArr = message.split(' ');
let cmd = msgArr[0];
let args = msgArr.slice(1, msgArr.length);
if(cmd === '@bot' || cmd === '@Bot') {
if(args.join(' ').length > 0) {
runSample(process.env.PROJECTID, args.join(' ').trim(), "en-US", async res => {
let display = res.queryResult.intent.displayName,
confidence = res.intentDetectionConfidence,
fulfillment = res.queryResult.fulfillmentText;;
if(display == "Question") {
let url = process.env.CUSTOMSEARCH_URI+args.join('+');
request(url, (e, res, body) => {
if(e) console.log(e);
body = JSON.parse(body);
let first = body.items[0];
return io.to('General').emit('userMessage', {
message: `${fulfillment} ${first.formattedUrl}`,
by: "Bot",
id: 101
});
});
return;
} else {
return io.to('General').emit('userMessage', {
message: fulfillment,
by: "Bot",
id: 101
});
return;
}
});
}
}
socket.to('General').broadcast.emit('userMessage', {
message: message,
by: users[id].username,
id
});
});
socket.on("disconnect", async () => {
console.log(`a User disconnected with socket id: ${socket.id}`)
await socket.broadcast.emit("userDisconnect", users[id].username);
delete users[id]
});
}
});
});
function genId() {
return Math.floor(Math.random() * (1000 - 111)) + 111;
};
/**
* Send a query to the dialogflow agent, and return the query result.
* @param {string} projectId The project to be used
* @param {string} text
* @param {string} lang
* @param {function} callback
*/
async function runSample(projectId=null, text, lang="en-US", callback) {
if(!projectId) throw new Error("Invalid projectId")
const sessionId = uuid.v4();
const sessionClient = new dialogflow.SessionsClient();
const sessionPath = sessionClient.sessionPath(projectId, sessionId);
const request = {
session: sessionPath,
queryInput: {
text: {
text: text,
languageCode: lang,
},
},
};
await sessionClient.detectIntent(request).then(res => {
return callback(res[0]);
});
}