-
Notifications
You must be signed in to change notification settings - Fork 6
/
bot.js
99 lines (83 loc) · 2.64 KB
/
bot.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
const botBuilder = require('claudia-bot-builder');
const Mustache = require('mustache');
const aws = require( './bot/aws');
const forecast = require('./bot/forecast');
const lang = require('./locale/en.json');
function debugOut() {
if (process.env.DEBUG && parseInt(process.env.DEBUG) == 1) {
for (let argument of arguments) {
console.log(argument);
}
}
}
function isValidTranslation(translation) {
return (
translation.success &&
translation.body.TranslatedText &&
translation.body.TranslatedText != '' &&
translation.body.TargetLanguageCode &&
translation.body.TargetLanguageCode == 'en'
);
}
async function processGetWeatherForecastIntent(intent) {
if (!intent.body.slots.Location) {
return lang.MISSING_LOCATION;
}
let forecastInfo = await forecast.getForecastForLocationAndDate(
intent.body.slots.Location,
intent.body.slots.Date
);
debugOut(forecastInfo);
return Mustache.render(lang.FORECAST, forecastInfo);
}
function processIntent(intent) {
if (intent.body.intentName == 'GetWeatherForecast') {
return processGetWeatherForecastIntent(intent);
}
return lang.DID_NOT_UNDERSTAND;
}
async function translateInput(request) {
// Trying to decode the input message
var intent = await aws.invokeLex(request);
var targetLanguageCode = null;
debugOut(intent);
if (intent.success && !intent.body.intentName) {
// If no intent is decoded, try to identify language and translate
var translation = await aws.invokeTranslate(request.text);
debugOut(translation);
if (isValidTranslation(translation)) {
request.text = translation.body.TranslatedText;
targetLanguageCode = translation.body.SourceLanguageCode;
intent = await aws.invokeLex(request);
debugOut(intent);
}
}
return {
intent: intent,
targetLanguageCode: targetLanguageCode
}
}
async function translateOutput(input, response) {
// In case the input message was translated,
// translate back to the original language
if (input.targetLanguageCode) {
translatedResponse = await aws.invokeTranslate(response, 'en', input.targetLanguageCode);
debugOut(translatedResponse);
if (translatedResponse.success) {
response = translatedResponse.body.TranslatedText;
}
}
return response;
}
async function processRequest(request) {
let input = await translateInput(request);
if (input.intent.success) {
let response = await processIntent(input.intent);
return await translateOutput(input, response);
}
return lang.GENERIC_ERROR;
}
module.exports = botBuilder(function (request) {
debugOut(request);
return processRequest(request);
});