-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathindex.js
More file actions
76 lines (58 loc) · 1.88 KB
/
index.js
File metadata and controls
76 lines (58 loc) · 1.88 KB
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
"use strict";
const express = require("express");
const bodyParser = require("body-parser");
// Instantiate a DialogFlow client.
const dialogflow = require('dialogflow');
var cors = require('cors');
const restService = express();
restService.use(cors());
restService.use(
bodyParser.urlencoded({
extended: true
})
);
restService.use(bodyParser.json());
const projectId = 'Your-Proyect-Key';
//https://dialogflow.com/docs/agents#settings
// generate session id (currently hard coded)
const sessionId = '2eccb33b-8494-40dd-ac92-212972b9dbea';
const languageCode = 'en-US';
let privateKey = 'Your-Private Key';
// as per goolgle json
let clientEmail = "Your-Client-Email";
let config = {
credentials: {
private_key: privateKey,
client_email: clientEmail
}
}
const sessionClient = new dialogflow.SessionsClient(config);
// Define session path
const sessionPath = sessionClient.sessionPath(projectId, sessionId);
restService.post("/message", async function (req, res) {
if(!req.body) return res.sendStatus(400);
// The text query request.
const request = {
session: sessionPath,
queryInput: {
text: {
text: req.body.messageText,
languageCode: languageCode,
},
},
};
// Send request and log result
sessionClient
.detectIntent(request)
.then(responses => {
const result = responses[0].queryResult;
console.log(` Response: ${result.fulfillmentText}`);
return res.json({ messageResponse: result.fulfillmentText });
})
.catch(err => {
return res.json({ messageResponse: "Intente nuevamente" });
});
});
restService.listen(process.env.PORT || 8000, function () {
console.log("Server up and listening");
});