Alexa Skills: лямбда-функция для чтения содержимого из файла в S3 - PullRequest
0 голосов
/ 28 июня 2018

У меня есть навык Alexa, который пытается прочитать содержимое файла, хранящегося в S3. Тестовое событие для лямбда-функции для Alexa Start Session прошло успешно. Я понимаю, что что-то не так с моим CompletedMyIntentHandler, но я не могу понять это. Любая помощь в этом очень ценится. Лямбда-функция получает помощь от https://github.com/alexa/alexa-cookbook/blob/master/aws/Amazon-S3/read/. Найдите мою лямбда-функцию ниже;

   const Alexa = require('ask-sdk');     
     // 1. Text strings =====================================================================================================
        //    Modify these strings and messages to change the behavior of your Lambda function

        const helpOutput = 'You can demonstrate the S3 Storage read capability by saying "Hello".';
        const helpReprompt = 'Try saying "Hello World".';


        var myBucket = 'jailalita';      // replace with your own bucket name!
        var myObject = 'hello.txt';          // replace with your own file name!


        // 2. Intent Handlers =============================================

        const CompletedMyIntentHandler = {
          canHandle(handlerInput) {
            const request = handlerInput.requestEnvelope.request;
            return request.type === 'IntentRequest' && request.intent.name === 'MyIntent';
          },
          handle(handlerInput) {
            console.log('My Intent - handle');

            const responseBuilder = handlerInput.responseBuilder;
            const speechOutput = MyIntent();
            return responseBuilder
            .speak(speechOutput)
            .getResponse();
          },
        };

        const HelpHandler = {
          canHandle(handlerInput) {
            const request = handlerInput.requestEnvelope.request;
            return request.type === 'IntentRequest' && request.intent.name === 'AMAZON.HelpIntent';
          },
          handle(handlerInput) {
            const responseBuilder = handlerInput.responseBuilder;
            return responseBuilder
              .speak(helpOutput)
              .reprompt(helpReprompt)
              .getResponse();
          },
        };

        const CancelStopHandler = {
          canHandle(handlerInput) {
            const request = handlerInput.requestEnvelope.request;
            return request.type === 'IntentRequest' && (request.intent.name === 'AMAZON.CancelIntent' || request.intent.name === 'AMAZON.StopIntent');
          },
          handle(handlerInput) {
            const responseBuilder = handlerInput.responseBuilder;
            const speechOutput = 'Okay, talk to you later! ';

            return responseBuilder
              .speak(speechOutput)
              .withShouldEndSession(true)
              .getResponse();
          },
        };

        const SessionEndedHandler = {
          canHandle(handlerInput) {
            const request = handlerInput.requestEnvelope.request;
            return request.type === 'SessionEndedRequest';
          },
          handle(handlerInput) {
            console.log(`Session ended with reason: ${handlerInput.requestEnvelope.request.reason}`);
            return handlerInput.responseBuilder.getResponse();
          },
        };

        const ErrorHandler = {
          canHandle() {
            return true;
          },
          handle(handlerInput, error) {
            const request = handlerInput.requestEnvelope.request;

            console.log(`Original Request was: ${JSON.stringify(request, null, 2)}`);
            console.log(`Error handled: ${error}`);

            return handlerInput.responseBuilder
              .speak('Sorry, I can not understand the command.  Please say again.')
              .reprompt('Sorry, I can not understand the command.  Please say again.')
              .getResponse();
          },
        };


        // 3. Helper Function  =================================================================================================

        function MyIntent() {

                var myParams = {
                    Bucket: myBucket,
                    Key: myObject
                };

                S3read(myParams,  myResult => {
                        console.log("sent     : " + JSON.stringify(myParams));
                        console.log("received : " + myResult);

                       var speech = this.response.speak('The S 3 file says, ' + myResult );
                       return speech;

                    }
                );

            }

        function S3read(params, callback) {
            // call AWS S3
            var AWS = require('aws-sdk');
            var s3 = new AWS.S3();

            s3.getObject(params, function(err, data) {
                if(err) { console.log(err, err.stack); }
                else {

                    var fileText = data.Body.toString();  // this is the complete file contents

                    callback(fileText);
                }
            });
        }


        // 4. Exports handler function and setup ===================================================

        const skillBuilder = Alexa.SkillBuilders.custom();
        exports.handler = skillBuilder
          .addRequestHandlers(
            //LaunchRequestHandler,
              CompletedMyIntentHandler,
            HelpHandler,
            CancelStopHandler,
            SessionEndedHandler,
            )
            .addErrorHandlers(ErrorHandler)
              .lambda();

JSON Input

{
        "version": "1.0",
        "session": {
            "new": true,
            "sessionId": "amzn1.echo-api.session.e6f74d95-8d55-4aac-ade0-dd4ff4ed4f04",
            "application": {
                "applicationId": "amzn1.ask.skill.5edd47bc-525d-4ef4-9b6e-a83a7e79744f"
            },
            "user": {
                "userId": "amzn1.ask.account.AF4SLRK5TC4SDSHL7LGK2IB6SMXCPGS7Y6YKYLPDGWRE7CA3K6MCKVVUW2OFMVCWJFXZDQBSYY5Z2RXZWQAJLDCMR3SXYCVA7ZARDRNQXA3TXBM4ILP77FKNOO4MCVPLWHIXW3QNZCRYPDQ7CCBP6QT7GMTBMQX2BVCNS22SZL4MC6WB7GDS44XN2DKGJQBMGIDQ3O7RBYD6GAI"
            }
        },
        "context": {
            "System": {
                "application": {
                    "applicationId": "amzn1.ask.skill.5edd47bc-525d-4ef4-9b6e-a83a7e79744f"
                },
                "user": {
                    "userId": "amzn1.ask.account.AF4SLRK5TC4SDSHL7LGK2IB6SMXCPGS7Y6YKYLPDGWRE7CA3K6MCKVVUW2OFMVCWJFXZDQBSYY5Z2RXZWQAJLDCMR3SXYCVA7ZARDRNQXA3TXBM4ILP77FKNOO4MCVPLWHIXW3QNZCRYPDQ7CCBP6QT7GMTBMQX2BVCNS22SZL4MC6WB7GDS44XN2DKGJQBMGIDQ3O7RBYD6GAI"
                },
                "device": {
                    "deviceId": "amzn1.ask.device.AETD2DDUWNTWA5BNNDFHCRT26SLOZUTZUFJ5P3OEQGDCWWDSFWPKNONGMT4KZAJPUB6ZRD3YVCDEVFAGPLXHVP6XESWS6BKEYZHZRXT25QNK2RTFNUG4PKD347P5DAWE2H4WQLGTQVLNQ5JNFGHFUSUC3X7Q",
                    "supportedInterfaces": {}
                },
                "apiEndpoint": "https://api.amazonalexa.com",
                "apiAccessToken": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6IjEifQ.eyJhdWQiOiJodHRwczovL2FwaS5hbWF6b25hbGV4YS5jb20iLCJpc3MiOiJBbGV4YVNraWxsS2l0Iiwic3ViIjoiYW16bjEuYXNrLnNraWxsLjVlZGQ0N2JjLTUyNWQtNGVmNC05YjZlLWE4M2E3ZTc5NzQ0ZiIsImV4cCI6MTUzMDUxMzU2NCwiaWF0IjoxNTMwNTA5OTY0LCJuYmYiOjE1MzA1MDk5NjQsInByaXZhdGVDbGFpbXMiOnsiY29uc2VudFRva2VuIjpudWxsLCJkZXZpY2VJZCI6ImFtem4xLmFzay5kZXZpY2UuQUVURDJERFVXTlRXQTVCTk5ERkhDUlQyNlNMT1pVVFpVRko1UDNPRVFHRENXV0RTRldQS05PTkdNVDRLWkFKUFVCNlpSRDNZVkNERVZGQUdQTFhIVlA2WEVTV1M2QktFWVpIWlJYVDI1UU5LMlJURk5VRzRQS0QzNDdQNURBV0UySDRXUUxHVFFWTE5RNUpORkdIRlVTVUMzWDdRIiwidXNlcklkIjoiYW16bjEuYXNrLmFjY291bnQuQUY0U0xSSzVUQzRTRFNITDdMR0sySUI2U01YQ1BHUzdZNllLWUxQREdXUkU3Q0EzSzZNQ0tWVlVXMk9GTVZDV0pGWFpEUUJTWVk1WjJSWFpXUUFKTERDTVIzU1hZQ1ZBN1pBUkRSTlFYQTNUWEJNNElMUDc3RktOT080TUNWUExXSElYVzNRTlpDUllQRFE3Q0NCUDZRVDdHTVRCTVFYMkJWQ05TMjJTWkw0TUM2V0I3R0RTNDRYTjJES0dKUUJNR0lEUTNPN1JCWUQ2R0FJIn19.Fc-aAcaf4qTgf489cQsZ44KTq-yZ-xMJCBenq9DbpppkMgSscF0NodGYTK967AcGblwqOFqcwIC1PvGmISER9oDH5TIhKF1kLsTimRHRKsttElRl7FIEvki-sKLD4VTeStTKM-w5laBm6urAzlCXpJySU-InVH5_qE0M5LHnLZRrE_qy7EmIq2vsrq2Cekve-gQ3Y3ImW3_0b7ikg6gwO6si-O0IxXO6hxS5sTuQH4f4aRybHVO3jflHD7g7pGPFzfkpc_tg6KFkhFv6CMvkx25A2u7iO7vVQpMHdj-_2ZM0ZmO9JuP-v7ydKYT_1IDjfpZKfvgIGyYsNfCPDY5F2Q"
            }
        },
        "request": {
            "type": "LaunchRequest",
            "requestId": "amzn1.echo-api.request.12ef23e3-a7e5-48a4-90f9-de9c253f72b9",
            "timestamp": "2018-07-02T05:39:24Z",
            "locale": "en-US",
            "shouldLinkResultBeReturned": false
        }
    }

Выход JSON

    {
        "body": {
            "version": "1.0",
            "response": {
                "outputSpeech": {
                    "type": "SSML",
                    "ssml": "<speak>Sorry, I can not understand the command.  Please say again.</speak>"
                },
                "reprompt": {
                    "outputSpeech": {
                        "type": "SSML",
                        "ssml": "<speak>Sorry, I can not understand the command.  Please say again.</speak>"
                    }
                },
                "shouldEndSession": false
            },
            "sessionAttributes": {},
            "userAgent": "ask-node/2.0.0 Node/v8.10.0"
        }
    }

JSON Editor

{
    "interactionModel": {
        "languageModel": {
            "invocationName": "hello world",
            "intents": [
                {
                    "name": "AMAZON.FallbackIntent",
                    "samples": []
                },
                {
                    "name": "AMAZON.CancelIntent",
                    "samples": []
                },
                {
                    "name": "AMAZON.HelpIntent",
                    "samples": []
                },
                {
                    "name": "AMAZON.StopIntent",
                    "samples": []
                },
                {
                    "name": "MyIntent",
                    "slots": [],
                    "samples": [
                        "hello"
                    ]
                }
            ],
            "types": []
        }
    }
}

1 Ответ

0 голосов
/ 16 ноября 2018

Вы не можете построить свой ответ и вернуться внутрь функции S3Read, поскольку это асинхронный вызов внешней службы. Вам нужно дождаться этого вызова, используя async / await, и как только вы получите значение, создайте ответ и вернитесь.

...