-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprocess-message.js
66 lines (55 loc) · 1.73 KB
/
process-message.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
const Dialogflow = require('dialogflow');
const Pusher = require('pusher');
const getWeatherInfo = require('./weather');
// You can find your project ID in your Dialogflow agent settings
const projectId = 'chatbot-poarse'; //https://dialogflow.com/docs/agents#settings
const sessionId = '123456';
const languageCode = 'en-US';
const config = {
credentials: {
private_key: process.env.DIALOGFLOW_PRIVATE_KEY,
client_email: process.env.DIALOGFLOW_CLIENT_EMAIL,
},
};
const pusher = new Pusher({
appId: process.env.PUSHER_APP_ID,
key: process.env.PUSHER_APP_KEY,
secret: process.env.PUSHER_APP_SECRET,
cluster: process.env.PUSHER_APP_CLUSTER,
encrypted: true,
});
const sessionClient = new Dialogflow.SessionsClient(config);
const sessionPath = sessionClient.sessionPath(projectId, sessionId);
const processMessage = message => {
const request = {
session: sessionPath,
queryInput: {
text: {
text: message,
languageCode,
},
},
};
sessionClient
.detectIntent(request)
.then(responses => {
const result = responses[0].queryResult;
// If the intent matches 'detect-city'
if (result.intent.displayName === 'detect-city') {
const city = result.parameters.fields['geo-city'].stringValue;
// fetch the temperature from openweather map
return getWeatherInfo(city).then(temperature => {
return pusher.trigger('bot', 'bot-response', {
message: `The weather is ${city} is ${temperature}°C`,
});
});
}
return pusher.trigger('bot', 'bot-response', {
message: result.fulfillmentText,
});
})
.catch(err => {
console.error('ERROR:', err);
});
};
module.exports = processMessage;