Невозможно выполнить намерения в Alexa Skills - PullRequest
0 голосов
/ 05 февраля 2020

По какой-то причине я не могу выполнить несколько своих намерений в своем навыке Alexa. Вот поток обсуждения, как он есть.

  1. «открыть мои пароли»

Alexa: какая у вас пароль?

«Мой пароль - тест»

Алекса: Вы находитесь.

'Какой у меня пароль Wi-Fi?'

Alexa: Возникла проблема с ответом запрошенного навыка.

Вот скриншот разговора.

enter image description here

А вот мои допустимые высказывания, где type относится к типу слотов AMAZON.SearchQuery.

enter image description here

На данный момент я просто пытаюсь достичь GetPasswordHandler и попросить ее сказать «Привет, мир». Но я не могу войти или достичь этого намерения. В какой-то момент я достиг этого и смог выполнить это намерение, но по какой-то причине оно сейчас не работает, и я просто получаю сообщение об ошибке c There was a problem with the requested skill's response.

Я попытался обойти намерения, потому что я Я подумал, может быть, порядок, в котором они были перечислены, был проблемой, но я еще не нашел порядок, который работает. Я также пытался использовать CloudWatch для регистрации любой проблемы, но я довольно новичок в этом, и, возможно, я использую ее неправильно, потому что я чувствую, что информация не очень полезна, кроме того, что сигнализирует. Из ввода JSON в тестовой панели мне удалось выяснить только, что ответ был недействительным. Вот как выглядит ошибка на входе JSON для SessionEndRequest.

"error": {
            "type": "INVALID_RESPONSE",
            "message": "An exception occurred while dispatching the request to the skill."
        }

Это вход JSON для исходного GetPassword запроса.

"request": {
        "type": "IntentRequest",
        "requestId": "amzn1.echo-api.request.bdae78eb-3c92-49a8-b3af-c590e284b842",
        "timestamp": "2020-02-05T17:23:03Z",
        "locale": "en-US",
        "intent": {
            "name": "GetPassword",
            "confirmationStatus": "NONE",
            "slots": {
                "type": {
                    "name": "type",
                    "value": "WiFi",
                    "confirmationStatus": "NONE",
                    "source": "USER"
                }
            }
        }
    }

Вот мой лямбда-код.

// This sample demonstrates handling intents from an Alexa skill using the Alexa Skills Kit SDK (v2).
// Please visit https://alexa.design/cookbook for additional examples on implementing slots, dialog management,
// session persistence, api calls, and more.
const Alexa = require('ask-sdk-core');

const passphrase = 'test';

const instructions = `You can access existing passwords or create a new password. 
            Just specify password type, such as wifi, laptop or cellphone.`;

// the intent being invoked or included it in the skill builder below.


 const LoginHandler = {
     canHandle(handlerInput) {
         return Alexa.getRequestType(handlerInput.requestEnvelope) === 'IntentRequest'
             && handlerInput.requestEnvelope.request.intent.name === "Login";
     },
     handle(handlerInput) {
         console.log('test');
         const request  = handlerInput.requestEnvelope.request;
         const responseBuilder = handlerInput.responseBuilder;
          let slotValues = handlerInput.requestEnvelope.request.intent.slots

         if (slotValues && slotValues.passphrase.value === passphrase){
             var attributes = handlerInput.attributesManager.getSessionAttributes()
             attributes.isLoggedIn = true
             const speakOutput = "You're in.";
             return handlerInput.responseBuilder
             .speak(speakOutput)
             .reprompt(speakOutput)
             .getResponse();  

         } else {
             const speakOutput = `Passphrase not recognized. What is your passphrase?`;

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

const LaunchRequestHandler = {
    canHandle(handlerInput) {
        return Alexa.getRequestType(handlerInput.requestEnvelope) === 'LaunchRequest';
    },
    handle(handlerInput) {
        var attributes = handlerInput.attributesManager.getSessionAttributes();
        if (attributes.isLoggedIn){
            const speakOutput = `Welcome to your passwords. ${instructions}`;
            return handlerInput.responseBuilder
            .speak(speakOutput)
            .reprompt(speakOutput)
            .getResponse(); 
        } else {
            const speakOutput = `What is your pass phrase?`;
            return handlerInput.responseBuilder
            .speak(speakOutput)
            .reprompt(speakOutput)
            .getResponse();     
        }

    }
};


// THIS IS THE INTENT THAT DOES NOT WORK
const GetPasswordHandler = {
    canHandle(handlerInput) {
        return (Alexa.getRequestType(handlerInput.requestEnvelope) === 'IntentRequest' && handlerInput.requestEnvelope.request.intent.name === "GetPassword");
    },
    handle(handlerInput) {
        console.log('yes');

        const speakOutput = 'hello world';
            return handlerInput.responseBuilder
            .speak(speakOutput)
            .reprompt(speakOutput)
            .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!';
        handlerInput.sessionAttributes.isLoggedIn = false 
        return handlerInput.responseBuilder
            .speak(speakOutput)
            .getResponse();
    }
};

const SessionEndedRequestHandler = {
    canHandle(handlerInput) {
        return Alexa.getRequestType(handlerInput.requestEnvelope) === 'SessionEndedRequest';
    },
    handle(handlerInput) {
        // Any cleanup logic goes here.
        handlerInput.sessionAttributes.isLoggedIn = false 
        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) {
        handlerInput.sessionAttributes.isLoggedIn = false 
        console.log(`~~~~ Error handled: ${error.stack}`);
        const speakOutput = `Sorry, I had trouble doing what you asked. Please try again. ${error.stack}`;

        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,
        CancelAndStopIntentHandler,
        SessionEndedRequestHandler,
        LoginHandler,
        GetPasswordHandler,
        HelpIntentHandler,
        IntentReflectorHandler, // make sure IntentReflectorHandler is last so it doesn't override your custom intent handlers
    )
    .addErrorHandlers(
        ErrorHandler,
    )
    .lambda();

А вот и мой JSON.

{
    "interactionModel": {
        "languageModel": {
            "invocationName": "my passwords",
            "intents": [
                {
                    "name": "AMAZON.CancelIntent",
                    "samples": []
                },
                {
                    "name": "AMAZON.HelpIntent",
                    "samples": []
                },
                {
                    "name": "AMAZON.StopIntent",
                    "samples": []
                },
                {
                    "name": "AMAZON.NavigateHomeIntent",
                    "samples": []
                },
                {
                    "name": "GetPassword",
                    "slots": [
                        {
                            "name": "type",
                            "type": "AMAZON.SearchQuery"
                        }
                    ],
                    "samples": [
                        "password for my {type}",
                        "{type} password",
                        "what is my {type} password"
                    ]
                },
                {
                    "name": "AMAZON.MoreIntent",
                    "samples": []
                },
                {
                    "name": "AMAZON.NavigateSettingsIntent",
                    "samples": []
                },
                {
                    "name": "AMAZON.NextIntent",
                    "samples": []
                },
                {
                    "name": "AMAZON.PauseIntent",
                    "samples": []
                },
                {
                    "name": "AMAZON.ResumeIntent",
                    "samples": []
                },
                {
                    "name": "Login",
                    "slots": [
                        {
                            "name": "passphrase",
                            "type": "AMAZON.SearchQuery"
                        }
                    ],
                    "samples": [
                        "my passphrase is {passphrase}"
                    ]
                },
                {
                    "name": "AMAZON.PageUpIntent",
                    "samples": []
                },
                {
                    "name": "AMAZON.PageDownIntent",
                    "samples": []
                },
                {
                    "name": "AMAZON.PreviousIntent",
                    "samples": []
                },
                {
                    "name": "AMAZON.ScrollRightIntent",
                    "samples": []
                },
                {
                    "name": "AMAZON.ScrollDownIntent",
                    "samples": []
                },
                {
                    "name": "AMAZON.ScrollLeftIntent",
                    "samples": []
                },
                {
                    "name": "AMAZON.ScrollUpIntent",
                    "samples": []
                }
            ],
            "types": []
        }
    }
}

1 Ответ

0 голосов
/ 06 февраля 2020

В итоге я просто переписал намерения, и теперь они работают. Я не уверен, что именно было не так, но я заметил, что, когда я добавил новые намерения, они были добавлены в конец моего манифеста скилл, в отличие от предыдущего порядка. Я не уверен на 100%, что это была проблема, но это единственное, что я заметил, изменившись, когда я переделал свои намерения.

...