How Do I Resolve Alexa Stop, Cancel Intents Not Working

i am using a mish mash of scripts as i do not know coding to be honest, and its working for the most part, but i am struggling with stop, help and cancel during the welcome speech, stop/cancel works ok once you get to the next part, but during the welcome speech, exanmples

User: "Alexa open breckland weather" Skill: "Welcome to Breckland Weather. Please ask me for the weather, heres a hint, whats the weather like or whats the current conditions." User: "stop" / User: "cancel" / User: "help" Skill: "There was a problem with the requested skill's response"

The intents are there and i added utterances in case but still the same so i feel theres sommat in the code thats not right, probably most of it lol, please can one of you kind soles peruse at your leisure and see if you can shed a little light?

exports.handler = (event, context, callback) => {
    try {
        //console.log(`event.session.application.applicationId=${event.session.application.applicationId}`);
        
        //if (event.session.application.applicationId !== APP_ID) {
        //     callback('Invalid Application ID');
        //}
        

        if (event.session.new) {
            onSessionStarted({ requestId: event.request.requestId }, event.session);
        }

        if (event.request.type === 'LaunchRequest') {
            onLaunch(event.request,
                event.session, (sessionAttributes, speechletResponse) => {
                    callback(null, buildResponse(sessionAttributes, speechletResponse));
                });
        } else if (event.request.type === 'IntentRequest') {
            onIntent(event.request,
                event.session,
                (sessionAttributes, speechletResponse) => {
                    callback(null, buildResponse(sessionAttributes, speechletResponse));
                });
        } else if (event.request.type === 'SessionEndedRequest') {
            onSessionEnded(event.request, event.session);
            callback();
        }
    } catch (err) {
        callback(err);
    }
};


const isDebug = false; 
const APP_ID = 'amzn1.ask.skill.d31840b5-27f2-4f07-9e19-ec0c73d78b39';
const url_weather = '
const APP_NAME = 'Breckland Weather';
const STR_REPROMPT = '\nPlease ask me for the weather, heres a hint, whats the weather like or whats the current conditions.';
const HELP_MESSAGE = 'You can say whats the weather like, or, you can say exit... What can I help you with?';
const HELP_REPROMPT = 'What can I help you with?';
const STOP_MESSAGE = 'Goodbye!';


function getWeather(intent, session, callback, numLetters) {
    


    let speechOutput = ''; 
    let cardTitle = 'Weather output';
    getWebRequest(url_weather, function webResonseCallback(err, data) {
        if (err) {            
            speechOutput = `DOH! somethings done gone bad, self destuct in 3 2 ah, false alarm, still broken though, carry on.`;
            callback({}, buildSpeechletResponse(cardTitle, speechOutput, STR_REPROMPT));     
        } else {
            //if (isDebug) {"SolveAnagram::data = " + console.log(data)};
            speechOutput = data;            
            callback({}, buildSpeechletResponse(cardTitle, speechOutput,  STR_REPROMPT));
        }    
    });
    
    
}

//Simple welcome intent handler
function getWelcomeResponse(callback) {
    console.log("START session");
    if (isDebug) {console.log("getWelcomeResponse()")}
        
    const cardTitle = APP_NAME;
    const speechOutput = 'Welcome to '+APP_NAME+'. '+ STR_REPROMPT;
        
    // If the user either does not reply to the welcome message or says something that is not
    // understood, they will be prompted again with this text.
    const repromptText = STR_REPROMPT;
    const shouldEndSession = false;

    callback({}, buildSpeechletResponse(cardTitle, speechOutput, repromptText, shouldEndSession));
}


//My effort of code

const handlers = {
    'LaunchRequest': function () {
        // this.emit('myIntent');
        this.emit(':tell', '2 Hello, what would you like to do?');
    },
    'AMAZON.HelpIntent': function () {
        const speechOutput = HELP_MESSAGE;
        const reprompt = HELP_REPROMPT;

        this.response.speak(speechOutput).listen(reprompt);
        this.emit(':responseReady');
    },
    'AMAZON.CancelIntent': function () {
        this.response.speak(STOP_MESSAGE);
        this.emit(':responseReady');
    },
    'AMAZON.StopIntent': function () {
        this.response.speak(STOP_MESSAGE);
        this.emit(':responseReady');
    },
};





//Simple end session intent handler
function handleSessionEndRequest(callback) {
    console.log("END session");
    
    const cardTitle = 'Goodbye';
    const speechOutput = 'Thanks for using '+APP_NAME+'.';
    const shouldEndSession = false;

    callback({}, buildSpeechletResponse(cardTitle, speechOutput, null, shouldEndSession));
}




function buildSpeechletResponse(title, output, repromptText, shouldEndSession) {
    if (isDebug) {console.log(`buildSpeechletResponse(title:${title}, shouldEndSession:${shouldEndSession}, reprompt:${repromptText})`)}
    return {
        outputSpeech: {
            type: 'PlainText',
            text: output,
        },
        card: {
            type: 'Simple',
            title: `${title}`,
            content: `${output}`,
        },
        reprompt: {
            outputSpeech: {
                type: 'PlainText',
                text: repromptText,
            },
        },
        shouldEndSession,
    };
}

function buildResponse(sessionAttributes, speechletResponse) {
    return {
        version: '2.0',
        response: speechletResponse,
        sessionAttributes: sessionAttributes,        
    };
}


//----------------- Web service helper ----------------------//
var http = require('http');
 
function getWebRequest(url,doWebRequestCallBack) {
    try
    {
        http.get(url, function (res) {
            var webResponseString = '';
            if (isDebug) {console.log('Status Code: ' + res.statusCode)}
     
            if (res.statusCode != 200) {
                doWebRequestCallBack(new Error("Non 200 Response"));
                return;
            }
     
            res.on('data', function (data) {
                webResponseString += data;
            });
     
            res.on('end', function () {
                //if (isDebug) {console.log('getWebRequest::Got some data: '+ webResponseString)};     
                
                //the weather isn't JSON so just return the string
                //var webResponseObject = JSON.parse(webResponseString);   
                doWebRequestCallBack(null, webResponseString);
                
                
            });
        }).on('error', function (e) {
            if (isDebug) {console.log("Communications error: " + e.message)}
            doWebRequestCallBack(new Error(e.message));
        });
    } 
    catch(err)
    {
        doWebRequestCallBack(new Error(err.message));
    }
}



// --------------- Events -----------------------

/**
 * Called when the session starts.
 */
function onSessionStarted(sessionStartedRequest, session) {
    //console.log(`onSessionStarted requestId=${sessionStartedRequest.requestId}, sessionId=${session.sessionId}`);
}

/**
 * Called when the user launches the skill without specifying what they want.
 */
function onLaunch(launchRequest, session, callback) {
    //console.log(`onLaunch requestId=${launchRequest.requestId}, sessionId=${session.sessionId}`);

    // Dispatch to your skill's launch.
    getWelcomeResponse(callback);
}


/**
 * Called when the user specifies an intent for this skill.
 */
function onIntent(intentRequest, session, callback) {
    
    const intent = intentRequest.intent;
    const intentName = intentRequest.intent.name;
    
    console.log("  ");
    console.log("== New Intent ==");
    console.log(`onIntent(${intentName})`);

    if (intentName === 'GetWeather') {
        getWeather(intent, session, callback,1); 
    } 
    
}

/**
 * Called when the user ends the session.
 * Is not called when the skill returns shouldEndSession=true.
 */
function onSessionEnded(sessionEndedRequest, session) {
    //console.log(`onSessionEnded requestId=${sessionEndedRequest.requestId}, sessionId=${session.sessionId}`);
    // Add cleanup logic here
}

1 Answer

Your design pattern is quite confusing. But I see where your problem is. You are not using your handlers object for handling intent requests at all. According to your design pattern you can make changes as follows:

/**
 * Called when the user specifies an intent for this skill.
 */
function onIntent(intentRequest, session, callback) {

    const intent = intentRequest.intent;
    const intentName = intentRequest.intent.name;

    console.log("  ");
    console.log("== New Intent ==");
    console.log(`onIntent(${intentName})`);

    if (intentName === 'GetWeather') {
        getWeather(intent, session, callback,1); 
    }else if(intentName === 'AMAZON.StopIntent'){
        getStopResponse(intent, session, callback,1)
    }else if(intentName === 'AMAZON.HelpIntent'){
        getHelpResponse(intent, session, callback,1)
    }

}

And response builder function as follows:

//Simple welcome intent handler
function getStopResponse(callback) {
    console.log("START session");
    if (isDebug) {console.log("getStopResponse()")}

    const cardTitle = APP_NAME;
    const speechOutput = STOP_MESSAGE
    const repromptText = STOP_MESSAGE;
    const shouldEndSession = true;

    callback({}, buildSpeechletResponse(cardTitle, speechOutput, repromptText, shouldEndSession));
}

Similar one would go for getHelpResponse(). I will leave that up to you.

Tell me if this helps you.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

David Miller

David Miller

Executive Financial & Market Analyst

David Miller brings 15 years of experience in global economics, personal finance strategy, and market dynamics. He specializes in turning complex economic trends into actionable insights for everyday readers.

Share this article
Twitter Facebook Pinterest