Как я могу учесть, когда пользователь ничего не вводит в Alexa после this.emit («: ask», речь)?

1

Я пишу игру для Alexa, но пользовательский ввод не требуется. Если ответа нет, то игра должна заканчиваться уникальным сообщением оценки пользователя. В настоящее время у меня есть Alexa, предлагающая пользователю вот так.

this.emit(":ask", speech);

Однако, если пользователь не хочет отвечать, Alexa заканчивается без какого-либо сообщения. Я проверил, могу ли я объяснить это в обработчике Stop или Cancel, но программа, похоже, не выходит из этого способа. Как я могу учесть отсутствие ввода и указать сообщение о выходе? Вот мой полный код для справки.

'use strict';
const Alexa = require('alexa-sdk');

//Messages

const WELCOME_MESSAGE = "Welcome to three six nine. You can play three six nine with just me or with friends. Say help for how to play";

const START_GAME_MESSAGE = "OK. I will start!";

const EXIT_SKILL_MESSAGE = "Better luck next time!";

const HELP_MESSAGE = "Three six nine is a game where we take turns counting up from one. If the number is divisible by three, you're going to say quack. If the number has a three, six, or nine anywhere, you're going to say quack";

const speechConsWrong = ["Argh", "Aw man", "Blarg", "Blast", "Boo", "Bummer", "Darn", "D'oh", "Dun dun dun", "Eek", "Honk", "Le sigh",
"Mamma mia", "Oh boy", "Oh dear", "Oof", "Ouch", "Ruh roh", "Shucks", "Uh oh", "Wah wah", "Whoops a daisy", "Yikes"];

const states = {
    START: "_START",
    GAME: "_GAME"
};

//Game Variables
var counter = 1; 
var numPlayers = 1; //By default is one

const handlers = {
    //Game goes straight to play currently 
     "LaunchRequest": function() {
        this.handler.state = states.START;
        this.emitWithState("Start");
     },
    "PlayIntent": function() {
        this.handler.state = states.GAME;
        this.emitWithState("NextNumber");
    },
    "PlayWithFriends": function() { 
         const itemSlot = this.event.request.intent.slots.numFriends.value; 
         numPlayers = itemSlot;
         this.handler.state = states.GAME; 
         this.emitWithState("NextNumber"); 
    },
    "AMAZON.HelpIntent": function() {
        this.response.speak(HELP_MESSAGE).listen(HELP_MESSAGE);
        this.emit(":responseReady");
    },
    "Unhandled": function() {
        this.handler.state = states.START;
        this.emitWithState("Start");
    }
};


//When skill is in START state
const startHandlers = Alexa.CreateStateHandler(states.START,{
    "Start": function() {
        this.response.speak(WELCOME_MESSAGE).listen(HELP_MESSAGE);
        this.emit(":responseReady");
    },
    "PlayIntent": function() {
        this.handler.state = states.GAME;
        this.emitWithState("NextNumber");
    },
     "PlayWithFriends": function() { 
         const itemSlot = this.event.request.intent.slots.Item;
         numPlayers = itemSlot; //set number to slot value
         this.handler.state = states.GAME; 
         this.emitWithState("NextNumber"); 
    },
    "AMAZON.StopIntent": function() {
        this.response.speak(EXIT_SKILL_MESSAGE);
        this.emit(":responseReady");
    },
    "AMAZON.CancelIntent": function() {
        this.response.speak(EXIT_SKILL_MESSAGE);
        this.emit(":responseReady");
    },
    "AMAZON.HelpIntent": function() {
        this.response.speak(HELP_MESSAGE).listen(HELP_MESSAGE);
        this.emit(":responseReady");
    },
    "Unhandled": function() {
        this.emitWithState("Start");
    }
});


const gameHandlers = Alexa.CreateStateHandler(states.GAME,{
    "Game": function() {
        let speech = ""; 
        let turnDivisible = (counter-1) % (numPlayers+1); 
        if (turnDivisible != 0) { 
            this.emit(":ask", speech);
        } else { 
            this.emitWithState("NextNumber");    
        }
    },
    "NextNumber": function() {

        //If the counter is at 1, the game is beginning with Alexa 
        if (counter == 1) {
            this.attributes.response = START_GAME_MESSAGE + " ";
        } else { 
            this.attributes.response = " ";    
        }

        //check if number contains three, six, nine or divisible by nine
        let speech = " ";
        let divisible = counter % 3; 
        let counterString = counter.toString(); 
        if (counterString.indexOf('3') > - 1 || counterString.indexOf('6') > - 1 || counterString.indexOf('9') > - 1 || divisible === 0) {
            speech = this.attributes.response + "quack"; 
        } else { 
            speech = this.attributes.response + counter;
        }

        //update variables 
        counter++;
        this.emit(":ask", speech);
    },
    "AnswerIntent": function() {
        let correct = checkAnswer(this.event.request.intent.slots, counter);
        //Game continues when you get the correct value
        if (correct) {
            counter++;
            this.emitWithState("Game");
        }
        //Game ends when the value is incorrect
        else {
            let speechOutput = endGame();
            this.response.speak(speechOutput);
            this.emit(":responseReady"); 
        }
    },
    "AMAZON.StopIntent": function() {
        this.response.speak(EXIT_SKILL_MESSAGE);
        endGame();
        this.emit(":responseReady");
    },
    "AMAZON.CancelIntent": function() {
        this.response.speak(EXIT_SKILL_MESSAGE);
        endGame();
        this.emit(":responseReady");
    },
    "AMAZON.HelpIntent": function() {
        this.response.speak(HELP_MESSAGE).listen(HELP_MESSAGE);
        this.emit(":responseReady");
    },
    "Unhandled": function() {
        this.emitWithState("Game");
    }
});

function checkAnswer(slots, value)
{
        for (var slot in slots) {  
        if (slots[slot].value !== undefined)
        {
            let slotValue = slots[slot].value.toString().toLowerCase(); 
            let counterValue = value.toString();

            let divisible = value % 3; 
            if (divisible === 0) { 
                if (slotValue == "quack") { 
                    return true;    
                } else { 
                    return false;    
                }
            }

            else if (counterValue.indexOf('3') > - 1 || counterValue.indexOf('6') > - 1 || counterValue.indexOf('9') > - 1) {
                if (slotValue == "quack") {
                    return true; 
                } else { 
                    return false; 
                }
            }

            else if (slotValue == value.toString().toLowerCase())
            {
                return true;
            } 
            else 
            { 
            return false; 
            }
        }
}
    return false;
}


function endGame() { 
    let speechOutput = "";
    let response = getSpeechCon(false);
    response += "your final score is " + counter;
    speechOutput = response + ". " + EXIT_SKILL_MESSAGE;
    counter = 1; 
    numPlayers = 1; 
    return speechOutput; 
}

function getSpeechCon(type) {
    return "<say-as interpret-as='interjection'>" + speechConsWrong[getRandom(0, speechConsWrong.length-1)] + " </say-as><break strength='strong'/>";
}

function getRandom(min, max) {
    return Math.floor(Math.random() * (max-min+1)+min);
}

exports.handler = (event, context) => {
    const alexa = Alexa.handler(event, context);
    //alexa.appId = APP_ID;
    alexa.registerHandlers(handlers, startHandlers, gameHandlers);
    alexa.execute();
};
Теги:
aws-lambda
alexa
alexa-skill
echo

1 ответ

0

Вы должны искать SessionEndedRequest, когда сессия закончится, чтобы вы могли слушать это и соответственно реагировать. Он должен быть request.type == 'SessionEndedRequest'. Как и LaunchRequest, на самом деле это не намерение, и я вижу, что вы уже обрабатываете LaunchRequest, поэтому его следует легко добавить.

Ещё вопросы

Сообщество Overcoder
Наверх
Меню