Проблема с обновлением Item DynamoDB таблицы на Alexa Skill - PullRequest
0 голосов
/ 13 октября 2019

Я пытаюсь обновить элемент на столе, у навыка есть только одно намерение, и предполагается, что элемент "статус" должен быть изменен на "включено" или "выключено" в зависимости от условия.

const Alexa = require('ask-sdk');
var AWS = require("aws-sdk");
const dynamoDBTableName = "automation-test";
AWS.config.update({region: "ap-southeast-2"});
const tableName = "automation-test";
var docClient = new AWS.DynamoDB.DocumentClient();


const LaunchRequestHandler = {
    canHandle(handlerInput) {
        return Alexa.getRequestType(handlerInput.requestEnvelope) === 'LaunchRequest';
    },
    handle(handlerInput) {
        const speakOutput = 'Welcome';
        return handlerInput.responseBuilder
            .speak(speakOutput)
            .reprompt(speakOutput)
            .getResponse();
    }
};


const LivingRoomLightsIntentHandler = {
    canHandle(handlerInput) {
        return Alexa.getRequestType(handlerInput.requestEnvelope) === 'IntentRequest'
            && Alexa.getIntentName(handlerInput.requestEnvelope) === 'LivingRoomLightsIntent';
    },
    handle(handlerInput) {

        const LightStatus = handlerInput.requestEnvelope.request.intent.slots.LightStatus.resolutions.resolutionsPerAuthority[0].values[0].value.name;
        const deviceID = "livingRoomLights"

        if (LightStatus === "On") {

            const status = "true"
            const params = {
                TableName: tableName,
                Key: {
                  'deviceID' : deviceID,
                },
                UpdateExpression: 'set status = :s', 
                ExpressionAttributeValues: {
                  ':s' : status
                }
            };

        docClient.update(params, function(err, data) {
            if (err) {
              console.log("Error", err);
            } else {
              console.log("Success", data);
            }
          });

        const speakOutput = `The living room light has been set to ${LightStatus}`;
        return handlerInput.responseBuilder
          .speak(speakOutput)
          .reprompt()
          .getResponse();

        }




         else if (LightStatus === "Off") {

            const status = "false"
            const params = {
                TableName: tableName,
                Key: {
                  'deviceID' : deviceID,
                },
                UpdateExpression: 'set status = :s', 
                ExpressionAttributeValues: {
                  ':s' : status
                }
            };

        docClient.update(params, function(err, data) {
            if (err) {
              console.log("Error", err);
            } else {
              console.log("Success", data);
            }
          });

        const speakOutput = `The living room light has been set to ${LightStatus}`;
        return handlerInput.responseBuilder
          .speak(speakOutput)
          .reprompt()
          .getResponse();
           }
           } 
    };


const HelpIntentHandler = {
    canHandle(handlerInput) {
        return Alexa.getRequestType(handlerInput.requestEnvelope) === 'IntentRequest'
            && Alexa.getIntentName(handlerInput.requestEnvelope) === 'AMAZON.HelpIntent';
    },
    handle(handlerInput) {
        const speakOutput = 'You can say hello to me! How can I help?';

        return handlerInput.responseBuilder
            .speak(speakOutput)
            .reprompt(speakOutput)
            .getResponse();
    }
};
const CancelAndStopIntentHandler = {
    canHandle(handlerInput) {
        return Alexa.getRequestType(handlerInput.requestEnvelope) === 'IntentRequest'
            && (Alexa.getIntentName(handlerInput.requestEnvelope) === 'AMAZON.CancelIntent'
                || Alexa.getIntentName(handlerInput.requestEnvelope) === 'AMAZON.StopIntent');
    },
    handle(handlerInput) {
        const speakOutput = 'Goodbye!';
        return handlerInput.responseBuilder
            .speak(speakOutput)
            .getResponse();
    }
};
const SessionEndedRequestHandler = {
    canHandle(handlerInput) {
        return Alexa.getRequestType(handlerInput.requestEnvelope) === 'SessionEndedRequest';
    },
    handle(handlerInput) {
        // Any cleanup logic goes here.
        return handlerInput.responseBuilder.getResponse();
    }
};

// The intent reflector is used for interaction model testing and debugging.
// It will simply repeat the intent the user said. You can create custom handlers
// for your intents by defining them above, then also adding them to the request
// handler chain below.
const IntentReflectorHandler = {
    canHandle(handlerInput) {
        return Alexa.getRequestType(handlerInput.requestEnvelope) === 'IntentRequest';
    },
    handle(handlerInput) {
        const intentName = Alexa.getIntentName(handlerInput.requestEnvelope);
        const speakOutput = `You just triggered ${intentName}`;

        return handlerInput.responseBuilder
            .speak(speakOutput)
            //.reprompt('add a reprompt if you want to keep the session open for the user to respond')
            .getResponse();
    }
};

// Generic error handling to capture any syntax or routing errors. If you receive an error
// stating the request handler chain is not found, you have not implemented a handler for
// the intent being invoked or included it in the skill builder below.
const ErrorHandler = {
    canHandle() {
        return true;
    },
    handle(handlerInput, error) {
        console.log(`~~~~ Error handled: ${error.stack}`);
        const speakOutput = `Sorry, I had trouble doing what you asked. Please try again.`;

        return handlerInput.responseBuilder
            .speak(speakOutput)
            .reprompt(speakOutput)
            .getResponse();
    }
};

// The SkillBuilder acts as the entry point for your skill, routing all request and response
// payloads to the handlers above. Make sure any new handlers or interceptors you've
// defined are included below. The order matters - they're processed top to bottom.
exports.handler = Alexa.SkillBuilders.custom()
    .addRequestHandlers(
        LaunchRequestHandler,
        LivingRoomLightsIntentHandler,
        HelpIntentHandler,
        CancelAndStopIntentHandler,
        SessionEndedRequestHandler,
        IntentReflectorHandler, // make sure IntentReflectorHandler is last so it doesn't override your custom intent handlers
        ) 

        .addErrorHandlers(ErrorHandler)
  .withTableName(dynamoDBTableName)
  .withAutoCreateTable(true)
    .lambda();

Вот журнал

Невозможно импортировать модуль 'index': ошибка. Function.Module._resolveFilename (module.js: 547: 15) в Function.Module._load (module.js): 474: 25) в Module.require (module.js: 596: 17) по требованию (internal / module.js: 11: 18) в Object. (/var/task/index.js:1:77)at Module._compile (module.js: 652: 30) в Object.Module._extensions..js (module.js: 663: 10) в Module.load (module.js: 565: 32) в tryModuleLoad (module.js: 505: 12) в Function.Module._load (module.js: 497: 3)

Пожалуйста, помогите!

1 Ответ

0 голосов
/ 13 октября 2019

DynamoDb использует 2 уникальных идентификатора для обнаружения конкретной строки. Убедитесь, что вы отправляете информацию правильно. Тогда только ваша строка будет обнаружена и значение будет обновлено.

...