как предотвратить запуск намерения, если другое намерение не было вызвано первым - PullRequest
0 голосов
/ 27 сентября 2019

Я хочу активировать свой WaitAnswerIntentHandler, только если ранее был запущен RandomLetterIntentHandler.В настоящее время мое второе намерение может быть вызвано высказываниями {animal} {country} {color} {food} (не все обязательны и могут быть в любом порядке), но ему нужно первое намерение для создания желаемой логики.

const RandomLetterIntentHandler = {
    canHandle(handlerInput) {
        return Alexa.getRequestType(handlerInput.requestEnvelope) === 'IntentRequest'
            && Alexa.getIntentName(handlerInput.requestEnvelope) === 'RandomLetterIntent';
    },
    handle(handlerInput) {
  // **get a letter from the user**
        const requestAttributes = handlerInput.attributesManager.getRequestAttributes();
        const randomLetter = randomLetterGenerator.getOneRandomLetter();
        const speechText = requestAttributes.t('RANDOM_LETTER_ASK', randomLetter);
        timerUtils.startTimer();
        puntuacion = 0;
        letter= randomLetter;
        return handlerInput.responseBuilder
            .speak(speechText)
            .reprompt(speechText)
            .getResponse();
    }
};
const WaitAnswerIntentHandler = {
    canHandle(handlerInput){
        return Alexa.getRequestType(handlerInput.requestEnvelope) === 'IntentRequest'
        && Alexa.getIntentName(handlerInput.requestEnvelope) === 'WaitAnswerIntent'
        && gameState > 0;
    },
    handle(handlerInput){
### **// get {animal}{country}{color}{food} (not all required and can be in any order) but need the letter that is obtained in the previous intent**
        const intent = handlerInput.requestEnvelope.request.intent;

        const animal = intent.slots.ANIMAL.value;
        const country = intent.slots.COUNTRY.value;
        const color = intent.slots.COLOR.value;
        const food = intent.slots.FOOD.value;

        let cadenaFinal = '';
        let tiempoFinal = 0;

        if(animal && animal[0]===letter){
            puntuacion = puntuacion + 10;
            cadenaFinal = cadenaFinal + ' ' + animal;
        }
        if(country && country[0]===letter){
            puntuacion = puntuacion + 10;
            cadenaFinal = cadenaFinal + ' ' + country;
        }
        if(color && color[0]===letter){
            puntuacion = puntuacion + 10;
            cadenaFinal = cadenaFinal + ' ' + color;
        }
        if(food && food[0]===letter){
            puntuacion = puntuacion + 10;
            cadenaFinal = cadenaFinal + ' ' + food;
        }

        tiempoFinal = timerUtils.endTimer();
        puntuacion = puntuacion - tiempoFinal;

        if(!cadenaFinal){cadenaFinal='ninguna'}
        const repromtText = 'pídeme otra letra para seguir jugando';
        const speakOutput = `Tu respuesta válida fue ${cadenaFinal}, has tardado ${tiempoFinal.toString()} segundos y tu puntuación es ${puntuacion.toString()}`;
        gameState = 0;
        return handlerInput.responseBuilder
        .speak(speakOutput)
        .reprompt(repromtText)
        .getResponse();
    }
};

Ответы [ 2 ]

1 голос
/ 29 сентября 2019

Вы можете добавить новый атрибут сеанса с именем state и проверить его в вашей функции canHandle.

В вашем случае после обработки RandomLetterIntentHandler вы можете установить state на answer или любое другое имя, которое, по вашему мнению, лучше всего подходит, а затем в функции WaitAnswerIntentHandler canHandle проверить, если state это answer.Если это так, обработайте запрос и установите state в значение по умолчанию или удалите его.Таким образом, WaitAnswerIntentHandler будет вызываться только после RandomLetterIntentHandler.

Более конкретный пример можно найти в игре alexa sdk repo ' High Low '.

0 голосов
/ 29 сентября 2019

Это лучшее решение от официального разработчика Amazon.

const Alexa = require('ask-sdk-core');
let hello = false;

const LaunchRequestHandler = {
  canHandle(handlerInput) {
    return handlerInput.requestEnvelope.request.type === 'LaunchRequest';
  },
  handle(handlerInput) {
    const speechText = 'Welcome to the Alexa Skills Kit, you can say hello!';

    return handlerInput.responseBuilder
      .speak(speechText)
      .reprompt(speechText)
      .getResponse();
  },
};

const HelloWorldIntentHandler = {
  canHandle(handlerInput) {
    return handlerInput.requestEnvelope.request.type === 'IntentRequest'
      && handlerInput.requestEnvelope.request.intent.name === 'HelloWorldIntent';
  },
  handle(handlerInput) {
    hello = true;
    const speechText = `Hello`;
    return handlerInput.responseBuilder
      .speak(speechText)
      .reprompt(speechText)
      .getResponse();
  },
};

const ByeIntentHandler = {
  canHandle(handlerInput) {
    return handlerInput.requestEnvelope.request.type === 'IntentRequest'
      && handlerInput.requestEnvelope.request.intent.name === 'ByeIntent';
  },
  handle(handlerInput) {
    let speechText;
    if (!hello) {
      speechText = 'dont say bye before hello';
      return handlerInput.responseBuilder
      .speak(speechText)
      .reprompt(speechText)
      .getResponse();
    }
    speechText = `Bye`;
    return handlerInput.responseBuilder
      .speak(speechText)
      .reprompt(speechText)
      .getResponse();
  },
};

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

      return handlerInput.responseBuilder
      .speak('I do not understand what you say')
      .getResponse();
  },
};

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

const skillBuilder = Alexa.SkillBuilders.custom();

exports.handler = skillBuilder
  .addRequestHandlers(
    LaunchRequestHandler,
    HelloWorldIntentHandler,
    ByeIntentHandler,
    SessionEndedRequestHandler
  )
  .addErrorHandlers(ErrorHandler)
  .lambda();
...