Alexa conversational skill Error - amazon-web-services

I'm creating a skill in Alexa that does the following.
User : Hi
Alexa, hello please give me your name
User : John
Alexa : Hi John, good to meet you. How old are you
User : 25
Below are my intents
{
"intents": [
{
"intent": "StartTheFlow",
"slots": [
{
"name": "custName",
"type": "list_of_userNames"
},
{
"name": "age",
"type": "AMAZON.NUMBER"
}
]
},
{
"intent": "AMAZON.HelpIntent"
},{
"intent": "Welcome"
},
{
"intent": "AMAZON.StopIntent"
},
{
"intent": "AMAZON.CancelIntent"
}
]
}
And below are my utterances
StartTheFlow Hi
StartTheFlow {custName}
StartTheFlow {age}
Below is my onIntent()
#Override
public SpeechletResponse onIntent(final IntentRequest request, final Session session) throws SpeechletException {
log.info("onIntent requestId={}, sessionId={}", request.getRequestId(), session.getSessionId());
Intent intent = request.getIntent();
String intentName = (intent != null) ? intent.getName() : null;
if ("StartTheFlow".equals(intentName)) {
return getTheFlow(intent, session);
} else if ("AMAZON.HelpIntent".equals(intentName)) {
return getHelpResponse();
} else if ("WelcomeChubb".equals(intentName)) {
return getWelcomeResponse();
} else {
throw new SpeechletException("Invalid Intent");
}
}
And I'm trying to handle this as below
private SpeechletResponse getTheFlow(Intent intent, Session session) {
boolean isAskResponse = true;
String responseText = "";
String nameFromSession = (String) session.getAttribute("name");
if (StringUtils.isNullOrEmpty(nameFromSession)) {
responseText = "please give me your name";
getTheNameText(intent, session);
} else {
System.out.println(session.getAttribute("nameFromSession"));
responseText = "please give me your date of birth";
}
return getSpeechletResponse(responseText, "", isAskResponse);
}
private String getTheNameText(Intent intent, Session session) {
String userNameFrmIntent = getNameFromSlot(intent).toString();
session.setAttribute("nameFromSession", userNameFrmIntent);
return getNameFromSlot(intent).toString();
}
private String getNameFromSlot(Intent intent) {
Slot userName = intent.getSlot(Slot_Name);
return userName.getValue();
}
Also, I've defined a slot in the top as below.
private static final String Slot_Name = "custName";
But here when I type Hi, Instead of asking me my name, it is giving me an error in logs it shows Java NullPointer Exception. the response that I get when I type Hi is as below.
{
"session": {
"sessionId": "SessionId.a2740ca4-73ff-4a15-856d-6461b3c7b2e1",
"application": {
"applicationId": "amzn1.ask.skill.e3dfb30e-0089-423c-a325-30ad28dd2e2b"
},
"attributes": {},
"user": {
"userId": "amzn1.ask.account.AEQYTT5HFHEGGDSUCT3NW45HKR7O3FBL5YCBSZIS7P5LNP5BXFEMUR7AUYOZVKC2FT5V6RKJC7RNA5VMZVREBAXAQP3NFNTQSFSSKSEXIYT4FQYMS5JCI2CCAOPUF4FN4C6DHEU6ONNY3D6GN5AWK75KOQNJH2IWROIIXTPNXSNI6FLQYRBBMP7TRSOWVNCY73WJUT2VLHDACWA"
},
"new": true
},
"request": {
"type": "IntentRequest",
"requestId": "EdwRequestId.cf686fc0-cbfd-4496-bb09-c41714563507",
"locale": "en-US",
"timestamp": "2017-02-15T20:12:44Z",
"intent": {
"name": "StartTheFlow",
"slots": {
"custName": {
"name": "custName",
"value": "hi"
}
}
}
},
"version": "1.0"
}
Can someone please let me know where am I going wrong and how can I fix this, I've quite a number of questions to be linked, like 25, can Someone please let me know if there is a better way to do this in java.
Thanks

I would recommend creating a separate intent for each thing that the user says. So for example, HelloIntent, NameIntent, and AgeIntent.
Then be sure to pass those bits of information forward to all following intents in the session. So each intent could use a common function at the beginning to read each string from the session (if exists), add the new slot data to it, and then write all the strings back to the response session before finishing.
Since you'll then have separate intents, and the user could conceivably say them out of order, you may want to check that all the needed strings have been entered, or else prompt the user for any missing strings.
The problem with saving data in the session is that the data will be gone the next time the user starts the skill. To resolve this, you could use a database to hold the users data, saving it keyed to the userId. There are lots of examples on how to do that. Be careful that some databases are essentially free, but others will charge you depending on how many times it is used each month.

Related

Secondary Index not working for Database using #key

I should get the DynamoDb id for Justin. The call doesn't seem to fail. If i console.log(returned) i get an [object Object]. When i try to get to the returned.data.getIdFromUserName.id or returned.data.getIdFromUserName.email (anything else in the table) i get undefined. What am i missing?
Returned data:
{
"data": {
"getIdFromUserName": {
"items": [
{
"id": "3a5a2ks4-f137-41e2-a604-594e0c52a298",
"userName": "Justin",
"firstname": "null",
"weblink": "#JustinTimberlake",
"email": "iuiubiwewe#hotmail.com",
"mobileNum": "+0123456789",
"profilePicURI": "null",
"listOfVideosSeen": null,
"userDescription": "I wanna rock your body, please stay",
"isBlocked": false,
"GridPairs": null
}
],
"nextToken": null
}
}
}
I'd suggest getting a better idea of what console.log(returned) is printing.
Try console.log(JSON.stringify(returned, null, 2)) to inspect what is being returned.
EDIT: The data you're working with looks like this:
{
"data": {
"getIdFromUserName": {
"items": [
{
"id": "3a5a2ks4-f137-41e2-a604-594e0c52a298",
"userName": "Justin",
"firstname": "null",
"weblink": "#JustinTimberlake",
"email": "iuiubiwewe#hotmail.com",
"mobileNum": "+0123456789",
"profilePicURI": "null",
"listOfVideosSeen": null,
"userDescription": "I wanna rock your body, please stay",
"isBlocked": false,
"GridPairs": null
}
],
"nextToken": null
}
}
}
Pay close attention to the structure of that response. Both data and getIdFromUserName are maps. The content of data.getIdFromUserName is an array named items. Therefore, data.getIdFromUserName.items is an array containing the results of your query. You'll need to iterate over that array to get the data you are looking for.
For example, data.getIdFromUserName.items[0].id would be 3a5a2ks4-f137-41e2-a604-594e0c52a298
To access the email it would be data.getIdFromUserName.items[0].email.

Azure Cosmos query to convert into List

This is my JSON data, which is stored into cosmos db
{
"id": "e064a694-8e1e-4660-a3ef-6b894e9414f7",
"Name": "Name",
"keyData": {
"Keys": [
"Government",
"Training",
"support"
]
}
}
Now I want to write a query to eliminate the keyData and get only the Keys (like below)
{
"userid": "e064a694-8e1e-4660-a3ef-6b894e9414f7",
"Name": "Name",
"Keys" :[
"Government",
"Training",
"support"
]
}
So far I tried the query like
SELECT c.id,k.Keys FROM c
JOIN k in c.keyPhraseBatchResult
Which is not working.
Update 1:
After trying with the Sajeetharan now I can able to get the result, but the issue it producing another JSON inside the Array.
Like
{
"id": "ee885fdc-9951-40e2-b1e7-8564003cd554",
"keys": [
{
"serving": "Government"
},
{
"serving": "Training"
},
{
"serving": "support"
}
]
}
Is there is any way that extracts only the Array without having key value pari again?
{
"userid": "e064a694-8e1e-4660-a3ef-6b894e9414f7",
"Name": "Name",
"Keys" :[
"Government",
"Training",
"support"
]
}
You could try this one,
SELECT C.id, ARRAY(SELECT VALUE serving FROM serving IN C.keyData.Keys) AS Keys FROM C
Please use cosmos db stored procedure to implement your desired format based on the #Sajeetharan's sql.
function sample() {
var collection = getContext().getCollection();
var isAccepted = collection.queryDocuments(
collection.getSelfLink(),
'SELECT C.id,ARRAY(SELECT serving FROM serving IN C.keyData.Keys) AS keys FROM C',
function (err, feed, options) {
if (err) throw err;
if (!feed || !feed.length) {
var response = getContext().getResponse();
response.setBody('no docs found');
}
else {
var response = getContext().getResponse();
var map = {};
for(var i=0;i<feed.length;i++){
var keyArray = feed[i].keys;
var array = [];
for(var j=0;j<keyArray.length;j++){
array.push(keyArray[j].serving)
}
feed[i].keys = array;
}
response.setBody(feed);
}
});
if (!isAccepted) throw new Error('The query was not accepted by the server.');
}
Output:

How to add the multiple payment profiles while adding the single customer?

Using sandbox key and transaction id when I'm creating the user using json flavour. This api will response me the customerProfileId and customerPaymentProfileIdList in the list there is one id. Can we create it multiples? if yes, Then what is the json string I have to send to generate multiple customerPaymentProfileIds. If no, Then please expalin why I'm not sending the array to the api. Or how to create the multiple payment profiles using authrization.net.
Now I'm sending this json:-
{
"createCustomerProfileRequest": {
"merchantAuthentication": {
"name": "name",
"transactionKey": "transaction_key"
},
"profile": {
"merchantCustomerId": "This is a+fdstring",
"description": "This is a description.",
"email": "RuldaRam#gmail.com",
"paymentProfiles": {
"customerType": "individual",
"billTo":{
"firstName":"Puneet",
"lastName":"Jindal",
"address":"Mohali",
"city":"Banglore",
"state":"Delhi",
"zip":"10001"
},
"payment": {
"creditCard": {
"cardNumber": "4111111111111111",
"expirationDate": "2020-12",
"cardCode":"123"
}
}
}
},
"validationMode": "testMode"
}
}
Developer link
I also tried to do it like this

How do I insert an optional field as null using AppSync Resolvers and Aurora?

I have an optional String field, notes, that is sometimes empty. If it's empty I want to insert null, otherwise I want to insert the string.
Here is my resolver -
{
"version" : "2017-02-28",
"operation": "Invoke",
#set($id = $util.autoId())
#set($notes = $util.defaultIfNullOrEmpty($context.arguments.notes, 'null'))
"payload": {
"sql":"INSERT INTO things VALUES ('$id', :NOTES)",
"variableMapping": {
":NOTES" : $notes
},
"responseSQL": "SELECT * FROM things WHERE id = '$id'"
}
}
With this graphql
mutation CreateThing{
createThing() {
id
notes
}
}
I get -
{
"data": {
"createRoll": {
"id": "6af68989-0bdc-44e2-8558-aeb4c8418e93",
"notes": "null"
}
}
}
when I really want null without the quotes.
And with this graphql -
mutation CreateThing{
createThing(notes: "Here are some notes") {
id
notes
}
}
I get -
{
"data": {
"createThing": {
"id": "6af68989-0bdc-44e2-8558-aeb4c8418e93",
"notes": "Here are some notes"
}
}
}
which is what I want.
How do I get a quoteless null and a quoted string into the same field?
TL;DR you should use $util.toJson() to print the $context.arguments.notes correctly. Replace your $notes assignment with
#set($notes = $util.toJson($util.defaultIfNullOrEmpty($context.arguments.notes, null)))
Explanation:
The reason is VTL prints whatever the toString() method returns and your call to
$util.defaultIfNullOrEmpty($context.arguments.notes, 'null') will return the string "null", which will be printed as "null".
If you replace with $util.defaultIfNullOrEmpty($context.arguments.notes, null) then it will return a null string. However, VTL will print $notes because that is the way it handles null references. In order to print null, which is the valid JSON representation of null, we have to serialize it to JSON. So the correct statement is:
#set($notes = $util.toJson($util.defaultIfNullOrEmpty($context.arguments.notes, null)))
Full test:
I'm assuming you started with the RDS sample provided in the AWS AppSync console and modified it. To reproduce, I updated the content field in the Schema to be nullable:
type Mutation {
...
createPost(author: String!, content: String): Post
...
}
type Post {
id: ID!
author: String!
content: String
views: Int
comments: [Comment]
}
and I modified the posts table schema so content can also be null there: (inside the Lambda function)
function conditionallyCreatePostsTable(connection) {
const createTableSQL = `CREATE TABLE IF NOT EXISTS posts (
id VARCHAR(64) NOT NULL,
author VARCHAR(64) NOT NULL,
content VARCHAR(2048),
views INT NOT NULL,
PRIMARY KEY(id))`;
return executeSQL(connection, createTableSQL);
}
This is the request template for the createPost mutation:
{
"version" : "2017-02-28",
"operation": "Invoke",
#set($id = $util.autoId())
"payload": {
"sql":"INSERT INTO posts VALUES ('$id', :AUTHOR, :CONTENT, 1)",
"variableMapping": {
":AUTHOR" : "$context.arguments.author",
":CONTENT" : $util.toJson($util.defaultIfNullOrEmpty($context.arguments.content, null))
},
"responseSQL": "SELECT id, author, content, views FROM posts WHERE id = '$id'"
}
}
and response template:
$util.toJson($context.result[0])
The following query:
mutation CreatePost {
createPost(author: "Me") {
id
author
content
views
}
}
returns:
{
"data": {
"createPost": {
"id": "b42ee08c-956d-4b89-afda-60fe231e86d7",
"author": "Me",
"content": null,
"views": 1
}
}
}
and
mutation CreatePost {
createPost(author: "Me", content: "content") {
id
author
content
views
}
}
returns
{
"data": {
"createPost": {
"id": "c6af0cbf-cf05-4110-8bc2-833bf9fca9f5",
"author": "Me",
"content": "content",
"views": 1
}
}
}
We were looking into the same issue. For some reason, the accepted answer does not work for us. Maybe because it's a beta feature and there is a new resolver version (2018-05-29 vs 2017-02-28, changes here: Resolver Mapping Template Changelog).
We use this for the time being using NULLIF():
{
"version": "2018-05-29",
"statements": [
"INSERT INTO sales_customers_addresses (`id`, `customerid`, `type`, `company`, `country`, `email`) VALUES (NULL, :CUSTOMERID, :TYPE, NULLIF(:COMPANY, ''), NULLIF(:COUNTRY, ''), :EMAIL)"
],
"variableMap": {
":CUSTOMERID": $customerid,
":TYPE": "$type",
":COMPANY": "$util.defaultIfNullOrEmpty($context.args.address.company, '')",
":COUNTRY": "$util.defaultIfNullOrEmpty($context.args.address.country, '')",
":EMAIL": "$context.args.address.email"
}
}

"type mismatch error, expected type LIST" for querying a one-to-many relationship in AppSync

The schema:
type User {
id: ID!
createdCurricula: [Curriculum]
}
type Curriculum {
id: ID!
title: String!
creator: User!
}
The resolver to query all curricula of a given user:
{
"version" : "2017-02-28",
"operation" : "Query",
"query" : {
## Provide a query expression. **
"expression": "userId = :userId",
"expressionValues" : {
":userId" : {
"S" : "${context.source.id}"
}
}
},
"index": "userIdIndex",
"limit": #if(${context.arguments.limit}) ${context.arguments.limit} #else 20 #end,
"nextToken": #if(${context.arguments.nextToken}) "${context.arguments.nextToken}" #else null #end
}
The response map:
{
"items": $util.toJson($context.result.items),
"nextToken": #if(${context.result.nextToken}) "${context.result.nextToken}" #else null #end
}
The query:
query {
getUser(id: "0b6af629-6009-4f4d-a52f-67aef7b42f43") {
id
createdCurricula {
title
}
}
}
The error:
{
"data": {
"getUser": {
"id": "0b6af629-6009-4f4d-a52f-67aef7b42f43",
"createdCurricula": null
}
},
"errors": [
{
"path": [
"getUser",
"createdCurricula"
],
"locations": null,
"message": "Can't resolve value (/getUser/createdCurricula) : type mismatch error, expected type LIST"
}
]
}
The CurriculumTable has a global secondary index titled userIdIndex, which has userId as the partition key.
If I change the response map to this:
$util.toJson($context.result.items)
The output is the following:
{
"data": {
"getUser": {
"id": "0b6af629-6009-4f4d-a52f-67aef7b42f43",
"createdCurricula": null
}
},
"errors": [
{
"path": [
"getUser",
"createdCurricula"
],
"errorType": "MappingTemplate",
"locations": [
{
"line": 4,
"column": 5
}
],
"message": "Unable to convert \n{\n [{\"id\":\"87897987\",\"title\":\"Test Curriculum\",\"userId\":\"0b6af629-6009-4f4d-a52f-67aef7b42f43\"}],\n} to class java.lang.Object."
}
]
}
If I take that string and run it through a console.log in my frontend app, I get:
{
[{"id":"2","userId":"0b6af629-6009-4f4d-a52f-67aef7b42f43"},{"id":"1","userId":"0b6af629-6009-4f4d-a52f-67aef7b42f43"}]
}
That's clearly an object. How do I make it... not an object, so that AppSync properly reads it as a list?
SOLUTION
My response map had a set of curly braces around it. I'm pretty sure that was placed there in the generator by Amazon. Removing them fixed it.
I think I'm not seeing the complete view of your schema, I was expecting something like:
schema {
query: Query
}
Where Query is RootQuery, in fact you didn't share us your Query definition. Assuming you have the right Query definition. The main problem is in your response template.
> "items": $util.toJson($context.result.items)
This means that you are passing a collection named: *"items"* to Graphql query engine. And you are referring this collection as "createdCurricula". So solve this issue your response-mapping-template is the right place to fix. How? just replace the above line with the following.
"createdCurricula": $util.toJson($context.result.items),
Please the main thing to note here is, the mapping template is a bridge between your datasources and qraphql, feel free to make any computation, or name mapping but don't forget that object names in that response json are the one should match in schema/query definition.
Thanks.
Musema
change to result type to $util.toJson($ctx.result.data.posts)
The exception msg says that it expected a type list.
Looking at:
{
[{"id":"2","userId":"0b6af629-6009-4f4d-a52f-67aef7b42f43"},{"id":"1","userId":"0b6af629-6009-4f4d-a52f-67aef7b42f43"}]
}
I don't see that createdCurricula is a LIST.
What is currently in DDB is:
"id": "0b6af629-6009-4f4d-a52f-67aef7b42f43",
"createdCurricula": null