Search code examples
node.jsalexa-skills-kit

Create an array of cards in Alexa Skill and show them


I'm trying to make a list withSimpleCard () of the items my API receives, but I haven't found anything on the internet saying this is possible.

What I managed to do is Alexa speak all the items I found.

Follow my code.

const ProcuraProdutoIntentHandler = {
canHandle(handlerInput) {
    return Alexa.getRequestType(handlerInput.requestEnvelope) === 'IntentRequest'
        && Alexa.getIntentName(handlerInput.requestEnvelope) === 'ProcuraProduto';
},
async handle(handlerInput) {
    let speakOutput = "This is the default message.";
    let totalResult = 0;
    let slotValue = handlerInput.requestEnvelope.request.intent.slots.produto.value;
    const titleCard = `Procurando por ${slotValue}, aguarde...`
    let names = '';
    await axios.get(`https://myapi.com/search=${slotValue}`).then((response) =>{
        if(response.data.length === 0){
            totalResult = `Não encontrei nenhum resultado.`
        //Se encontrar apenas 1 resultado
        } else if(response.data.length === 1){
            response.data.map(item => {
              names += item.name;
            });
            console.log("Produtos ", names);
            totalResult = `Eu encontrei ${response.data.length} resultado.`
        //Se encontrar mais de 1 resultado
        } else {
            response.data.map(item => {
              names += `${item.name} <break time="2s"/>, `;
            });
            console.log("Produtos ", names);
            totalResult = `Eu encontrei ${response.data.length} resultados.`
        }
    }).catch((erro) =>{
        speakOutput = 'Ocorreu um erro. Tente novamente.';
    })
    const speechText = `<speak> Os produtos que encontrei foram: <break time="1s"/> ${names}</speak>`;

    return handlerInput.responseBuilder
        .speak(speechText)
        .withSimpleCard('Pesquisa concluída!', totalResult)
        //.reprompt('add a reprompt if you want to keep the session open for the user to respond')
        .getResponse();
}
};

How would you loop to create a withSimpleCard for each product found?


Solution

  • withSimpleCard won't help you here since it returns just one element and you want to display a list.

    Instead, you should use Display template feature. Make sure you meet all limitations mentioned in the documentation.

    You can find more information in related article on Alexa Blog.

    And to make things easier - display directive sample from alexa-cookbook (they did some refactoring in the repository and links in the article navigate to 404 page).