-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
68 lines (59 loc) · 1.85 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
const path = require("path");
const express = require("express");
const colors = require("colors");
const dotenv = require("dotenv");
const socketio = require("socket.io");
const dialogflow = require("@google-cloud/dialogflow");
const uuid = require("uuid");
const app = express();
dotenv.config({ path: "./config/config.env" });
app.use(express.static(path.join(__dirname, "views")));
app.use(express.static(path.join(__dirname, "public")));
const PORT = process.env.PORT || 3000;
const server = app.listen(
PORT,
console.log(
`Server is runnig on ${process.env.NODE_ENV} mode at port ${PORT}`.yellow .bold
)
);
const io = socketio(server);
io.on("connection", function (socket) {
console.log("a user connected");
socket.on("chat message", (message) => {
console.log(message);
const callapibot = async (projectId = process.env.PROJECT_ID) => {
try {
const sessionId = uuid.v4();
const sessionClient = new dialogflow.SessionsClient({
keyFilename: "./smartbot-dkgh-5e8a17fdde9f.json",
});
const sessionPath = sessionClient.projectAgentSessionPath(
projectId,
sessionId
);
const request = {
session: sessionPath,
queryInput: {
text: {
text: message,
languageCode: "en-US",
},
},
};
const responses = await sessionClient.detectIntent(request);
console.log("Detected intent");
const result = responses[0].queryResult.fulfillmentText;
socket.emit("bot reply", result);
console.log(result);
if (result.intent) {
console.log(` Intent: ${result.intent.displayName}`);
} else {
console.log(` No intent matched.`);
}
} catch (error) {
console.log(error);
}
};
callapibot();
});
});