Code Monkey home page Code Monkey logo

alexa-skills-kit-sdk-for-nodejs's People

Contributors

abhipwr avatar anthony-dallagnola avatar ask-sdk avatar bhardwz avatar breedloj avatar daltonhuynh avatar dependabot[bot] avatar doiron avatar hideokamoto avatar hig3 avatar hoegertn avatar joshbean avatar kakhaurigashvili avatar masachaco avatar nikhilym avatar panw avatar pbheemag avatar raeglan avatar rahulawl avatar roycodes avatar sattpat avatar shenchen93 avatar shreraju-amzn avatar shreyas-vgr avatar skokovic avatar sleepingtree avatar tianrenz avatar tiantxie avatar vyancharuk avatar xtiantia avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

alexa-skills-kit-sdk-for-nodejs's Issues

The unhandled intent is never called

The app calls one of the defined intents even if the input doesn't match any utterance.
This is a simple skill to replicate the issue.

index.js

var Alexa = require('alexa-sdk');

exports.handler = function(event, context, callback){
    var alexa = Alexa.handler(event, context);
    alexa.registerHandlers(handlers);
    alexa.execute();
};

var handlers = {
    'Amazon.LaunchIntent': function () {
        this.emit(':ask', 'Welcome!', 'Welcome!');
    },
    'TestIntent': function () {
        this.emit(':ask', 'Test intent', 'Test intent');
    },
    'Unhandled': function () {
        this.emit(':ask', 'I don\'t get it!', 'I don\'t get it!');
    },
}

Intent Schema

{
  "intents": [
    {
      "intent": "TestIntent"
    },
    {
      "intent": "AMAZON.StopIntent"
    },
    {
      "intent": "AMAZON.CancelIntent"
    },
    {
      "intent": "AMAZON.HelpIntent"
    }
  ]
}

Utterances
TestIntent test

A way to tell (not ask) without closing the session

It would make sense to have a way to tell the user something (as opposed to asking) without closing the session. There are situations when the session may contain useful contextual information that may be used by alexa in a further query, but that does not necessitate waiting for a response by default.

As an example use case:

  • alexa, ask taxi app to book me a taxi
  • I have booked you a taxi
  • alexa, ask taxi app when that taxi will arive
  • the taxi you booked will arrive in 10 minutes

I would be happy to create a pull request if a preferred approach can be identified - an alternate function with keyword (eg :tellWithSession)? another parameter to the ":tell" function?

Use Lambda callback parameter instead of context.fail context.succeed ?

I wondered, why I got no logs on CloudWatch for my alexa skill lambda function. Especially for the errors from my function.

As mentioned in the lambda documentation for nodejs handlers here: http://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-handler.html#nodejs-prog-model-handler-callback one should use the callback parameter to propagate the error to the CloudWatch logging.

At the moment the callback parameter is passed to the alexa handler function and saved into the _callback property, but it is never used. I think we should replace the _context.fail and _context.succeed function calls with the appropriate _callback calls.

Do you agree?
I will try to provide a PR for that, soon.

Best regards.

Ampersand (&) in Response Causes Error

Using an ampersand in a response causes an error:

this.emit(':tell', "Some amount of text with an & character");

Gives the following error when invoked via Lambda:

Invalid SSML Output Speech for requestId amzn1.echo-api.request.8ad916fa-2f18-44db-95df-25569d049500. Error: Fatal error occured when processing SSML content. This usually happens when the SSML is not well formed. Error: Unexpected character ' ' (code 32) (missing name?)\n at [row,col {unknown-source}]: [1,94]

Although the error message says it is a code 32 character (a space) that is the problem, the error disappears after replacing the & with and.

error using Alexa Nodejs SDK

Getting below error when testing an alexa hello world skill using nodejs sdk.

Can somebody point out what am I doing wrong

TypeError: Cannot read property 'locale' of undefined
at AlexaRequestEmitter.HandleLambdaEvent (/var/task/n

The offending line in SDK is

function HandleLambdaEvent() {
    this.locale = this._event.request.locale;

How to call a different intent with a slot value?

I understand that I can call a different intent handler using this.emit('OtherIntent'); inside the original handler. If the other intent handler expects a slot value, how can I call it with a specific value? I would expect something like this.emit('OtherIntentWithSlots', { 'slotName' : 'slotValue' });. Is this possible?

Question: how to run asynchronous call after speech response

I'm trying to run an asynchronous API call after Alexa has completed speaking / playing an audio file. I'm playing a 30 second mp3 file to provide feedback to the user. I'd like the asynchronous call to run after that audio file (or potential speech reply) is completed playing:

MyFancyIntent: function() {
  this.emit(':tell', '<audio src="https://s3.amazonaws.com/bucket/30secondsound.mp3" />')
  var self = this

  makeAPIRequest('doSomething') => {
   // end session, and ideally respond again:
   self.emit(':tell', 'All done')
  }
}

Right now the session ends after the emit. I'm guessing that maybe I could accomplish this with a custom function that doesn't end the session, replacing the first :tell? If that's correct, I'd very much appreciate some guidance on how to do so.

How make alexa give the user output then emit a new intent

Lets say I have the following code:

"NewSession": function() {
this.emit(":tell", "New session");
this.emitWithState("AMAZON.HelpIntent");
},

I'd like for Alexa to speak something to the user (in this case inform him about the start of a New Session) than automatically emit and event that will trigger a new intent (in this case HelpIntent). Is this possible with Alexa ? Is this possible using the SDK ?

I've seen no examples of how to do this but otherwise it seems pretty nonsensical to have an option to emit a new intent in the first place.

Python support

We use Python at my company and we wound up developing our own Framework. It would be nice to have your support.

Get the access token off of user after account linking

Is this possible? The account is linked through google currently in alexa-dev, not sure how to get the access token back now that my account is linked. There is an explanation for Java in the documentation, but not javascript.

Asynchronous actions not supported?

I'm calling out to an external REST API with the https module, and even wrapping the call in a Promise, a null response is returned by default even if .emit() is not called.

I'm assuming that .execute() calls HandleLambdaEvent() when any handler returns, ending the lambda context. The async code completes a few seconds later, and in the .then() of its promise calls .emit(), but the response has already returned. Am I missing something in the source code that allows a handler to suppress auto response send and manually .emit() when async returns?

This is a really handy module and I'm probably just missing something obvious in my code:

const Alexa = require('alexa-sdk');
const https = require('https');

const handlers = {
    'GoGetRESTfoo': function () {
        console.log("GoGetRESTfoo called");
        promisedRESTrequest('Some foo bar url').then(function(response) {
            console.log("Success!", response); // Yea, REST all the things
            this.emit(':tell', 'ok');
        }, function(error) {
            console.error("Failure!", response); // Boo, bad feels 
            this.emit(':tell', 'Hmm.. that didn\'t work.  Check the CloudWatch Luke.');
        });
    },

    // lots more handlers..
}

exports.handler = (event, context) => {
    const alexa = Alexa.handler(event, context);
    alexa.APP_ID = APP_ID;
    alexa.registerHandlers(handlers);
    console.log('before exec');
    alexa.execute();
    console.log('after exec');
};

Thanks!

audioPlayerPlay does not allow chaining play directives

I'd like to queue up multiple audio streams, as per the directives array discussed in the API docs here:
https://developer.amazon.com/public/community/post/Tx1DSINBM8LUNHY/New-Alexa-Skills-Kit-ASK-Feature-Audio-Streaming-in-Alexa-Skills

The natural way seems to be to make multiple calls to audioPlayerPlay. Unfortunately that method just overwrites the directive array every time instead of pushing new items. It would be nice if that method would support multiple calls.

System.ExceptionEncountered Handling

I'm not seeing anything in the sdk to handle System.ExceptionEncountered requests. As I'm working on a skill with the AudioPlayer, it'd be nice to see the errors with Audio directives or responses.

Full API description

Hello. Do we have any full api description? In readme you described some functions like:
".registerHandlers"
".emit"
".dynamoDBTableName"

but where i can see full possibilities list? Not just described in samples

Session is not cleared by setting this.handler.state = ''

if you set this.handler.state = '' and persist the state into DynamoDB the state will never get cleared, this is due to the following code:

':saveState': function(forceSave) {
if (this.isOverridden()) {
return;
}

        **if(forceSave && this.handler.state){
            this.attributes['STATE'] = this.handler.state;
        }**

notice that if you assign this.handler.state = '', then the if will not succeed. I am not sure exactly why this code is here. It may be that the && needs to be an ||. I believe the author is trying to prevent this.handler.state from being null (because Dynamo can't persist an empty string) or if state's aren't being used, then there isn't a reason to save the state. Maybe there needs to be a function to clear state or resetState, or maybe a parameter to saveState that is boolean for clearState. so something like this.

':saveState': function(forceSave, clearState) {
if (this.isOverridden()) {
return;
}

if (clearState) {
this.attributes['STATE'] = undefined;
} else {
if (forceSave && this.handler.state) {
this.attributes['STATE'] = this.handler.state;
}
}

I believe the above would be the least intrusive as many developers may already be working around this issue and may rely on this to function this way.

How to stop user session with Alexa-sdk?

Hi, i'm using alexa-sdk. My skill is very simple, but i'm not sure how to stop user session so that he can't use my skill without restarting it.
I use "shouldEndSession" for this purpose, when not using SDK. but i'm unable to find this in functionality provided by SDK (I'm sure it's been provided. Please guide).

Q: Streams By Timezone (Getting Custom Slots from Utterances)

Instead of audioData being a list of podcast files, I'm creating a list of streams. Each one is identified by a key tied to their timezone.

Since there doesn't appear to be a way to ask the device for the timezone, I've been prompting the user to provide the timezone. Once I get the value, I plan to check against the list of timezones I have streams for. If it's valid, I'll store it as an attribute in the session and store it in the db. Otherwise, reprompt the user.

For context:

Custom Slot
LIST_OF_TZ: Hawaii-Aleutian | Alaska | Pacific | Mountain | Central | Eastern | Atlantic

Utterance
GetTZ {Timezone}
GetTZ Set my timezone to {Timezone}

State Handler

 getTZIntentHandlers : Alexa.CreateStateHandler(constants.states.GET_TZ, {
 'LaunchRequest' : function () {
            // Session ended mid-tz setup.
           //  Initialize other attributes
           [...]
           // TZ Check
            if (!this.attributes['tz_info']) {
                var message = 'No timezone detected.  What timezone you are in?';
                this.response.speak(message).listen(message);
                this.emit(':responseReady');
            } else {
                var message = 'Timezone detected. On with the show!';
                this.response.speak(message);
                controller.play.call(this);
            }
        },
'GetTZ' : function () {
           // #TODO: Validation for invalid Custom Slot Type Values.
           this.attributes['tz_info'] = this.request.intent.slots.Timezone.value;   // The problem line.
           var message = 'You have a timezone. On with the show!';
           this.handler.state = constants.states.START_MODE;
           this.response.speak(message);
           controller.play.call(this);
        },
[...]
}

On to the main problem: I'm having trouble getting the slot value from the request. Is this referring to the session? It'd explain why I can't get the value through this.request.intent.slots.Timezone.value. If that's the case, who would I do it? And after that, how would I go about validating it against my custom slot type?

Sidebar: Is there another way to do this? It'd be great if there was something in the SDK for node.js like Alexa.locale.tz_info.

createStateHandler(s)

Couple of questions:

Should the API be CreateStateHandlers?

It's a bit confusing to have code where you create multiple handlers by creating a state handler singular?

var startStateHandlers = Alexa.CreateStateHandler(GAME_STATES.START, {

Also - in the example, newSessionHandlers don't use the above pattern. What's the best practice on this, should all handlers be created and assigned a state key so GAME_STATES.NEW ?

Thanks

home skill is at higher priority than custom skill?

Hello,

We are testing a custom skill, on which have command like "tell abc to turn on device xyz". Reply to me is always the smart home skill, not my custom skill. Though testing on Service Simulator is ok.

Just want to confirm that home skill is always at higher priority than custom skill. Is there any way to overwrite the priority?

Thanks.

Where to get slot values in intent function handler?

I'm having a hard time with the best approach to pull out slot values in the intent function handlers.

So for example:
utterance:

getFactAbout get fact about {name}
...

intent:

{
...
"intent": "getFactAbout",
"slots": [{
  "name": "name",
  "type": "string"
}]
...

handler:

getFactAbout: function () {
  const name = this.event.request.intent.slots.name.value;

  this.emit(":tell", name + " is ....");
}

Is this the correct approach? this.event.request.intent.slots.name.value has the value of the name passed in via an utterance like "Get fact about shaun". Where the value above would be shaun taken from the utterance and available in the handler?

Also, what other values are available on this object? (e.g. this.attributes and this.events)

Hosting as web service

Hi,

I have a doubt ..will this sdk even work without lambda function? I am hosting it as a webservice by using this sdk and I am getting the following error "There was an error calling the remote endpoint, which returned HTTP 405 : Method Not Allowed" . Could you give me the clarity whether this sdk works when hosted as a webservice(i,e without using lambda func) If yes do we need any additional configuration?

Please help! Thanks in Advance!

Add SessionStart and SessionEnd Callbacks for Tracking Analytics

This issue talks about integrating Mobile Analytics into the ASK:
#28

I think a better solution would now be SessionStart and SessionEnd callbacks that could be used with any analytics: Amazon Mobile, Google, VoiceLabs, etc.

At a minimum, these callbacks would pass the sessionId.

This would allow any analytics to be used with Alexa skills.

Include deployment scripts

Include deployment scripts like this project:

https://github.com/rmtuckerphx/alexa-skill-serverless-starter-template

This project shows improvements to an Alexa Skills Kit that uses the Serverless Framework to deploy your Node.js skill to Amazon Lambda. The template includes NPM scripts for creating both a Dev and Prod deployment including 1) creating IAM users used for deployment, 2) deploying code to Lambda, and 3) deploying translations, audio and image content to S3 via a local folder.

No mention of Account Linking or accessToken for user

Most skills for Alexa will require a linked account to be personal and secure for a given user and their data. You have a detailed wiki on account linking and seem to support it fairly well for the platform overall. After linking my account and generating a test json message with the test harness in the AWS Alexa developer console I can see a linked account gets passed the
session.user.accessToken value from the linking. However I do NOT see this mentioned anywhere in your documentation or sdk/library for a helper method or example about accessing and using it. It seems at minimum the READ.ME should be updated to mention and ideally have a helper method to access it safely if present.

https://developer.amazon.com/public/solutions/alexa/alexa-skills-kit/docs/linking-an-alexa-user-with-a-user-in-your-system

Thank You.

How to use with Dynamo DB

Hi
I have added the code you suggest and I am getting an AccessDeniedException. this is the code I am running

exports.handler = function (event, context, callback) { var alexa = Alexa.handler(event, context); alexa.dynamoDBTableName = 'skillstate; alexa.registerHandlers(Handler1, Handler2, Handlers3); alexa.execute(); };

Am I missing something?
Thanks

ValidationError loading data from DynamoDB

On my first request the dynamodb table is created successfully, but one each subsequent request to my service i get an error with the following message:

Error fetching user state: ValidationException: The provided key element does not match the schema

Here is the CloudWatch Log.

{
    "message": "The provided key element does not match the schema",
    "code": "ValidationException",
    "time": "2016-07-25T20:52:59.605Z",
    "requestId": "AR03L7713TK9HP5QEVK6GFO8U7VV4KQNSO5AEMVJF66Q9ASUAAJG",
    "statusCode": 400,
    "retryable": false,
    "retryDelay": 0
}

This is simply when testing the Start New Session event via Lambda.

Emit ask to specific intent

Is there a way to call emit:ask and route to a specific intent automatically without requiring the user to say a specific utterance matching the intent?

in my case I am asking the user which project they want to add a task to -

'Add task wash the car'

emit:ask 'Which project do you want to add wash the car to'

At the moment they have to say the word 'project' followed by the name of the project in order to call the specific intent.

This is quite annoying - if I could route to the correct intent automatically then all they would need to say is the name of the project.

Is this possible??

How to call rest api inside intent

i need some help.

I have been following the updated samples but unfortunately none have a call to an API.

Easiest way to explain is to attach a gist!!

In my BookingTimeIntent I want to call github status api for example.

See:
https://gist.github.com/shavo007/a89d82975c9a5420307f0bc7c871b7da

Now without a callback, it will not wait until the response comes back from api.

If i wrap the emit in a callback, i see the response from github in the logs but the emit complains.

Any clue?

Error handling for the case of a Response larger than 24kb

Need to add error handling to throw an error if a Request is packaged up that will result in the the Response being larger than 24 kilobytes.

I'm getting intent failures with no corresponding errors. In troubleshooting I've found that in certain cases I am exceeding the max allowed size of the JSON Response object. I see from the docs that the total size of your response cannot exceed 24 kilobytes.

Is there any way to store more than 24kb between intents in a session and not pass it in as part of the JSON Request object? Obviously if it goes in to the request it is going to come out as part of the response object and exceed the size limit.

I already persist data with DynamoDB, pulling in data to a new session each time. I have a workaround for the issue above to check if max allowable size is exceeded and if so to set this.attributes = null before this.emit(':ask/tell') and then reload them from the DB when the response comes back, but I don't want to have to go to the DB after every intent in the same session!

Also what is the object that I can refer to with something like (JSON.stringify(this.).length​ to get the full size of the JSON request object (not just the size of attributes)?

Run Code on Session Start

Is there a way to run code when a session has started? I understand there's a NewSession handler, but it seems mutually exclusive with any other handler and intercepts any intent requests.

For example, let's say somebody launches my skill with Alexa, tell {MyApp} {SomeIntent}. This is both a new session and an intent request. I'd like to execute code to initialize an analytics SDK only when a session is started regardless of whether or not it is an intent request (e.g. in the case of a LaunchRequest as well), and then continue on processing the intent request or the LaunchRequest like normal.

How to override built in functions?

The documentation says you have the Ability to override built-in functions but I cannot find any documentation for how to do so.

I am looking to post data to mobile analytics with each intent that comes in. I would rather do this once instead of having to wrap it around each individual intent handler.

Thanks in advance.

AWS SDK not passing correct credentials to test harness

I've followed the instructions supplied in the awesome tutorial provided by Nathan Grice.

I set up all users/roles/permissions/credentials correctly AFAICT but I end up with the following error:

get error: { "message": "The security token included in the request is invalid.", "code": "UnrecognizedClientException", "time": "2016-10-19T19:26:12.380Z", "requestId": "8123U3IOJAJQH3PDLEOUS484HRVV4KQNSO5AEMVJF66Q9ASUAAJG", "statusCode": 400, "retryable": false, "retryDelay": 0 } context.fail Error fetching user state: UnrecognizedClientException: The security token included in the request is invalid.

When I print out the security credentials, I noticed that they do no match the credentials I set up in my ~/.aws/credentials file for the debug user that I created. They're something else entirely.

When I hard-code my security credentials inside my test/main.js function like so

AWS.config.update({ accessKeyId: "...XXX...",//data.Credentials.AccessKeyId, secretAccessKey: "...xxx...",//data.Credentials.SecretAccessKey, sessionToken: data.Credentials.sessionToken });

I'm able to access my data in my dynamoDB.

So something's up with the credentials not getting passed around correctly, or I just messed up or misunderstood something. I'm happy to close this out if it's my bad, but I need to know what I'm doing incorrectly.

I've also pasted the test/main.js file I'm using for greater context.
main.js.txt

Alexa.CreateStateHandler & potential of being able to specify a list of intent handlers in a Request

From the readme: 'Alexa-sdk will route incoming intents to the correct function handler based on state.'

Just a thought, and it isn't specific to the alexa-sdk, but rather the way Requests are made with ASK - It seems like it could be more powerful if you could pass a list of intents in the Request that you wanted to be considered for when the user utterance is mapped to an intent. You could then prevent the wrong intent from firing (when a custom slot is misinterpreted for example) or handle a situation where you want the same utterance to invoke one of many intent handlers depending on the context.

Example:

Below OtherOptionsA and OtherOptionsB intent handlers are created to each only be applicable to the WELCOME state and the LODGE state, respectively. Both intents are set up to be invoked with the same sample utterance of 'other'.

If the skill is not in state=WELCOME, OtherOptionsAIntent will not work. So there is only one intent handler at a time that is active and can be invoked with the utterance 'other'. But as it stands now, when the skill is in state=LODGE and a user says 'other', the intent request comes in for OtherOptionsAIntent, which by definition is not available since it was defined specific to state=WELCOME. Since OtherOptionsAIntent isn't available, the Unhandled intent handler under state=LODGE is invoked, producing a response of res.lodgeUnhandled(), not res.OtherOptionsB().

In this example it is easy enough to just have a single intent handler that fires with utterance 'other', and then route to the appropriate response within that handler, but just wondering about the potential of being able to specify a list of handlers in a Request.

module.exports.welcome = Alexa.CreateStateHandler(APP_STATES.WELCOME, mixinHandlers(coreHandlers, {
  NewSession () {
      res.ask.call(this, res.welcomeGuest())
  },
  OtherOptionsAIntent () {
    this.handler.state = APP_STATES.OTHEROPTIONS
    res.ask.call(this, res.otherOptionsA())
  },
  Unhandled () {
    res.ask.call(this, res.welcomeUnhandled(), res.welcomeUnhandled())
  }
}))

module.exports.lodge = Alexa.CreateStateHandler(APP_STATES.LODGE, mixinHandlers(coreHandlers, {
  NewSession () {
      res.ask.call(this, res.lodge())
  },
  OtherOptionsBIntent () {
    res.ask.call(this, res.OtherOptionsB())
  },
  Unhandled () {
    res.ask.call(this, res.lodgeUnhandled(), res.lodgeUnhandled())
  }
}))

Add Mobile Analytics to ASK

I have started integration of Mobile Analytics into the ASK and the basic cases are working.
The repo is at: https://github.com/rmtuckerphx/alexa-skills-kit-sdk-for-nodejs

The code to create custom events inside an intent handler function is not working. Here is a sample of what I am trying to do:

    'GetNewFactIntent': function () {
        this.recordMobileAnalyticsEvent('foo', 'sessionId');

Feedback on the changes or help figuring out this issue is appreciated.

.NET Support...

With such widespread .NET support, across so many devices and platforms, any chance Amazon will release a .NET SDK for Alexa?

Update "Next Steps" in Readme

Currently, the "Next Steps" sections contains links to Intro to "Alexa Skills On Demand" and "Voice Design 101 On Demand." These links appear to no longer point to valid content. If the content has moved, I recommend updating the links. If the content is simply no longer available, it may be optimal to remove those items from the Readme.

old context model dooms callbacks to fail

The alexa sdk doesn't use the Lambda callback. Instead, it uses the old context.(succeed|fail) methods. This works fine in a lot of cases, but dooms a few fairly simple use cases.

For instance, if your skill wants to increment a number every time the user launches the app, and persist in dynamodb, you would try to set an attribute on launch and then maybe do

this.handler.state  = "SOME_STATE";
emit(":ask", "Welcome. What is your name?");
this.attributes.invocations = 1

Unless you have saveBeforeResponse on, this won't call saveState and so you have to do that yourself. So now we have

this.handler.state  = "SOME_STATE";
emit(":ask", "Welcome. What is your name?");
this.attributes.invocations = 1
emit(":saveState", true);

This will not work. Ask will emit(":responseReady"), which will call context.succeed, and poof, sucks to suck for your saveState request. It's callback is likely doomed to fail. Your database won't update and you'll be sad. This is extra confusing because you might happen to use a tell instead.

this.handler.state  = "SOME_STATE";
emit(":tell", "This is my skill. Goodbye!");
this.attributes.invocations = 1
emit(":saveState", true);

This will appear to work because tell automatically persists, see #8 for a fix for that. However, all you'll see in your database is the state, because you set invocations after the tell. And of course the callback for saveState is doomed to fail and so you're screwed.

I propose a switch the use callback. You already have a object property for it! I found it in alexa.js, it's set and everything! But y'all need to use it instead of the context calls.

I am totally open to being wrong about all this, but after several days of testing and hacking I'm pretty sure this is what's going on. If I can get a response here that this is correct I will gladly make the PR for this change.

State doesn't get saved if you return to start state

Start state is represented by having a blank state variable. Switching to another state works fine, but if you try to switch back to the start state, it never gets saved.

I suspect this is caused by the following line in /lib/response.js:93:

            if(this.handler.state) {
                this.handler.response.sessionAttributes['STATE'] = this.handler.state;
            }

seeing as the expression evaluates to false for an empty string, the STATE attribute never gets updated. Does this if statement really need to be there?

Asynchronous callback not firing this.emit(':ask') before exit of HandleLambdaEvent()

I have an event handler which is making an external call to a REST interface. The event handler is setup to perform the this.emit(':ask', ...) in the callback from a request call to the remote service. The service takes about 1-2 seconds to return data and is asynchronous (from the npm request package)

var request = require('request);
function myHandler(input, callback) {
         request('http://rest_url...', function(error, response, body) { 
               if (response) { // we have a success so call the call back
                     callback(null, 'found it!');
               } else {
                     callback(error);
               }
        }
}

The callback, which is called from the event handler, then performs the this.emit(':ask'),

'myEventHandler': function() {
        myHandler('findThisData', (error, rsp) => {
            if(error) {
                this.emit(":tell",  "I'm sorry, but I can't find  that information.");
            } else {
               this.emit(":ask", " I found!", "Want to do anything else?");
        });
       // notice no emit or context.success/fail/done at end of event handler
}

The alexa-sdk seems to call HandleLambdaEvent() which calls EmitEvent which will return from myEventHandler before the callback is executed. The delay return in the asynchronous callback will get executed after HandleLambdaEvent() has returned. This sequence seems to return a 'null' to the lambda function and fails to ever get a chance to handle the eventual call to this.emit() processed in the callback function.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.