mercoledì 23 gennaio 2019

Persistenza delle variabili in Alexa Skills

La persistenza delle variabili in Alexa Skills con NodeJS si ottiene tramite PersistantAttributes che si appoggia su DynamoDB in modo trasparente



In questa prima fase viene settata una variabile (per semplicita' statica) in modo persistente. Se non e' settata crea una nuova stringa. Importante impostare la chiamata come asincrona

Da notare che le variabili sono relative ad un determinato account per cui ogni utente ritrovera' le proprie impostazioni

---------------------------------------------------------------------------
const LaunchRequestHandler = {
  canHandle(handlerInput) {
     return handlerInput.requestEnvelope.request.type === 'LaunchRequest';
    
  },
  
  async handle(handlerInput) {    
    const attributesManager = handlerInput.attributesManager;
    var speechText = "Benvenuto nella skill ";

    const attributes = await attributesManager.getPersistentAttributes() || {};

    if (Object.keys(attributes).length === 0) {
      attributes.nameValue = "Luca";
      attributesManager.setPersistentAttributes(attributes);
      await attributesManager.savePersistentAttributes();
    }else {
      speechText = "Benvenuto  ${attributes.nameValue.toString()}";
    }
    
    return handlerInput.responseBuilder
      .speak(speechText)
      .withShouldEndSession(false)
      .getResponse();
  },
};
---------------------------------------------------------------------------


Con questo codice si puo' richiamare il valore della variabile da altra intent

---------------------------------------------------------------------------
 const attributesManager = handlerInput.attributesManager;
  const attributes = await attributesManager.getPersistentAttributes()
  var speechOutput =  attributes.nameValue.toString();
---------------------------------------------------------------------------

Per salvare i dati e' necessario impostare il nome della tabella in cui sono salvate le variabili e la possibilita' di creare in automatico la tabella ove non esista
---------------------------------------------------------------------------
const skillBuilder = Alexa.SkillBuilders.standard();

exports.handler = skillBuilder
  .addRequestHandlers(
    LaunchRequestHandler,
    YesHandler,
    geo,
    HelpHandler,
    ExitHandler,
    SessionEndedRequestHandler
  )
  .addErrorHandlers(ErrorHandler)
  .withTableName('alexa-data')
  .withAutoCreateTable(true)
  .lambda();
---------------------------------------------------------------------------


Nessun commento:

Posta un commento

Perche' investire su Unix

 Un libro trovato nel libero scambio alla Coop su cio' che poteva essere e non e' stato...interessante la storia su Unix del primo c...