alexa-skills-kitalexa-slot

how to make slots output different responses


Doing some smart home skill development and my Intent utterance is "how long until my battery is {state}" State being either empty or full. I know I could do this with different intents but I wont want to have two many intents as I already have many. I basically want the user to say either full or empty in place of {state}. and then from there, depending on their answer, give different answers for full or empty. I haven't found much online so i hope you guys can help. Im also new to code.


Solution

  • You should create a slot for your battery state:

    {
      "name": "BatteryState",
      "values": [
          {
              "id": "empty",
              "name": {
                  "value": "empty"
              }
          },
          {
              "id": "full",
              "name": {
                  "value": "full"
              }
          }
      ]
    }
    

    You can create it by yourself in the UI or paste in types collection in JSON editor.

    Then use created slot in your intent

    {
      "name": "BatteryStateIntent",
      "slots": [
          {
              "name": "batteryState",
              "type": "BatteryState"
          }
      ],
      "samples": [
          "how long until my battery is {batteryState}"
      ]
    }
    

    You can create it by yourself in the UI or paste in intents collection in JSON editor.

    Then in the code:

    const BatteryStateIntentHandler = {
      canHandle(handlerInput) {
        return (
          Alexa.getRequestType(handlerInput.requestEnvelope) === "IntentRequest" &&
          Alexa.getIntentName(handlerInput.requestEnvelope) === "BatteryStateIntent"
        );
      },
      handle(handlerInput) {
        const batteryStatus =
          handlerInput.requestEnvelope.request.intent.slots.batteryState.value;
        let speakOutput = "";
        if (batteryStatus === "full") {
          const timeToFull = 10; // or some sophisticated calculations ;)
          speakOutput += `Your battery will be full in ${timeToFull} minutes!`;
        } else if (batteryStatus === "empty") {
          const timeToEmpty = 5; // or some sophisticated calculations ;)
          speakOutput += `Your battery will be full in ${timeToEmpty} minutes!`;
        } else {
          speakOutput += "I don't know this status";
        }
    
        return handlerInput.responseBuilder
          .speak(speakOutput)
          .reprompt(speakOutput)
          .getResponse();
      },
    };
    

    Make sure you used the same intent name as in the builder. And at the end, add created intent handler to request handlers:

    exports.handler = Alexa.SkillBuilders.custom()
      .addRequestHandlers(
        BatteryStateIntentHandler,
        // ...
      )
      .lambda();