36 Commits

Author SHA1 Message Date
GotPPay
dc2c8f384e use foreach instead of map 2018-01-23 12:15:04 +01:00
GotPPay
cc579133c0 Amazon default intents not working with dialog 2018-01-23 02:23:59 +01:00
GotPPay
0a8eb2e280 fix code 2018-01-23 02:18:08 +01:00
GotPPay
6b26db3d18 fix code 2018-01-23 02:15:44 +01:00
GotPPay
3202bf5f0b Implement help intent 2018-01-23 01:56:07 +01:00
GotPPay
370edd6ef0 fix inherited explanation bug 2018-01-23 01:51:36 +01:00
GotPPay
0d858ad1c7 List only questions with explanation 2018-01-23 01:46:02 +01:00
GotPPay
c6cd49a66f fix typo 2018-01-23 01:41:34 +01:00
GotPPay
97b6755f2f No magic numbers 2018-01-23 01:40:19 +01:00
GotPPay
b2386ea0d6 Yes and No intent dont work with dialog 2018-01-23 01:03:59 +01:00
GotPPay
2ae983d211 Experiment with Yes and No intent 2018-01-23 00:40:19 +01:00
GotPPay
b1a853c363 experiment with Yes and No intents 2018-01-23 00:20:50 +01:00
GotPPay
d58d4b89e3 experiment with yes intent 2018-01-23 00:08:39 +01:00
GotPPay
2c6953fe97 list all questions on Launch 2018-01-22 23:35:25 +01:00
GotPPay
af19108e9c fix InteractionModel generator 2018-01-22 22:34:58 +01:00
GotPPay
a00859c594 fix InteractionModel generator 2018-01-22 22:34:13 +01:00
GotPPay
085a0324b3 . 2018-01-22 20:12:16 +01:00
GotPPay
d8799fa40d fix JSON model 2018-01-19 23:26:59 +01:00
GotPPay
de0a4f3176 fix reverting skill on failed update 2018-01-19 22:54:50 +01:00
GotPPay
48578d3ffe Change UI 2018-01-19 22:42:37 +01:00
GotPPay
e2d648980b fix code 2018-01-19 20:28:26 +01:00
GotPPay
b73086291c code fix and improvements 2018-01-19 20:23:50 +01:00
GotPPay
434d45248c fix error in validation and undefined email value 2018-01-19 20:15:27 +01:00
GotPPay
00272ec67d validate email using regex 2018-01-19 20:05:49 +01:00
GotPPay
0727328e58 improve email preview 2018-01-19 19:53:49 +01:00
GotPPay
e2d76ff03e improve email preview 2018-01-19 19:50:21 +01:00
GotPPay
9cff3cd9ae change email service 2018-01-19 19:28:46 +01:00
GotPPay
2f82709f11 improve dialog ; send email 2018-01-19 16:29:47 +01:00
GotPPay
4b594898b1 Complete dialogtest 2018-01-19 08:00:51 +01:00
GotPPay
b07a9e21b3 Testing dialog handler 2018-01-19 07:43:10 +01:00
GotPPay
a570640fe1 hande unknown questions 2018-01-18 22:07:23 +01:00
GotPPay
9e4b06bd4c keep session open - fix 2018-01-18 21:56:56 +01:00
GotPPay
6bfd4adcaf keep session open 2018-01-18 21:50:26 +01:00
GotPPay
48badce0f0 fix 'res not defined' 2018-01-18 21:43:25 +01:00
GotPPay
68287d49ff complete switch to new alexa package 2018-01-18 21:33:44 +01:00
GotPPay
2f59e12aa7 test new library 2018-01-18 19:50:13 +01:00
15 changed files with 776 additions and 423 deletions

View File

@@ -67,7 +67,7 @@ Prerequests for step 3 (run on server):
requires running mongodb service requires running mongodb service
Database (tellall) with collection (skill_list) Database (tellall) with collection (skill_list)
* Insert dummy skill with : db.skill_list.insert({"skillID" : "amzn1.ask.skill.efbf0564-a732-4ba9-958f-57939138adae", "intents" : [ { "intentName" : "GetFirstQuestion", "questions" : [ "tell me something about projects", "tell me all about projects" ], "answer" : "blablabla bla bla" }, { "intentName" : "GetThirdQuestion", "questions" : [ "Give me third question" ], "answer" : "This is answer to the third question" } ], "invocationName" : "Saburly", "invocationAnswer" : "We are Saburly team one" }) * Insert dummy skill with : db.skill_list.insert({"skillID" : "amzn1.ask.skill.efbf0564-a732-4ba9-958f-57939138adae", "intents" : [ { "intentName" : "GetFirstQuestion", "questionExplanation" : "", "questions" : [ "tell me something about projects", "tell me all about projects" ], "answer" : "blablabla bla bla" }, { "intentName" : "GetThirdQuestion", "questionExplanation" : "", "questions" : [ "Give me third question" ], "answer" : "This is answer to the third question" } ], "invocationName" : "Saburly", "invocationAnswer" : "We are Saburly team one" })
*obtain _id and change in web/src/App.js, and also skill_db_id in backend/config.js *obtain _id and change in web/src/App.js, and also skill_db_id in backend/config.js
*enter web/ dir and run "npm run build" *enter web/ dir and run "npm run build"

View File

@@ -1,204 +0,0 @@
var alexa = require ('alexa-app');
const config = require ('../config/config');
var databaseHelper = require ('../helpers/database');
//User data for sending message, this is skill-related and will be in some skill container
var Name = null;
var Email = null;
var Message = null;
var State = 0; // states should be defined in seperate file. (Not sending message, Waiting for name, Waiting for email, Waiting for message)
//For now (this is not long term solution)
// 0 : Not sending Message
// 1 : Waiting for name
// 2 : Waiting for email
// 3 : Waiting for message
var alexaApp = new alexa.app ('saburly'); // this means we still work with one skill
module.exports = {
init: function (express) {
alexaApp.express ({
expressApp: express,
// verifies requests come from amazon alexa. Must be enabled for production.
// You can disable this if you're running a dev environment and want to POST
// things to test behavior. enabled by default.
checkCert: false,
// sets up a GET route when set to true. This is handy for testing in
// development, but not recommended for production. disabled by default
debug: true,
});
},
updateIntentsJSON: function () {
databaseHelper
.getSkill (config.SKILL_DB_ID)
.then (skill => {
skill.intents.map (intent => {
alexaApp.intent (
intent.intentName,
{
slots: [],
utterances: intent.questions,
},
function (request, response) {
return response.say (intent.answer).shouldEndSession (false);
}
);
});
alexaApp.launch ((request, response) => {
return response.say (skill.invocationAnswer).shouldEndSession (false);
});
alexaApp.intent (
'EmailIntentLaunch',
{
slots: [],
utterances: [
'I want to send a message',
'I would like to send a message',
'I would like to leave a message',
'Leave a message',
],
},
function (request, response) {
Name = null;
Email = null;
Message = null;
State = 1;
return response
.say ('Ok. What is your name')
.shouldEndSession (false);
}
);
//TODO : Watch out for this intent. It will make trouble with other regular intents
//if other intents have utterance with just one slot like {Data}
//It should be taken care somwhere before this, to check if Email Intent is invoked
//This is problem only if we introduce slot options for regular intents for users
alexaApp.intent (
'EmailIntent',
{
slots: {
Name: 'AMAZON.US_FIRST_NAME',
Email: 'AMAZON.LITERAL',
Message: 'AMAZON.LITERAL',
Data: 'AMAZON.LITERAL',
},
utterances: [
'My name is {-|Name}',
'I am {-|Name}',
'{dawdw at dwd wdw|Data}',
'My email is {wadwwdw at wadwwd wdw|Email}',
'Send replay to {fkofkeofe at dppfam wd|Email}',
'My message is {Quick brown fox jumps over lazy dog|Message}',
],
},
function (request, response) {
let Data = undefined;
try {
if (!Name) Name = request.slot ('Name');
} catch (e) {
console.log ('Error. No name slot ');
Name = undefined;
}
try {
if (!Email) Email = request.slot ('Email');
} catch (e) {
console.log ('Error. No Email slot');
Email = undefined;
}
try {
if (!Message) Message = request.slot ('Message');
} catch (e) {
console.log ('Error. No Message slot');
Message = undefined;
}
try {
Data = request.slot ('Data');
} catch (e) {
console.log ('Error. No Data slot');
Data = undefined;
}
console.log ('State : ' + State);
//TODO : Responses could be configurable for each skill ?
if (State === 1) {
//Was waiting for name, so if Name is null, name is probably in Data
if ((!Name && Data) || Name) {
//got the name, let's continue for the email
if (!Name) Name = Data;
State = 2;
return response
.say ('Ok ' + Name + '. What is your email ?')
.shouldEndSession (false);
} else {
//Something is wrong, ask for name again
return response
.say (
'Sorry, I didnt understand your name. Can you say it again ?'
)
.shouldEndSession (false);
}
} else if (State === 2) {
//was waiting for email, so if Email is null, email is probably in Data
if ((!Email && Data) || Email) {
//Got the email, first verify email and than continue to message
if (!Email) Email = Data;
//TODO : verify email
State = 3;
return response
.say ('Great. Whats the message ?')
.shouldEndSession (false);
} else {
//Something is wrong, ask for the email again
return response
.say (
'Sorry, I didnt understan you email. Can you say it again ?'
)
.shouldEndSession (false);
}
} else if (State === 3) {
//Was waiting for message, so if Message is null, message is probably in Data
if ((!Message && Data) || Message) {
//Ok, we got all informations. Exit email intent
if (!Message) Message = Data;
State = 0;
//TODO : Send email
console.log (
'Name : ' +
Name +
' | Email : ' +
Email +
' | Message : ' +
Message
);
return response.say (
'Message sent. Someone will contact you ASAP'
);
} else {
//Something is wrong, ask for the message again
return response
.say (
'Sorry, I didnt understand your message. Can you say it again ?'
)
.shouldEndSession (false);
}
} else {
console.log ('State strange ! ' + State);
}
}
);
})
.catch (err => {
console.log (err);
alexaApp.launch ((request, response) => {
return response.say ('Sorry, there was no skill with that name');
});
});
},
};

View File

@@ -17,7 +17,7 @@ constants.apiResultCodes = {
AMAZON_FAIL:2, //amazon api doesn't work AMAZON_FAIL:2, //amazon api doesn't work
DATABASE_ERROR:3, DATABASE_ERROR:3,
NO_SKILL:4, NO_SKILL:4,
INCONSISTEN_STATE:5, INCONSISTENT_STATE:5,
} }
constants.HTTPResultCodes = { constants.HTTPResultCodes = {
@@ -26,6 +26,17 @@ constants.HTTPResultCodes = {
constants.SKILL_ID_LENGTH = 24; constants.SKILL_ID_LENGTH = 24;
constants.voiceResponseStrings = {
QUESTION_NOT_FOUND : 'Sorry, I didnt understand',
GENERIC_CONTINUE : 'Would you like to continue'
}
//Timing is given in [ms]
constants.voiceResponseTimings = {
PAUSE_BETWEEN_QUESTIONS : 650,
PAUSE_AFTER_WELCOME_MESSAGE : 650,
}
module.exports = constants; module.exports = constants;

14
backend/config/email.js Normal file
View File

@@ -0,0 +1,14 @@
var config = {};
config.PORT = 587;
config.SMTP_HOST = 'smtp.mail.com';
config.SECURE = false;
config.AUTH = {
user: 'saburly@mail.com',
pass: 'KeepSaburly',
};
config.FROM_EMAIL = 'saburly@mail.com';
config.SUBJECT = 'Message from Saburly service';
module.exports = config;

View File

@@ -1,5 +1,6 @@
var express = require ('express'), router = express.Router (); var express = require ('express'), router = express.Router ();
router.use ('/skill', require ('./skill')); router.use ('/skill', require ('./skill'));
router.use ('/saburly', require('./saburlyEntryPoint'));
module.exports = router; module.exports = router;

View File

@@ -0,0 +1,9 @@
var express = require ('express'), router = express.Router ();
var bodyParser = require ('body-parser');
var alexa = require ('../models/alexa');
router.post ('/', bodyParser.json (), async (req, res) => {
alexa.run (req, res);
});
module.exports = router;

View File

@@ -3,7 +3,7 @@ const constants = require ('../config/constants');
var databaseHelper = require ('../helpers/database'); var databaseHelper = require ('../helpers/database');
var amazonHelper = require ('../helpers/amazon'); var amazonHelper = require ('../helpers/amazon');
var bodyParser = require ('body-parser'); var bodyParser = require ('body-parser');
var alexa = require ('../components/alexa'); var alexa = require ('../models/alexa');
router.get ('/:id', async (req, res, next) => { router.get ('/:id', async (req, res, next) => {
const id = req.params.id; const id = req.params.id;
@@ -41,6 +41,7 @@ router.put ('/:id', bodyParser.json (), async (req, res, next) => {
.then (() => { .then (() => {
//Ok, done, now update skill on Amazon (if needed) //Ok, done, now update skill on Amazon (if needed)
if (updateOnAmazon) { if (updateOnAmazon) {
//We need to update skill on Amazon
amazonHelper amazonHelper
.updateSkill (skill) .updateSkill (skill)
.then (amazonResult => { .then (amazonResult => {
@@ -49,47 +50,80 @@ router.put ('/:id', bodyParser.json (), async (req, res, next) => {
amazonResult === constants.amazonResultCodes.ACCEPTED amazonResult === constants.amazonResultCodes.ACCEPTED
) { ) {
res.json ({result: constants.apiResultCodes.OK, message: ''}); res.json ({result: constants.apiResultCodes.OK, message: ''});
alexa.updateIntentsJSON (); alexa.updateModel ();
} else { } else {
res.status(constants.HTTPResultCodes.INTERNAL_SERVER_ERROR).json ({ //Update on amazon failed, revert changes in database and send error to user
result: constants.apiResultCodes.AMAZON_ERROR, databaseHelper
message: amazonResult, .updateSkill (id, currentSkillState)
}); .then (() => {
res
.status (
constants.HTTPResultCodes.INTERNAL_SERVER_ERROR
)
.json ({
result: constants.apiResultCodes.AMAZON_ERROR,
message: amazonResult,
});
})
.catch (() => {
//This should never happen, something is seriously wrong, like no database connection
res
.status (
constants.HTTPResultCodes.INTERNAL_SERVER_ERROR
)
.json ({
result: constants.apiResultCodes.INCONSISTENT_STATE,
message: '',
});
});
} }
}) })
.catch (e => { .catch (e => {
res.status(constants.HTTPResultCodes.INTERNAL_SERVER_ERROR).json ({ //Update on amazon failed, revert changes in database and send error to user
result: constants.apiResultCodes.AMAZON_FAIL, databaseHelper
message: e, .updateSkill (id, currentSkillState)
}); .then (() => {
res
.status (constants.HTTPResultCodes.INTERNAL_SERVER_ERROR)
.json ({
result: constants.apiResultCodes.AMAZON_FAIL,
message: e,
});
})
.catch (() => {
//This should never happen, something is seriously wrong, like no database connection
res
.status (constants.HTTPResultCodes.INTERNAL_SERVER_ERROR)
.json ({
result: constants.apiResultCodes.INCONSISTENT_STATE,
message: '',
});
});
}); });
}else{ } else {
//No need to update on Amazon, tell to user it's ok
res.json ({result: constants.apiResultCodes.OK, message: ''}); res.json ({result: constants.apiResultCodes.OK, message: ''});
alexa.updateIntentsJSON (); alexa.updateModel ();
} }
}) })
.catch (() => { .catch (() => {
//Update in database didn't go well, revert changes //Update in database didn't go well, no need to revert since it failed to write in the first place
databaseHelper //just send error to user
.updateSkill (id, currentSkillState) res
.then (() => { .status (
res.status(constants.HTTPResultCodes.INTERNAL_SERVER_ERROR).json ({ constants.HTTPResultCodes.INTERNAL_SERVER_ERROR
result: constants.apiResultCodes.DATABASE_ERROR, )
message: '', .json ({
}); result: constants.apiResultCodes.DATABASE_ERROR,
}) message: '',
.catch (() => { });
//This should never happen, something is seriously wrong, like no database connection
res.status(constants.HTTPResultCodes.INTERNAL_SERVER_ERROR).json ({
result: constants.apiResultCodes.INCONSISTEN_STATE,
message: '',
});
});
}); });
}) })
.catch (e => { .catch (e => {
//I don't know why, but something went wrong, possibly ID of skill is wrong, doesn't exist in DB //I don't know why, but something went wrong, possibly ID of skill is wrong, doesn't exist in DB
res.status(constants.HTTPResultCodes.INTERNAL_SERVER_ERROR).json ({result: constants.apiResultCodes.NO_SKILL, message: ''}); res
.status (constants.HTTPResultCodes.INTERNAL_SERVER_ERROR)
.json ({result: constants.apiResultCodes.NO_SKILL, message: ''});
}); });
}); });

View File

@@ -37,15 +37,22 @@ var refreshTokens = function () {
request (options, function (error, response, body) { request (options, function (error, response, body) {
if (error) { if (error) {
reject (error); reject (error);
}else{ } else {
parsedResponse = JSON.parse (body); parsedResponse = JSON.parse (body);
if (parsedResponse.refresh_token){ if (parsedResponse.refresh_token) {
databaseHelper.updateTokens(parsedResponse.refresh_token, parsedResponse.access_token, parsedResponse.expires_in).then(()=>{ databaseHelper
resolve(); .updateTokens (
}).catch(e=>{ parsedResponse.refresh_token,
reject(e); parsedResponse.access_token,
}); parsedResponse.expires_in
}else{ )
.then (() => {
resolve ();
})
.catch (e => {
reject (e);
});
} else {
reject (body); reject (body);
} }
} }
@@ -56,85 +63,186 @@ var refreshTokens = function () {
var generateInteractionModel = function (skill) { var generateInteractionModel = function (skill) {
let result = {}; let result = {};
let allIntents = []; let allIntents = [];
let defaultIntents = [
{
name: 'AMAZON.CancelIntent',
samples: [],
},
{
name: 'AMAZON.HelpIntent',
samples: [],
},
{
name: 'AMAZON.StopIntent',
samples: [],
},
];
/*
defaultIntents.map(intent=>{
allIntents.push(intent);
});
*/
skill.intents.map (intent => { skill.intents.map (intent => {
allIntents.push ({name: intent.intentName, samples: intent.questions}); allIntents.push ({name: intent.intentName, samples: intent.questions});
}); });
//Special Email Intents : //Special intent for sending message (Dialog)
allIntents.push ({
name: 'EmailIntentLaunch',
slots: [],
samples: [
'I want to send a message',
'I would like to send a message',
'I would like to leave a message',
'Leave a message',
],
});
allIntents.push ({ allIntents.push ({
name: 'EmailIntent', name: 'SendMessageIntent',
samples: [
'I would like to send a message',
'I want to send a message',
'Send message',
],
slots: [ slots: [
{ {
name: 'Name', name: 'Name',
type: 'AMAZON.US_FIRST_NAME', type: 'AMAZON.US_FIRST_NAME',
samples: ['My name is {Name}', 'I am {Name}', '{Name}'],
}, },
{ {
name: 'Email', name: 'Email',
type: 'AMAZON.LITERAL', type: 'EmailSlot',
samples: ['My email is {Email}', '{Email}'],
}, },
{ {
name: 'Message', name: 'Message',
type: 'AMAZON.LITERAL', type: 'MessageSlot',
samples: ['{Message}'],
}, },
{
name: 'Data',
type: 'AMAZON.LITERAL',
},
],
samples: [
'My name is {Name}',
'I am {Name}',
'{exampleww at wwdwdw|Data}',
'My email is {example at efefegedd|Email}',
'Send replay to {example at abcdefg|Email}',
'My message is {The quick brown fox jumps over the lazy dog.The quick brown fox jumps over the lazy dog.The quick brown fox jumps over the lazy dog.|Message}',
], ],
}); });
let customSlotTypes = [
{
name: 'EmailSlot',
values: [
{
id: null,
name: {
value: 'bla@bla.bla',
synonyms: [],
},
},
{
id: null,
name: {
value: 'bla.bla@bla.bla.bla',
synonyms: [],
},
},
{
id: null,
name: {
value: 'bla_bla@bla.bla',
synonyms: [],
},
},
],
},
{
name: 'MessageSlot',
values: [
{
id: null,
name: {
value: 'Quick brown fox jumps over lazy dog',
synonyms: [],
},
},
{
id: null,
name: {
value: 'Quick brown fox jumps over lazy dog. Quick brown fox jumps over lazy dog.',
synonyms: [],
},
},
{
id: null,
name: {
value: 'Quick brown fox jumps over lazy dog. Quick brown fox jumps over lazy dog. Quick brown fox jumps over lazy dog.',
synonyms: [],
},
},
],
},
];
let dialogPrompts = [
{
id: 'Elicit.Intent-SendMessageIntent.IntentSlot-Name',
variations: [
{
type: 'PlainText',
value: 'What is your name ?',
},
{
type: 'PlainText',
value: 'Tell me your name',
},
],
},
{
id: 'Elicit.Intent-SendMessageIntent.IntentSlot-Email',
variations: [
{
type: 'PlainText',
value: 'What is your email ?',
},
{
type: 'PlainText',
value: 'Tell me your email',
},
],
},
{
id: 'Elicit.Intent-SendMessageIntent.IntentSlot-Message',
variations: [
{
type: 'PlainText',
value: 'What is your message',
},
],
},
];
let dialogIntents = [
{
name: 'SendMessageIntent',
confirmationRequired: false,
prompts: {},
slots: [
{
name: 'Name',
type: 'AMAZON.US_FIRST_NAME',
elicitationRequired: true,
confirmationRequired: false,
prompts: {
elicitation: 'Elicit.Intent-SendMessageIntent.IntentSlot-Name',
},
},
{
name: 'Email',
type: 'EmailSlot',
elicitationRequired: true,
confirmationRequired: false,
prompts: {
elicitation: 'Elicit.Intent-SendMessageIntent.IntentSlot-Email',
},
},
{
name: 'Message',
type: 'MessageSlot',
elicitationRequired: true,
confirmationRequired: false,
prompts: {
elicitation: 'Elicit.Intent-SendMessageIntent.IntentSlot-Message',
},
},
],
},
];
result.interactionModel = {}; result.interactionModel = {};
result.interactionModel.languageModel = { result.interactionModel.languageModel = {
invocationName: skill.invocationName, invocationName: skill.invocationName,
types: customSlotTypes,
intents: allIntents, intents: allIntents,
}; };
result.interactionModel.prompts = dialogPrompts;
result.interactionModel.dialog = {};
result.interactionModel.dialog.intents = dialogIntents;
return JSON.stringify (result); return JSON.stringify (result);
}; };
var uploadSkill = function (skill) { var uploadSkill = function (skill) {
let generatedInteractionModel = generateInteractionModel (skill);
return fetch ( return fetch (
`https://api.amazonalexa.com/v0/skills/${skill.skillID}/interactionModel/locales/en-US`, `https://api.amazonalexa.com/v0/skills/${skill.skillID}/interactionModel/locales/en-US`,
{ {
@@ -142,7 +250,7 @@ var uploadSkill = function (skill) {
headers: { headers: {
Authorization: config.TOKEN, Authorization: config.TOKEN,
}, },
body: generateInteractionModel (skill), body: generatedInteractionModel,
} }
); );
}; };

75
backend/helpers/email.js Normal file
View File

@@ -0,0 +1,75 @@
const nodemailer = require ('nodemailer');
const emailConfig = require('../config/email');
module.exports = {
transformEmailFromAlexaResponse: function (email) {
//email from alexa response will contain words instead of symbols, like :
//at = @
//underscore = _
//dash = -
//dot = .
//TODO: This list should be longer
let transformedEmail = email
.replace (/\s/g, '') //remove all spaces
.replace (/at/gi, '@')
.replace (/underscore/gi, '_')
.replace (/dash/gi, '-')
.replace (/dot/gi, '.');
return transformedEmail;
},
isEmailValid: function (email) {
console.log ('Email to validate : ' + email);
let validEmailRegex = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return validEmailRegex.test (email);
},
sendEmal: function (name, fromEmail, message, toEmail) {
return new Promise ((resolve, reject) => {
fromEmail = this.transformEmailFromAlexaResponse(fromEmail);
let messageBody =
'Hello. User left you a message on Saburly service using Alexa skill. \r\nMessage : ' +
message +
'\r\nName : ' +
name +
'\r\nEmail : ' +
fromEmail +
'\r\nYour Saburly team';
let messageBodyHTML =
'<p>Hello. User left you a message on Saburly service using Alexa skill.</p><br/><b>Message : </b><br/><p>' +
message +
'</p><br/><b>Name : </b>' +
name +
'<br/><b>Email : </b>' +
fromEmail +
'<br/><br/><b>Your Saburly team</b>';
let transporter = nodemailer.createTransport ({
host: emailConfig.SMTP_HOST,
port: emailConfig.PORT,
secure: emailConfig.SECURE,
auth: emailConfig.AUTH,
});
var mailOptions = {
from: emailConfig.FROM_EMAIL,
replyTo: fromEmail,
to: toEmail,
subject: emailConfig.SUBJECT,
text: messageBody,
html: messageBodyHTML,
};
transporter.sendMail (mailOptions, (error, info) => {
if (error) {
reject (error);
} else {
resolve (info);
}
});
});
},
};

181
backend/models/alexa.js Normal file
View File

@@ -0,0 +1,181 @@
var Alexa = require ('alexa-sdk');
const config = require ('../config/config');
var databaseHelper = require ('../helpers/database');
var emailHelper = require ('../helpers/email');
const constants = require ('../config/constants');
var handlers = {};
var destinationEmail;
module.exports = {
run: function (req, res) {
// Build the context manually, because Amazon Lambda is missing
var context = {
succeed: function (result) {
res.json (result);
},
fail: function (error) {
console.log (error);
//We could send error json from here
},
};
var alexa = Alexa.handler (req.body, context);
alexa.appId = config.SKILL_ID;
alexa.registerHandlers (handlers);
alexa.execute ();
},
updateModel: function () {
//Get info from database, and store it for faster response on intent
databaseHelper
.getSkill (config.SKILL_DB_ID)
.then (activeSkill => {
handlers = {};
destinationEmail = activeSkill.contactEmail;
let listOfPossibleQuestions = '';
activeSkill.intents.forEach(intent => {
if (intent.questions.length > 0 && intent.intentExplanation) {
listOfPossibleQuestions +=
intent.intentExplanation +
intent.questions[0] +
'<break time="' +
constants.voiceResponseTimings.PAUSE_BETWEEN_QUESTIONS +
'ms"/>';
}
});
console.log(listOfPossibleQuestions);
//Handler for launch requestconsole.log()
handlers = {
LaunchRequest: function () {
this.response
.speak (
activeSkill.invocationAnswer +
'<break time="' +
constants.voiceResponseTimings.PAUSE_AFTER_WELCOME_MESSAGE +
'ms"/>' +
listOfPossibleQuestions
)
.listen (constants.voiceResponseStrings.GENERIC_CONTINUE); //Phrase from listen doesn't work !!!
this.emit (':responseReady');
},
};
//Handlers for user defined questions
activeSkill.intents.map (intent => {
handlers[intent.intentName] = function () {
this.response
.speak (intent.answer)
.listen (constants.voiceResponseStrings.GENERIC_CONTINUE); //Phrase from listen doesn't work !!!
this.emit (':responseReady');
};
});
//Handler for sending message
handlers.SendMessageIntent = function () {
let intent = this.event.request.intent;
console.log ('Dialog state : ' + this.event.request.dialogState);
console.log (intent);
//STARTED, IN_PROGRESS
if (!intent.slots.Name.value) {
//Name not defined yet, ask user for name
const slotToElicit = 'Name';
const speechOutput = 'What is your name';
const repromptSpeech = speechOutput;
this.emit (
':elicitSlot',
slotToElicit,
speechOutput,
repromptSpeech
);
} else if (!intent.slots.Email.value) {
//Name not defined yet, ask user for email
const slotToElicit = 'Email';
const speechOutput =
'Ok ' + intent.slots.Name.value + '. What is your email';
const repromptSpeech = speechOutput;
this.emit (
':elicitSlot',
slotToElicit,
speechOutput,
repromptSpeech
);
} else if (!intent.slots.Message.value) {
intent.slots.Email.value = emailHelper.transformEmailFromAlexaResponse (
intent.slots.Email.value
);
if (!emailHelper.isEmailValid (intent.slots.Email.value)) {
//Email is not valid, ask again
const slotToElicit = 'Email';
const speechOutput =
'Sorry, that was not valid email. What is your email';
const repromptSpeech = speechOutput;
this.emit (
':elicitSlot',
slotToElicit,
speechOutput,
repromptSpeech
);
} else {
//Email is valid
const slotToElicit = 'Message';
const speechOutput = 'Great. What is your message';
const repromptSpeech = speechOutput;
this.emit (
':elicitSlot',
slotToElicit,
speechOutput,
repromptSpeech
);
}
} else {
//all slots are filled
console.log ('Name : ' + intent.slots.Name.value);
console.log ('Email : ' + intent.slots.Email.value);
console.log ('Message : ' + intent.slots.Message.value);
emailHelper
.sendEmal (
intent.slots.Name.value,
intent.slots.Email.value,
intent.slots.Message.value,
destinationEmail
)
.then (info => {
console.log (info);
this.response.speak (
'Ok. Message sent. Someone will contact you ASAP'
);
this.emit (':responseReady');
})
.catch (error => {
console.log (error);
this.response.speak (
'Sorry, there was a problem with sending message.'
);
this.emit (':responseReady');
});
}
};
//Default handlers for unknown questions and session close
handlers.Unhandled = function () {
this.response
.speak (constants.voiceResponseStrings.QUESTION_NOT_FOUND)
.listen (constants.voiceResponseStrings.GENERIC_CONTINUE);
};
handlers.SessionEndedRequest = function () {
//We don't care for now
};
})
.catch (e => {
//Something is wrong, skill is not ready, use catch-all intent to inform user
console.log ('Error. Skill doesnt exist');
});
},
};

View File

@@ -4,12 +4,13 @@
"description": "", "description": "",
"main": "test.js", "main": "test.js",
"dependencies": { "dependencies": {
"alexa-app": "4.2.0", "alexa-sdk": "^1.0.25",
"body-parser": "^1.13.1", "body-parser": "^1.13.1",
"ejs": "^2.5.7", "ejs": "^2.5.7",
"express": "^4.13.0", "express": "^4.13.0",
"isomorphic-fetch": "^2.2.1", "isomorphic-fetch": "^2.2.1",
"mongodb": "^2.2.33", "mongodb": "^2.2.33",
"nodemailer": "^4.4.1",
"request": "^2.83.0" "request": "^2.83.0"
}, },
"author": "Matt Kruse <github@mattkruse.com> (http://mattkruse.com/)", "author": "Matt Kruse <github@mattkruse.com> (http://mattkruse.com/)",

View File

@@ -1,11 +1,7 @@
var amazonHelper = require ('./helpers/amazon');
var databaseHelper = require ('./helpers/database'); var databaseHelper = require ('./helpers/database');
const config = require ('./config/config'); const config = require ('./config/config');
const constants = require ('./config/constants');
require ('isomorphic-fetch');
var express = require ('express'); var express = require ('express');
var alexa = require('./components/alexa'); var alexa = require ('./models/alexa');
var MongoClient = require ('mongodb').MongoClient; var MongoClient = require ('mongodb').MongoClient;
var ObjectID = require ('mongodb').ObjectID; var ObjectID = require ('mongodb').ObjectID;
@@ -13,10 +9,7 @@ var ObjectID = require ('mongodb').ObjectID;
const router = express.Router (); const router = express.Router ();
var app = express (); var app = express ();
// ALWAYS setup the alexa app and attach it to express before anything else. app.set ('view engine', 'ejs'); // Should be removed
alexa.init (app);
app.set ('view engine', 'ejs');
app.use (require ('./middleware')); //common middleware for all requests app.use (require ('./middleware')); //common middleware for all requests
app.use (require ('./controllers')); //all routes app.use (require ('./controllers')); //all routes
@@ -26,7 +19,7 @@ MongoClient.connect (config.DB_URL)
app.listen (config.PORT, () => { app.listen (config.PORT, () => {
console.log ('Express server running on port ' + config.PORT); console.log ('Express server running on port ' + config.PORT);
alexa.updateIntentsJSON (); alexa.updateModel ();
databaseHelper.loadTokens (); databaseHelper.loadTokens ();
}); });
}) })

View File

@@ -1,4 +1,4 @@
import React, { Component } from 'react'; import React, {Component} from 'react';
import './css/App.css'; import './css/App.css';
import './css/popup.css'; import './css/popup.css';
import IntentList from './components/IntentList'; import IntentList from './components/IntentList';
@@ -6,90 +6,117 @@ import IntentDetails from './components/IntentDetails';
import LaunchRequest from './components/LaunchRequest'; import LaunchRequest from './components/LaunchRequest';
import Contact from './components/Contact'; import Contact from './components/Contact';
import Popup from 'react-popup'; import Popup from 'react-popup';
import {getSkill, updateSkill} from './lib/api' import {getSkill, updateSkill} from './lib/api';
import { import {
NEW_INTENT_SELECTED_INDEX, NEW_INTENT_SELECTED_INDEX,
LAUNCH_REQUEST_SELECTED_INDEX, LAUNCH_REQUEST_SELECTED_INDEX,
CONTACT_SELECTED_INDEX, CONTACT_SELECTED_INDEX,
RESULT_CODES} from './config/constants' RESULT_CODES,
} from './config/constants';
class App extends Component { class App extends Component {
constructor (props) {
super (props);
constructor(props){ this.state = {
super(props); _id: '5a232fb86ce046c749739455',
skillID: '',
skillName: '',
invocationName: 'Saburly',
invocationAnswer: 'We are saburly',
allIntents: [],
selectedIntent: {
intentName: '',
intentExplanation: '',
questions: [''],
answer: '',
},
selectedIndex: NEW_INTENT_SELECTED_INDEX,
contactEmail: '',
waiting: false,
};
this.state={_id:'5a232fb86ce046c749739455', getSkill (this.state._id).then (l => l.json ()).then (result => {
skillID:'', if (result === undefined) return;
skillName:'', this.setState ({
invocationName:'Saburly', skillID: result.skillID,
invocationAnswer:'We are saburly', skillName: result.skillName,
allIntents:[], invocationName: result.invocationName,
selectedIntent: {intentName:'',questions:[''],answer:''}, invocationAnswer: result.invocationAnswer,
selectedIndex:NEW_INTENT_SELECTED_INDEX, allIntents: result.intents,
contactEmail:'', contactEmail: result.contactEmail,
waiting: false });
}; });
getSkill(this.state._id).then(l=>l.json()).then(result=>{ this.handleIntentClick = this.handleIntentClick.bind (this);
if (result===undefined) return; this.handleLaunchRequestClick = this.handleLaunchRequestClick.bind (this);
this.setState({ skillID:result.skillID,skillName:result.skillName, invocationName: result.invocationName, this.handleDeleteIntentClick = this.handleDeleteIntentClick.bind (this);
invocationAnswer: result.invocationAnswer, this.handleSaveIntentClick = this.handleSaveIntentClick.bind (this);
allIntents: result.intents, contactEmail: result.contactEmail}) this.handleAddIntentClick = this.handleAddIntentClick.bind (this);
}) this.handleSaveLaunchRequestClick = this.handleSaveLaunchRequestClick.bind (
this
this.handleIntentClick = this.handleIntentClick.bind(this); );
this.handleLaunchRequestClick = this.handleLaunchRequestClick.bind(this); this.createSkill = this.createSkill.bind (this);
this.handleDeleteIntentClick = this.handleDeleteIntentClick.bind(this); this.sendSkill = this.sendSkill.bind (this);
this.handleSaveIntentClick = this.handleSaveIntentClick.bind(this); this.handleContactClick = this.handleContactClick.bind (this);
this.handleAddIntentClick = this.handleAddIntentClick.bind(this); this.handleSaveEmailClick = this.handleSaveEmailClick.bind (this);
this.handleSaveLaunchRequestClick = this.handleSaveLaunchRequestClick.bind(this);
this.createSkill = this.createSkill.bind(this);
this.sendSkill = this.sendSkill.bind(this);
this.handleContactClick = this.handleContactClick.bind(this);
this.handleSaveEmailClick = this.handleSaveEmailClick.bind(this);
} }
render() { render () {
let rightPanel; let rightPanel;
switch (this.state.selectedIndex) { switch (this.state.selectedIndex) {
case LAUNCH_REQUEST_SELECTED_INDEX: case LAUNCH_REQUEST_SELECTED_INDEX:
rightPanel = <LaunchRequest invocationName={this.state.invocationName} rightPanel = (
invocationAnswer={this.state.invocationAnswer} <LaunchRequest
onSaveClick={this.handleSaveLaunchRequestClick} invocationName={this.state.invocationName}
waiting={this.state.waiting}/> ; invocationAnswer={this.state.invocationAnswer}
onSaveClick={this.handleSaveLaunchRequestClick}
waiting={this.state.waiting}
/>
);
break; break;
case CONTACT_SELECTED_INDEX: case CONTACT_SELECTED_INDEX:
rightPanel = <Contact contactEmail={this.state.contactEmail} rightPanel = (
onSaveEmailClick={this.handleSaveEmailClick} <Contact
waiting={this.state.waiting}/> ; contactEmail={this.state.contactEmail}
onSaveEmailClick={this.handleSaveEmailClick}
waiting={this.state.waiting}
/>
);
break; break;
default: default:
rightPanel = <IntentDetails selectedIntent={this.state.selectedIntent} rightPanel = (
onDeleteIntentClick={this.handleDeleteIntentClick} <IntentDetails
onSaveIntentClick={this.handleSaveIntentClick} selectedIntent={this.state.selectedIntent}
waiting={this.state.waiting}/>; onDeleteIntentClick={this.handleDeleteIntentClick}
onSaveIntentClick={this.handleSaveIntentClick}
waiting={this.state.waiting}
/>
);
} }
return( return (
<div className="App"> <div className="App">
<Popup/> <Popup />
<div className="App-header"> <div className="App-header">
<h1> Tell All </h1> <h1> Tell All </h1>
</div> </div>
<IntentList allIntents={this.state.allIntents} <IntentList
onLaunchRequestClick={this.handleLaunchRequestClick} allIntents={this.state.allIntents}
onContactClick={this.handleContactClick} onLaunchRequestClick={this.handleLaunchRequestClick}
onIntentClick={this.handleIntentClick} onContactClick={this.handleContactClick}
onAddIntentClick={this.handleAddIntentClick} onIntentClick={this.handleIntentClick}
selectedIndex={this.state.selectedIndex} onAddIntentClick={this.handleAddIntentClick}
waiting={this.state.waiting}/> selectedIndex={this.state.selectedIndex}
waiting={this.state.waiting}
/>
{rightPanel} {rightPanel}
</div> </div>
); );
} }
createSkill(intents, name, answer, email, updateOnAmazon){ createSkill (intents, name, answer, email, updateOnAmazon) {
return { return {
_id: this.state._id, _id: this.state._id,
skillID: this.state.skillID, skillID: this.state.skillID,
@@ -97,97 +124,181 @@ class App extends Component {
invocationName: name, invocationName: name,
invocationAnswer: answer, invocationAnswer: answer,
contactEmail: email, contactEmail: email,
updateOnAmazon: updateOnAmazon updateOnAmazon: updateOnAmazon,
}; };
} }
handleIntentClick(selectedIntent, index){ handleIntentClick (selectedIntent, index) {
this.setState({selectedIntent:selectedIntent, selectedIndex: index, launchRequest:false}); this.setState ({
selectedIntent: selectedIntent,
selectedIndex: index,
launchRequest: false,
});
} }
handleLaunchRequestClick(){ handleLaunchRequestClick () {
this.setState({selectedIndex: LAUNCH_REQUEST_SELECTED_INDEX}); this.setState ({selectedIndex: LAUNCH_REQUEST_SELECTED_INDEX});
} }
handleContactClick(){ handleContactClick () {
this.setState({selectedIndex: CONTACT_SELECTED_INDEX}) this.setState ({selectedIndex: CONTACT_SELECTED_INDEX});
} }
handleSaveLaunchRequestClick(name, answer){ handleSaveLaunchRequestClick (name, answer) {
this.setState({waiting:true, invocationName:name, invocationAnswer: answer}); this.setState ({
this.sendSkill(this.state.allIntents,true,{waiting:false},{waiting:false},name,answer,this.state.contactEmail,true); waiting: true,
invocationName: name,
invocationAnswer: answer,
});
this.sendSkill (
this.state.allIntents,
true,
{waiting: false},
{waiting: false},
name,
answer,
this.state.contactEmail,
true
);
} }
handleSaveEmailClick(email){ handleSaveEmailClick (email) {
this.setState({waiting:true}); this.setState ({waiting: true});
this.sendSkill(this.state.allIntents,true,{contactEmail: email, waiting:false},{waiting:false},this.state.invocationName,this.state.invocationAnswer,email,false); this.sendSkill (
this.state.allIntents,
true,
{contactEmail: email, waiting: false},
{waiting: false},
this.state.invocationName,
this.state.invocationAnswer,
email,
false
);
} }
handleDeleteIntentClick(selectedIntent){ handleDeleteIntentClick (selectedIntent) {
let id = -1; let id = -1;
//TODO : Change comparsion method ! Same object with different proeprty sorting will not be same string //TODO : Change comparsion method ! Same object with different proeprty sorting will not be same string
this.state.allIntents.map((intent,index)=>{ this.state.allIntents.map ((intent, index) => {
if ((id===-1) && (JSON.stringify(selectedIntent)===JSON.stringify(intent))) if (
id = index; id === -1 &&
JSON.stringify (selectedIntent) === JSON.stringify (intent)
)
id = index;
}); });
if (id!==-1){ if (id !== -1) {
try{ try {
let newAllIntentsJSON = JSON.stringify(this.state.allIntents); let newAllIntentsJSON = JSON.stringify (this.state.allIntents);
let newAllIntents = JSON.parse(newAllIntentsJSON); let newAllIntents = JSON.parse (newAllIntentsJSON);
newAllIntents.splice(id,1); newAllIntents.splice (id, 1);
this.setState({waiting:true}); this.setState ({waiting: true});
let newState = {allIntents: newAllIntents, selectedIntent: {intentName:'', questions:[''],answer:''}, waiting:false}; let newState = {
this.sendSkill(newAllIntents,true,newState,{waiting:false},this.state.invocationName,this.state.invocationAnswer,this.state.contactEmail,true); allIntents: newAllIntents,
selectedIntent: {intentName: '', questions: [''], answer: ''},
}catch(e){ waiting: false,
console.log("error : " + e); };
this.sendSkill (
newAllIntents,
true,
newState,
{waiting: false},
this.state.invocationName,
this.state.invocationAnswer,
this.state.contactEmail,
true
);
} catch (e) {
console.log ('error : ' + e);
} }
} }
} }
handleSaveIntentClick (selectedIntent) {
handleSaveIntentClick(selectedIntent){ let newAllIntentsJSON = JSON.stringify (this.state.allIntents);
let newAllIntentsJSON = JSON.stringify(this.state.allIntents); let newAllIntents = JSON.parse (newAllIntentsJSON);
let newAllIntents = JSON.parse(newAllIntentsJSON);
let newState = null; let newState = null;
if (this.state.selectedIndex === NEW_INTENT_SELECTED_INDEX){ if (this.state.selectedIndex === NEW_INTENT_SELECTED_INDEX) {
//new intent //new intent
newAllIntents.push(selectedIntent); newAllIntents.push (selectedIntent);
newState = {allIntents: newAllIntents, selectedIntent: selectedIntent, selectedIndex: newAllIntents.length-1, waiting:false}; newState = {
}else{ allIntents: newAllIntents,
selectedIntent: selectedIntent,
selectedIndex: newAllIntents.length - 1,
waiting: false,
};
} else {
newAllIntents[this.state.selectedIndex] = selectedIntent; newAllIntents[this.state.selectedIndex] = selectedIntent;
newState = {allIntents: newAllIntents, selectedIntent: selectedIntent, waiting: false}; newState = {
allIntents: newAllIntents,
selectedIntent: selectedIntent,
waiting: false,
};
} }
this.setState({waiting:true}); this.setState ({waiting: true});
this.sendSkill(newAllIntents, true, newState, {waiting:false}, this.state.invocationName,this.state.invocationAnswer,this.state.contactEmail, true); this.sendSkill (
newAllIntents,
true,
newState,
{waiting: false},
this.state.invocationName,
this.state.invocationAnswer,
this.state.contactEmail,
true
);
} }
handleAddIntentClick(){ handleAddIntentClick () {
this.setState({allIntents: this.state.allIntents, selectedIndex: NEW_INTENT_SELECTED_INDEX,launchRequest:false,selectedIntent: {intentName:'',questions:[''], answer:''}}); this.setState ({
allIntents: this.state.allIntents,
selectedIndex: NEW_INTENT_SELECTED_INDEX,
launchRequest: false,
selectedIntent: {intentName: '', questions: [''], answer: '', intentExplanation:''},
});
} }
sendSkill(newAllIntents, showPopUp, resolveState, rejectState, newName, newAnswer, email, updateOnAmazon){ sendSkill (
return new Promise((resolve,reject)=>{ newAllIntents,
updateSkill(this.createSkill(newAllIntents,newName,newAnswer,email,updateOnAmazon)).then(l=>l.json()).then(result=>{ showPopUp,
if (result.result !== RESULT_CODES.OK){ resolveState,
console.log(result.result); rejectState,
if (showPopUp) Popup.alert('Model was not saved. Please try again'); newName,
this.setState(rejectState); newAnswer,
//reject('Error code : ' + jResult.result); email,
}else{ updateOnAmazon
if (showPopUp) Popup.alert('Saved'); ) {
this.setState(resolveState); return new Promise ((resolve, reject) => {
resolve(); updateSkill (
} this.createSkill (
}).catch(e=>{ newAllIntents,
console.log('error : ' + e); newName,
if (showPopUp) Popup.alert('Model was not saved. Please try again'); newAnswer,
this.setState(rejectState); email,
//reject(e); updateOnAmazon
}); )
)
.then (l => l.json ())
.then (result => {
if (result.result !== RESULT_CODES.OK) {
console.log (result);
if (showPopUp)
Popup.alert ('Model was not saved. Please try again');
this.setState (rejectState);
//reject('Error code : ' + jResult.result);
} else {
if (showPopUp) Popup.alert ('Saved');
this.setState (resolveState);
resolve ();
}
})
.catch (e => {
console.log ('error : ' + e);
if (showPopUp) Popup.alert ('Model was not saved. Please try again');
this.setState (rejectState);
//reject(e);
});
}); });
} }
} }

View File

@@ -1,7 +1,8 @@
import React, { Component } from 'react'; import React, { Component } from 'react';
import {Button, SVGIcon, TextField} from 'react-md'; import {Button, SVGIcon, TextField} from 'react-md';
import '../css/components/IntentDetails.css'; import '../css/components/IntentDetails.css';
import {QUESTION_MAX_LENGTH, ANSWER_MAX_LENGTH, INTENT_NAME_MAX_LENGTH} from '../config/constants'; import '../css/Common.css';
import {QUESTION_MAX_LENGTH, ANSWER_MAX_LENGTH, INTENT_NAME_MAX_LENGTH, INTENT_EXPLANATION_MAX_LENGTH} from '../config/constants';
class IntentDetails extends Component { class IntentDetails extends Component {
constructor(props){ constructor(props){
@@ -14,6 +15,7 @@ class IntentDetails extends Component {
this.handleQuestionEdit = this.handleQuestionEdit.bind(this); this.handleQuestionEdit = this.handleQuestionEdit.bind(this);
this.handleAnswerEdit = this.handleAnswerEdit.bind(this); this.handleAnswerEdit = this.handleAnswerEdit.bind(this);
this.handleIntentNameEdit = this.handleIntentNameEdit.bind(this); this.handleIntentNameEdit = this.handleIntentNameEdit.bind(this);
this.handleIntentExplanationEdit = this.handleIntentExplanationEdit.bind(this);
} }
componentWillReceiveProps(props){ componentWillReceiveProps(props){
@@ -24,10 +26,19 @@ class IntentDetails extends Component {
return ( return (
<div className="RightPanelBox"> <div className="RightPanelBox">
<div className="QuestionBox"> <div className="QuestionBox">
<h5 className="PanelSubTitle"> In introduction, Alexa will help users to ask her the right questions about your business. For Example, she will say : "To ask us about our services, say : What do you do ? ". What do you do ? is defined in question field. Alexa will use first variation of question in intro.</h5>
<TextField
id="intent explanation"
lineDirection="center"
placeholder="To ask us about our services, say "
className="md-cell md-cell--bottom IntentDetailsInputBoxes"
onChange={this.handleIntentExplanationEdit}
maxLength={INTENT_EXPLANATION_MAX_LENGTH}
value={this.state.intent.intentExplanation} />
<br/>
<TextField <TextField
id="intent name" id="intent name"
lineDirection="center" lineDirection="center"
placeholder="Intent name"
label="Question name" label="Question name"
className="md-cell md-cell--bottom IntentDetailsInputBoxes" className="md-cell md-cell--bottom IntentDetailsInputBoxes"
onChange={this.handleIntentNameEdit} onChange={this.handleIntentNameEdit}
@@ -98,6 +109,13 @@ class IntentDetails extends Component {
this.setState({intent: newIntent}); this.setState({intent: newIntent});
} }
handleIntentExplanationEdit(e,index){
if (e.length === INTENT_EXPLANATION_MAX_LENGTH) return;
let newIntent = this.state.intent;
newIntent.intentExplanation = e;
this.setState({intent: newIntent});
}
handleAnswerEdit(e){ handleAnswerEdit(e){
if (e.length === ANSWER_MAX_LENGTH) return; if (e.length === ANSWER_MAX_LENGTH) return;
let newIntent = this.state.intent; let newIntent = this.state.intent;

View File

@@ -1,4 +1,5 @@
export const INTENT_NAME_MAX_LENGTH = 30; export const INTENT_NAME_MAX_LENGTH = 30;
export const INTENT_EXPLANATION_MAX_LENGTH = 70;
export const QUESTION_MAX_LENGTH = 150; export const QUESTION_MAX_LENGTH = 150;
export const ANSWER_MAX_LENGTH = 150; export const ANSWER_MAX_LENGTH = 150;