Search code examples
alexa-skills-kit

Amazon Alexa "SpeechletResponse was null"


This is not through any third-party code editor. This is through the Alexa Developer Console.

I am trying to create a skill for my school to get the current updates if the school is closed, two-hour delay, etc.

This is the code that handles it:

const GetCurrentUpdateHandler = {
    canHandle(handlerInput) {
        return Alexa.getRequestType(handlerInput.requestEnvelope) === 'IntentRequest'
            && Alexa.getIntentName(handlerInput.requestEnvelope) === 'GetCurrentUpdate'
    },
    handle(handlerInput) {
        let speakOutput = ""
        axios.get("District Link")
            .then(res => {
                const dom = new JSDOM(res.data)
                const msgs = dom.window.document.getElementById("onscreenalert-ctrl-msglist")
                const useless = msgs.querySelectorAll("input")
                useless.forEach(function (el) {
                    el.parentNode.removeChild(el)
                })
                const message = msgs.innerText
                if (message === undefined) {
                    console.log("no messages")
                    speakOutput = "There are currently no messages."
                    finishReq(speakOutput)
                } else {
                    console.log("message")
                    speakOutput = `Here is a message from District. ${msgs.innerText}`
                    finishReq(speakOutput)
                }
            })
        function finishReq(output) {
            return handlerInput.responseBuilder
                .speak(output)
                .getResponse();
        }
    }
}

I am getting a "SpeechletResponse was null" error.


Solution

  • Two things...

    1. Because of the promise on axios.get, the function itself could be terminating and returning nothing before the promise is fulfilled.

      Consider using async-await to pull the results of the axios.get call synchronously.

    2. finishReq returns the response builder to the function that called it, not as the result of the handler. So even if you use async-await, wrapping the handler return in a function redirects it and doesn't return it to the SDK for transmission to Alexa.

    So:

    async handle(handlerInput)
    const res = await axios.get(...)
    

    Unwrap the .then and finishReq code so it's all in the handler scope.