-
Notifications
You must be signed in to change notification settings - Fork 8
/
dialogflowv2.js
115 lines (98 loc) · 3.04 KB
/
dialogflowv2.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
var _ = require('underscore');
var utils = require('./lib/helpers/utils');
var lcd = require('./lib/helpers/lcd');
var dialogflow = require('dialogflow');
var when = utils.when;
module.exports = function(RED) {
function DialogflowV2(config) {
RED.nodes.createNode(this, config);
var node = this;
node.dialogflow = config.dialogflow;
node.language = config.language;
node.debug = config.debug;
node.variable = config.variable;
this.on('input', function (msg) {
var dialogFlowNode = RED.nodes.getNode(node.dialogflow);
var language = utils.extractValue('string', 'language', node, msg, false);
var variable = utils.extractValue('string', 'variable', node, msg, false);
var debug = utils.extractValue('boolean', 'debug', node, msg, false);
// exit if empty credentials
if (dialogFlowNode == null || dialogFlowNode.credentials == null) {
lcd.warn('Dialogflow.ai credentials are missing.');
return;
}
// error if no language at all
if (_.isEmpty(language)) {
node.error('Language param is empty in Dialogflow node');
return;
}
var email = dialogFlowNode.credentials.email;
var privateKey = dialogFlowNode.credentials.privateKey;
var projectId = dialogFlowNode.credentials.projectId;
var sessionClient = new dialogflow.SessionsClient({
credentials: {
private_key: privateKey,
client_email: email
}
});
var sessionPath = sessionClient.sessionPath(projectId, String(msg._msgid));
var request = {
session: sessionPath,
queryInput: {
text: {
text: msg.payload,
languageCode: language.toLowerCase()
}
}
};
var body = null;
function start (key, value) {
var global = key+value;
return global;
}
when(start('id ', msg._msgid))
.then(function() {
return sessionClient.detectIntent(request);
})
.then(function(response) {
body = response;
return when(msg!==null);
})
.then(function() {
if (body == null || !_.isArray(body) || _.isEmpty(body)) {
return Promise.reject('Error on api.dialogflow.com');
}
})
.then(function() {
//Result output
msg._dialogflow = body[0].queryResult;
if (debug) {
lcd.node(msg.payload, { node: node, title: 'Dialogflow-V2.com' });
}
node.send([msg, null]);
})
.catch(function(error) {
if (error != null) {
node.error(error, msg);
}
});
});
}
RED.nodes.registerType('dialogflowv2', DialogflowV2);
function DialogflowV2Token(n) {
RED.nodes.createNode(this, n);
}
RED.nodes.registerType('dialogflowv2-token', DialogflowV2Token, {
credentials: {
email: {
type: 'text'
},
privateKey: {
type: 'text'
},
projectId: {
type: 'text'
}
}
});
};