Ti ringraziamo per la visita. Questa pagina è per il momento disponibile solo in inglese.

GameEngine Interface Reference

The Game Engine interface enables your skill to receive input from Echo Buttons. This interface works with compatible Amazon Echo devices only.

Your skill uses the Game Engine interface by sending directives that start and stop the Input Handler, which is the component within Alexa that sends your skill Echo Button events when conditions that you define are met (for example, the user pressed a certain sequence of buttons).

Configuring Your Skill to Use the Game Engine Interface

To use Game Engine directives, you must specify the Game Engine interface in your skill metadata. If you want your skill to control Echo Buttons in addition to receiving input from them, include the Gadget Controller interface also.

Game Engine Directives

The Game Engine interface provides the following directives:

Directive Description
GameEngine.StartInputHandler Sends Alexa a command to configure Echo Button events and start the Input Handler, which translates button presses into Echo Button events. For an example of how to assemble this directive using the Alexa Skills Kit (ASK) SDKs, see StartInputHandler Example.
GameEngine.StopInputHandler Sends Alexa a command to stop sending Echo Button press events to your skill. For an example of how to assemble this directive using the ASK SDKs, see StopInputHandler Example.

When including a directive in your response, set the type property to the directive that you want to send. Include directives in the directives array in your response. The following is the format of a request with a GameEngine.StartInputHandler directive in it.

{
  "version": "1.0",
  "sessionAttributes": {},
  "response": {
    "outputSpeech": {},
    "card": {},
    "reprompt": {},
    "directives": [
    {
      "type": "GameEngine.StartInputHandler",
      "timeout": 5000,
      "proxies": [],
      "recognizers": {},
      "events": {}
    }
    ],
    "shouldEndSession": true
  }
}

For the full response format, see Response Format in the JSON Interface Reference for Custom Skills.

StartInputHandler Directive

Configures and starts the Input Handler to send Echo Button events to your skill.

For an example of how to assemble this directive using the Alexa Skills Kit (ASK) SDKs, see StartInputHandler Example.

The following is the basic form of the StartInputHandler directive. For examples, see Receive Echo Button Events and Define Echo Button Events.

{
  "type": "GameEngine.StartInputHandler",
  "timeout": 5000,
  "proxies": [],
  "recognizers": {},
  "events": {}
}
Parameter Description Type Required
type Must be set to GameEngine.StartInputHandler. string yes
timeout The maximum run time for this Input Handler, in milliseconds. Although this parameter is required, you can specify events with conditions on which to end the Input Handler earlier. Minimum value: 0. Maximum value: 90,000 ms (90 seconds). number yes
proxies Names for unknown gadget IDs to use in recognizers, allocated on a first-come, first-served basis. array no
recognizers Conditions that, at any moment, are either true or false. You use recognizers when you specify the conditions under which your skill is notified of Echo Button input. Minimum number of recognizers: 0 (leave the object empty). Maximum number of recognizers: 20. object yes
events The logic that determines when your skill is notified of Echo Button input. Minimum number of events: 1. Maximum number of events: 32. object yes

recognizers object

The recognizers object contains one or more objects that represent different types of recognizers: the patternRecognizer, deviationRecognizer, or progressRecognizer. In addition to these recognizers, there is a predefined timed out recognizer. All of these recognizers are described next.

For more information about how to use recognizers, see Define Echo Button Events.

The following example is a recognizers object that contains two recognizers. Both recognizers are of type patternRecognizer. The first recognizer detects button presses and the second recognizer detects button releases.

"recognizers": 
{  
   "button_down_recognizer": 
    {
        "type": "match",
        "fuzzy": false,
        "anchor": "end",
        "pattern": [
         {
           "action": "down"
         }
        ]
     },
    "button_up_recognizer": {
        "type": "match",
        "fuzzy": false,
        "anchor": "end",
        "pattern": [
         {
           "action": "up"
         }
        ]
    }
}
patternRecognizer object

This recognizer is true when all of the specified events have occurred in the specified order.

Parameter Description Type Required

type

Must be set to match.

string

yes

anchor

Where the pattern must appear in the history of this input handler. Possible values:

  • start: (Default) The first event in the pattern must be the first event in the history of raw Echo Button events.
  • end: The last event in the pattern must be the last event in the history of raw Echo Button events.
  • anywhere: The pattern may appear anywhere in the history of raw Echo Button events.

enum

no

fuzzy

When true, the recognizer will ignore additional events that occur between the events specified in the pattern.

boolean

no

gadgetIds

The gadget IDs of the Echo Buttons to consider in this pattern recognizer.

array

no

actions

The actions to consider in this pattern recognizer. All other actions will be ignored.

array

no

pattern

An object that provides all of the events that need to occur, in a specific order, for this recognizer to be true. Omitting any parameters in this object means "match anything".

array

yes

pattern.gadgetIds

A whitelist of gadgetIds that are eligible for this match.

array

no

pattern.colors

A whitelist of colors that are eligible for this match.

array

no

pattern.action

The specific action name that must match. Possible values:

  • down: A button is pressed down.
  • up: A button is released.
  • silence: There is no action on the buttons.

enum

no

pattern.repeat

The number of times that the specified action must occur to be considered complete.

number

no

deviationRecognizer object

The deviation recognizer returns true when another specified recognizer reports that the player has deviated from its expected pattern.

Parameter Description Type Required
type Must be set to deviation. string yes
recognizer The name of the recognizer that defines a pattern that must not be deviated from. string yes
progressRecognizer object

This recognizer consults another recognizer for the degree of completion, and is true if that degree is above the specified threshold. The completion parameter is specified as a decimal percentage.

Parameter Description Type Required
type Must be set to progress. string yes
recognizer The name of a recognizer for which to track the progress. string yes
completion The completion threshold, as a decimal percentage, of the specified recognizer before which this recognizer becomes true. number yes
timed out recognizer object

This recognizer is true when the Input Handler has reached the end of the timeout period specified using StartInputHandler. This recognizer is predefined and cannot be overridden.

events object

The events object is where you define the conditions that must be met for your skill to be notified of Echo Button input. You must define at least one event.

The following is an example of an event defined within an events object. For examples, see Define Echo Button Events.

{
  "myEventName": {
    "meets": [ "a recognizer", "a different recognizer" ],
    "fails": [ "some other recognizer" ],
    "reports": "history",
    "shouldEndInputHandler": true,
    "maximumInvocations": 1,
    "triggerTimeMilliseconds": 1000    
  }
}

The fields are as follows.

Parameter Description Type Required

meets

Specifies that this event will be sent when all of the recognizers are true.

array

yes

fails

Specifies that this event will not be sent if any of these recognizers are true.

array

no

reports

Specifies what raw button presses to put in the inputEvents field of the event. Possible values:

  • history: All button presses since this Input Handler was started.
  • matches: Just the button presses that contributed to this event (that is, were in the recognizers).
  • nothing: The inputEvents list will be empty.

enum

no

shouldEndInputHandler

Whether the Input Handler should end after this event fires. If true, the Input Handler will stop and no further events will be sent to your skill unless you call StartInputHandler again.

boolean

yes

maximumInvocations

Enables you to limit the number of times that the skill is notified about the same event during the course of the Input Handler. The default value is 1. This property is mutually exclusive with triggerTimeMilliseconds. Minimum: 1. Maximum: 2,048.

number

no

triggerTimeMilliseconds

Adds a time constraint to the event. Instead of being considered whenever a raw button event occurs, an event that has this parameter will only be considered once at triggerTimeMilliseconds after the Input Handler has started. Because a time-triggered event can only fire once, the maximumInvocations value is ignored. Omit this property entirely if you do not want to time-constrain the event. Minimum: 0. Maximum: 300,000.

number

no

StopInputHandler Directive

Stops Echo Button events from being sent to your skill.

The following is the basic form of the StopInputHandler directive. For an example of how to assemble this directive using the ASK SDKs, see StopInputHandler Example.

{
  "type": "GameEngine.StopInputHandler",
  "originatingRequestId": "amzn1.echo-api.request.406fbc75-8bf8-4077-a73d-519f53d172a4"
}
Parameter Description Type Required
type Set to GameEngine.StopInputHandler string yes
originatingRequestId Provides the requestId of the request to which you responded with a StartInputHandler directive. string yes

Game Engine Requests

This section contains the types of requests that Alexa might send your skill when you use the Game Engine interface.

InputHandlerEvent Request

GameEngine sends the following requests to notify your skill about Echo Button events:

Request Type Description
GameEngine.InputHandlerEvent Sent when the conditions of an Echo Button event that your skill defined were met.

The form of a GameEngine.InputHandlerEvent request is as follows.

{
  "version": "1.0",
  "session": {
    "application": {},
    "user": {}
  }, 
  "request": {
      "type": "GameEngine.InputHandlerEvent",  
      "requestId": "amzn1.echo-api.request.406fbc75-8bf8-4077-a73d-519f53d172a4",
      "timestamp": "2017-08-18T01:29:40.027Z",
      "locale": "en-US",
      "originatingRequestId": "amzn1.echo-api.request.406fbc75-8bf8-4077-a73d-519f53d172d6",
      "events": [
        {       
          "name": "myEventName",
          "inputEvents": [
            {
              "gadgetId": "someGadgetId1",
              "timestamp": "2017-08-18T01:32:40.027Z",
              "action": "down",
              "color": "FF0000"
            }
          ]
        }
      ]
   }
}

For the full request format, see Request Format in the JSON Interface Reference for Custom Skills.

Parameters
Parameter Description Type
type GameEngine.InputHandlerEvent string
requestId Represents a unique identifier for the specific request. string
timestamp Provides the date and time when Alexa sent the request as an ISO 8601 formatted string. Used to verify the request when hosting your skill as a web service. string
locale A string indicating the user's locale. For example: en-US. string
originatingRequestId The requestId of the request to which your skill responded with a StartInputHandler directive. You should store that requestId to use as a filter here to reject any older stray asynchronous InputHanderEvents that show up after you've started a new Input Handler. string
events A list of events sent from the Input Handler. Each event that you specify will be sent only once to your skill as it becomes true. Note that in any InputHandlerEvent request one or more events may have become true at the same time. array
events.name The name of the event as you defined it in your GameEngine.StartInputHandler directive. string
events.inputEvents A chronologically ordered report of the raw Button Events that contributed to this Input Handler Event. array
events.inputEvents.gadgetId The permanent identifier of the Echo Button in question. It matches the gadgetId that you will have discovered in roll call. string
events.inputEvents.timestamp The event's original moment of occurrence, in ISO format. string
events.inputEvents.action Either "down" for a button pressed or "up" for a button released. enum
events.inputEvents.color The hexadecimal RGB values of the button LED at the time of the event. string
events.inputEvents.feature For gadgets with multiple features, this is the feature that the event represents. Echo Buttons have one feature only, so this is always press. string

Valid Response Types

Your skill is not required to return a response to GameEngine requests. However, if your skill does respond, Alexa handles the response similarly to how it handles responses to intent requests, with the following differences:

  • If there is a card in the response, Alexa will not display the card in the Alexa app. It will only display the card on devices with screens, like the Echo Show.
  • Alexa will ignore the shouldEndSession flag provided in the response. That is, a response to a GameEngine request cannot end the skill session.
  • If there is an error in the response, the error is reported back to the skill as a System.ExceptionEncountered error and will not end the session.

System.ExceptionEncountered Request

If a GameEngine directive that you send fails (for example, you send an invalid Input Handler definition), then your skill will be invoked with a standard System.ExceptionEncountered request. Any directives included in the response are ignored.

{
  "type": "System.ExceptionEncountered",
  "requestId": "string",
  "timestamp": "string",
  "locale": "string",
  "error": {
    "type": "string",
    "message": "string"
  },
  "cause": {
    "requestId": "string"
  }
}

Parameters

Parameter Description Type
type System.ExceptionEncountered string
requestId A unique identifier for the specific request. string
timestamp Provides the date and time when Alexa sent the request as an ISO 8601 formatted string. Used to verify the request when hosting your skill as a web service. string
locale A string indicating the user's locale. For example: en-US. string
error An object with error information. object
error.type The specific type of error (INVALID_RESPONSE, DEVICE_COMMUNICATION_ERROR, INTERNAL_ERROR). string
error.message A description of the error the device has encountered. string
cause.requestId The requestId for the request that caused the error. string

Valid Response Types

Your skill cannot return a response to System.ExceptionEncountered.

Examples

This section provides examples of StartInputHandler and StopInputHandler directives and how you might assemble them using the ASK SDKs. It also provides an example of receiving and parsing an Input Handler event.

For complete sample skills, see Hello Buttons and Color Changer in GitHub.

Start Input Handler Example

This example configures an Input Handler to notify the skill when the user presses or releases a button, or the Input Handler times out, which is in thirty seconds.

This example also shows how to save the request ID of the original request to the session attributes. This request ID serves as the ID of the Input Handler in case you ever need to explicitly stop the Input Handler with StopInputHandler (see the tab for the Node.js SDK or Java SDK in the Stop Input Handler example).

Copied to clipboard.

{
    "outputSpeech": {
        "type": "SSML",
        "ssml": "<speak>This directive configures the Input Handler to send an event if the user presses or releases a button, or the Input Handler reaches its 30-second timeout. <audio src=\"https://s3.amazonaws.com/ask-soundlibrary/foley/amzn_sfx_rhythmic_ticking_30s_01.mp3\"/></speak>"
    },
    "shouldEndSession": false,
    "directives": [
        {
            "type": "GameEngine.StartInputHandler",
            "timeout": 30000,
            "recognizers": {
                "buttonDownRecognizer": {
                    "type": "match",
                    "fuzzy": false,
                    "anchor": "end",
                    "pattern": [
                        {
                            "action": "down"
                        }
                    ]
                },
                "buttonUpRecognizer": {
                    "type": "match",
                    "fuzzy": false,
                    "anchor": "end",
                    "pattern": [
                        {
                            "action": "up"
                        }
                    ]
                }
            },
            "events": {
                "buttonDownEvent": {
                    "meets": [
                        "buttonDownRecognizer"
                    ],
                    "reports": "matches",
                    "shouldEndInputHandler": false
                },
                "buttonUpEvent": {
                    "meets": [
                        "buttonUpRecognizer"
                    ],
                    "reports": "matches",
                    "shouldEndInputHandler": false
                },
                "timeoutEvent": {
                    "meets": [
                        "timed out"
                    ],
                    "reports": "history",
                    "shouldEndInputHandler": true
                }
            }
        }
    ]
}

Copied to clipboard.

This sample code uses the Alexa Skills Kit SDK for Node.js (v2).

const StartInputIntentHandler = {
  canHandle(handlerInput) {
    return handlerInput.requestEnvelope.request.type === 'IntentRequest'
      && handlerInput.requestEnvelope.request.intent.name === 'StartInputHandlerIntent';
  },
  handle(handlerInput) {

      // Save the request ID because we'll need it if we explicitly
      // stop this Input Handler using StopInputHandler later.
      const sessionAttributes = handlerInput.attributesManager.getSessionAttributes();
      const { request } = handlerInput.requestEnvelope;
      sessionAttributes.currentInputHandlerId = request.requestId;

      // Set up an Input Handler to notify this skill when the user
      // presses or releases an Echo Button, or the Input Handler
      // times out.
      const response = handlerInput.responseBuilder
          .speak("This directive configures the Input Handler to send an event "
                  + "if the user presses or releases a button, or the Input Handler "
                  + "reaches its 30-second timeout. "
                  + "<audio src=\"https://s3.amazonaws.com/ask-soundlibrary/foley/amzn_sfx_rhythmic_ticking_30s_01.mp3\"/>")
          .withShouldEndSession(false)
          .addDirective({
            'type': 'GameEngine.StartInputHandler',
            'timeout': 30000,
            'recognizers': {
               'buttonDownRecognizer': {
                  'type': 'match',
                  'fuzzy': false,
                  'anchor': 'end',
                  'pattern': [
                      {
                         'action': 'down'
                      }
                   ]
                },
                'buttonUpRecognizer': {
                   'type': 'match',
                   'fuzzy': false,
                   'anchor': 'end',
                   'pattern': [
                       {
                           'action': 'up'
                       }
                    ]
                 }
            },
            'events': {
                'buttonDownEvent': {
                    'meets': [
                       'buttonDownRecognizer'
                    ],
                    'reports': 'matches',
                    'shouldEndInputHandler': false
                },
                'buttonUpEvent': {
                    'meets': [
                       'buttonUpRecognizer'
                    ],
                    'reports': 'matches',
                    'shouldEndInputHandler': false
                },
                'timeoutEvent': {
                    'meets': [
                       'timed out'
                    ],
                    'reports': 'history',
                    'shouldEndInputHandler': true
                }
            }
         })
          .getResponse();

         console.log('===RESPONSE=== '+ JSON.stringify(response));
         return response;

   }
};

Copied to clipboard.

This sample code uses the Alexa Skills Kit SDK for Java.

package com.amazon.ask.buttonsamples.handlers;
import com.amazon.ask.dispatcher.request.handler.HandlerInput;
import com.amazon.ask.dispatcher.request.handler.RequestHandler;
import com.amazon.ask.model.Response;
import static com.amazon.ask.request.Predicates.intentName;
import com.amazon.ask.model.services.gameEngine.*;
import com.amazon.ask.model.interfaces.gameEngine.*;
import java.util.Optional;
import java.util.Collections;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.HashMap;

public class StartInputIntentHandler implements RequestHandler {

    @Override
    public boolean canHandle(HandlerInput handlerInput) {
        return handlerInput.matches(intentName("StartInputHandlerIntent"));
    }

    @Override
    public Optional<Response> handle(HandlerInput handlerInput) {

      // Save the request ID because we'll need it if we explicitly
      // stop this Input Handler using StopInputHandler later.
      String requestId = handlerInput.getRequestEnvelope().getRequest().getRequestId();
      handlerInput.getAttributesManager().setSessionAttributes
                        (Collections.singletonMap("currentInputHandlerId", requestId));

      // Build the pattern that our button down recognizer will use.
      Pattern buttonDownPattern = Pattern.builder()
        .withAction(InputEventActionType.DOWN)
        .build();

      // Build the pattern that our button up recognizer will use.
      Pattern buttonUpPattern = Pattern.builder()
        .withAction(InputEventActionType.UP)
        .build();

      // Build the recognizer that looks for button downs.
      PatternRecognizer buttonDownRecognizer = PatternRecognizer.builder()
        .withFuzzy(false)
        .withAnchor(PatternRecognizerAnchorType.END)
        .withPattern((List<Pattern>)Arrays.asList(buttonDownPattern))
        .build();

      // Build the recognizer that looks for button ups.
      PatternRecognizer buttonUpRecognizer = PatternRecognizer.builder()
        .withFuzzy(false)
        .withAnchor(PatternRecognizerAnchorType.END)
        .withPattern((List<Pattern>)Arrays.asList(buttonUpPattern))
        .build();

       // Put the recognizers into a map.
       HashMap<String, Recognizer> recognizerMap = new HashMap<String, Recognizer>();
       recognizerMap.put("buttonDownRecognizer", buttonDownRecognizer);
       recognizerMap.put("buttonUpRecognizer", buttonUpRecognizer);

      // Define the event that will be triggered by the button down recognizer.
      Event buttonDownEvent = Event.builder()
        .withShouldEndInputHandler(false)
        .withReports(EventReportingType.MATCHES)
        .withMeets((List<String>)Arrays.asList("buttonDownRecognizer"))
        .build();

      // Define the event that will be triggered by the button up recognizer.
      Event buttonUpEvent = Event.builder()
        .withShouldEndInputHandler(false)
        .withReports(EventReportingType.MATCHES)
        .withMeets((List<String>)Arrays.asList("buttonUpRecognizer"))
        .build();

      // Define the event that will be triggered by the time out recognizer.
      Event timeoutEvent = Event.builder()
        .withShouldEndInputHandler(true)
        .withReports(EventReportingType.HISTORY)
        .withMeets((List<String>)Arrays.asList("timed out"))
        .build();

       // Put the events into a map.
       HashMap<String, Event> eventMap = new HashMap<String, Event>();
       eventMap.put("buttonDownEvent", buttonDownEvent);
       eventMap.put("buttonUpEvent", buttonUpEvent);
       eventMap.put("timeoutEvent", timeoutEvent);

      // Assemble an Input Handler directive with the parameters defined above.
      // This directive tells the Input Handler to notify the skill when the user
      // presses or releases a button, or the Input Handler times out.
      StartInputHandlerDirective directive = StartInputHandlerDirective.builder()
        .withTimeout((long)30000)
        .withRecognizers(recognizerMap)
        .withEvents(eventMap)
        .build();

      // Assemble the response.
      Optional<Response> response = handlerInput.getResponseBuilder()
        .withSpeech("This directive configures the Input Handler to send an event "
                     + "if the user presses or releases a button, or the Input Handler "
                     + "reaches its 30-second timeout. "
                     + "<audio src=\"https://s3.amazonaws.com/ask-soundlibrary/foley/amzn_sfx_rhythmic_ticking_30s_01.mp3\"/>")
        .withShouldEndSession(false)
        .addDirective(directive)
        .build();

      // Write the response to CloudWatch.
      String responseLog = response.toString();
      responseLog = responseLog.replace("\n", " ").replace("\r", " ");
      System.out.println("===RESPONSE=== " + responseLog);

      // Return the response.
      return response;

    }
}

Copied to clipboard.

This sample code uses the Alexa Skills Kit SDK for Python.

from ask_sdk_core.dispatch_components import AbstractRequestHandler
from ask_sdk_core.handler_input import HandlerInput
from ask_sdk_core.utils import is_intent_name
from ask_sdk_model import Response
from ask_sdk_model.interfaces.game_engine import StartInputHandlerDirective
from ask_sdk_model.services.game_engine import (
    Event, EventReportingType, PatternRecognizer, Pattern,
    InputEventActionType, PatternRecognizerAnchorType)


class StartInputIntentHandler(AbstractRequestHandler):
    def can_handle(self, handler_input):
        # type: (HandlerInput) -> bool
        return is_intent_name("StartInputHandlerIntent")(handler_input)

    def handle(self, handler_input):
        # type: (HandlerInput) -> Response

        # Save the request ID because we'll need it if we explicitly
        # stop this Input Handler using StopInputHandler later.
        request_id = handler_input.request_envelope.request.request_id
        session_attributes = handler_input.attributes_manager.session_attributes
        session_attributes['currentInputHandlerId'] = request_id

        #  Build the pattern that our button down recognizer will use.
        button_down_pattern = Pattern(action=InputEventActionType.down)

        # Build the pattern that our button up recognizer will use.
        button_up_pattern = Pattern(action=InputEventActionType.up)

        # Build the recognizer that looks for button downs.
        button_down_recognizer = PatternRecognizer(
            fuzzy=False, anchor=PatternRecognizerAnchorType.end,
            pattern=[button_down_pattern])

        # Build the recognizer that looks for button ups.
        button_up_recognizer = PatternRecognizer(
            fuzzy=False, anchor=PatternRecognizerAnchorType.end,
            pattern=[button_up_pattern])

        # Put the recognizers into a map.
        recognize_map = {
            "buttonDownRecognizer": button_down_recognizer,
            "buttonUpRecognizer": button_up_recognizer
        }

        # Define the event that will be triggered by the
        # button down recognizer.
        button_down_event = Event(
            should_end_input_handler=False, reports=EventReportingType.matches,
            meets=["buttonDownRecognizer"])

        # Define the event that will be triggered by the
        # button up recognizer.
        button_up_event = Event(
            should_end_input_handler=False, reports=EventReportingType.matches,
            meets=["buttonUpRecognizer"])

        # Define the event that will be triggered by the
        # time out recognizer.
        time_out_event = Event(
            should_end_input_handler=True, reports=EventReportingType.history,
            meets=["timed out"])

        # Put the events into a map.
        event_map = {
            "buttonDownEvent": button_down_event,
            "buttonUpEvent": button_up_event,
            "timeoutEvent": time_out_event
        }
    
        # Assemble an Input Handler directive with the parameters
        # defined above. This directive tells the Input Handler to
        # notify the skill when the user presses or releases a button,
        # or the Input Handler times out.
        start_inpout_handler_directive = StartInputHandlerDirective(
            timeout=30000, recognizers=recognize_map, events=event_map)

        speech_text = (
            'This directive configures the Input Handler to send an event '
            'if the user presses or releases a button, or the Input Handler '
            'reaches its 30-second timeout. '
            '<audio src="https://s3.amazonaws.com/ask-soundlibrary/foley/'
            'amzn_sfx_rhythmic_ticking_30s_01.mp3"/>')

        # Assemble the response.
        response = handler_input.response_builder.speak(
            speech=speech_text).set_should_end_session(
            False).add_directive(
            start_inpout_handler_directive).response

        # Write the response to CloudWatch.
        print("===RESPONSE===\n {}".format(response))

        # Return the response.
        return response

Stop Input Handler Example

The following directive stops an Input Handler, if one is running. This directive requires the ID of the request to which you responded with a StartInputHandler directive. You can save this request ID as an attribute in the session object. For an example of how to save the request ID, see the tab for the Node.js SDK or Java SDK in the Start Input Handler example.

Copied to clipboard.

{
    "shouldEndSession": false,
    "outputSpeech": {
        "type": "SSML",
        "ssml": "<speak>Stopping the Input Handler, if one was running.</speak>"
    },
    "directives": [
        {
            "type": "GameEngine.StopInputHandler",
            "originatingRequestId": "request-id-that-you-saved"
        }
    ]
}

Copied to clipboard.

This sample code uses the Alexa Skills Kit SDK for Node.js (v2).

const StopInputIntentHandler = {
  canHandle(handlerInput) {
    return handlerInput.requestEnvelope.request.type === 'IntentRequest'
      && handlerInput.requestEnvelope.request.intent.name === 'StopInputHandlerIntent';
  },
   handle(handlerInput) {

      // Retrieve the session attributes, which is where
      // we stored the request ID of the original request
      // that we responded to when we started the Input
      // Handler.
     const sessionAttributes = handlerInput.attributesManager.getSessionAttributes();

     // Start building a response.
     const responseBuilder = handlerInput.responseBuilder;
     responseBuilder.withShouldEndSession(false)
                    .speak("Stopping the Input Handler, if one was running.");

     // If we were able to retrieve an Input Handler's originating
     // request ID from the session attributes, stop the Input Handler
     // with it. If the ID was from an Input Handler that is no longer
     // running, it is ok because in that case the Game Engine will
     // ignore this directive.
     if (sessionAttributes.currentInputHandlerId) {
           // Add the directive.
           responseBuilder.addDirective({
               'type': 'GameEngine.StopInputHandler',
               'originatingRequestId': sessionAttributes.currentInputHandlerId
             });            
     }

      // Build the response.
      const response = responseBuilder.getResponse();

      // Write the response to CloudWatch.
      console.log('===RESPONSE=== '+ JSON.stringify(response));

      // Return the response.
      return response;

   }
};

Copied to clipboard.

This sample code uses the Alexa Skills Kit SDK for Java.

package com.amazon.ask.buttonsamples.handlers;

import com.amazon.ask.dispatcher.request.handler.HandlerInput;
import com.amazon.ask.dispatcher.request.handler.RequestHandler;
import com.amazon.ask.model.Response;
import com.amazon.ask.response.ResponseBuilder;
import com.amazon.ask.model.services.gameEngine.*;
import com.amazon.ask.model.interfaces.gameEngine.*;
import java.util.Optional;

import static com.amazon.ask.request.Predicates.intentName;

public class StopInputIntentHandler implements RequestHandler {

    @Override
    public boolean canHandle(HandlerInput handlerInput) {
        return handlerInput.matches(intentName("StopInputHandlerIntent"));
    }

    @Override
    public Optional<Response> handle(HandlerInput handlerInput) {

      // Retrieve the session attribute that we used to store
      // the request ID of the original request that we responded
      // to when we started the Input Handler.
      String currentInputHandlerId = (String) handlerInput.getAttributesManager().getSessionAttributes().get("currentInputHandlerId");

      // Start building a response.
      ResponseBuilder responseBuilder = handlerInput.getResponseBuilder()
         .withShouldEndSession(false)
         .withSpeech("Stopping the Input Handler, if one was running.");

      // If we were able to retrieve an Input Handler's originating
      // request ID from the session attributes, stop the Input Handler
      // with it. If the ID was from an Input Handler that is no longer
      // running, it is ok because in that case the Game Engine will
      // ignore this directive.
      if (currentInputHandlerId != null) {

      	// Assemble the directive.
        StopInputHandlerDirective directive = StopInputHandlerDirective.builder()
          .withOriginatingRequestId(currentInputHandlerId)
          .build();

      	// Add the directive that stops the Input Handler.
        responseBuilder.addDirective(directive);
      }

      // Build the response.
      Optional<Response> response = responseBuilder.build();

      // Write the response to CloudWatch.
      String responseLog = response.toString();
      responseLog = responseLog.replace("\n", " ").replace("\r", " ");
      System.out.println("===RESPONSE=== " + responseLog);

      // Return the response.
      return response;

    }

}

Copied to clipboard.

This sample code uses the Alexa Skills Kit SDK for Python.

from ask_sdk_core.dispatch_components import AbstractRequestHandler
from ask_sdk_core.handler_input import HandlerInput
from ask_sdk_core.utils import is_intent_name
from ask_sdk_model import Response
from ask_sdk_model.interfaces.game_engine import StopInputHandlerDirective


class StopInputIntentHandler(AbstractRequestHandler):
    def can_handle(self, handler_input):
        # type: (HandlerInput) -> bool
        return is_intent_name("StopInputHandlerIntent")(handler_input)

    def handle(self, handler_input):
        # type: (HandlerInput) -> Response

        # Retrieve the session attribute that we used to store
        # the request ID of the original request that we responded
        # to when we started the Input Handler.
        session_attributes = handler_input.attributes_manager.session_attributes

        # Assign an empty string if key doesn't exist in session attributes
        current_input_handler_id = session_attributes.get(
            "currentInputHandlerId", "")

        # Start building a response.
        response_builder = handler_input.response_builder.set_should_end_session(
            False).speak(
            speech="Stopping the Input Handler, if one was running.")

        # If we were able to retrieve an Input Handler's originating
        # request ID from the session attributes, stop the Input Handler
        # with it. If the ID was from an Input Handler that is no longer
        # running, it is ok because in that case the Game Engine will
        # ignore this directive.
        if current_input_handler_id is not None:

            #  Assemble the directive.
            stop_input_handler_directive = StopInputHandlerDirective(
                originating_request_id=current_input_handler_id)

            # Add the directive that stops the Input Handler.
            response_builder.add_directive(stop_input_handler_directive)

        # Build the response.
        response = response_builder.response

        # Write the response to CloudWatch.
        print("===RESPONSE===\n {}".format(response))

        # Return the response.
        return response

Input Handler Event Parsing Example

The following code shows an Input Handler event and how to extract the fields using the ASK SDKs.

Copied to clipboard.

{
    "type": "GameEngine.InputHandlerEvent",
    "requestId": "amzn1.echo-api.request.12345-678910",
    "timestamp": "2018-10-11T19:09:56Z",
    "locale": "en-US",
    "originatingRequestId": "amzn1.echo-api.request.12345-678910",
    "events": [
        {
            "name": "buttonUpEvent",
            "inputEvents": [
                {
                    "gadgetId": "amzn1.ask.gadget.12345678910",
                    "timestamp": "2018-10-11T19:09:56.287Z",
                    "color": "000050",
                    "feature": "press",
                    "action": "up"
                }
            ]
        }
    ]
}

Copied to clipboard.

This sample code uses the Alexa Skills Kit SDK for Node.js (v2).

const InputHandlerEventHandler = {
  canHandle(handlerInput) {
    return handlerInput.requestEnvelope.request.type === 'GameEngine.InputHandlerEvent';
  },

  handle(handlerInput) {
   const request = handlerInput.requestEnvelope.request;
   const events = request.events;
   var infoToSpeak = '';

   // Loop over the list of Input Handler events that triggered this
   // request. When an Input Handler event's conditions become true,
   // the event is sent to your skill only once. However, there may
   // be multiple Input Handler events within one request if more
   // than one such event became true at the same time.
   events.forEach(function(event){

      const numRawEvents = event.inputEvents.length;
      console.log('===INPUT HANDLER EVENT INFO=== name: ' + event.name +
            ', number of raw events: ' + numRawEvents);

      infoToSpeak = 'There was an Input Handler event of type ' + event.name;

      // Loop over the list of raw button events that contributed
      // to this Input Handler event.
      event.inputEvents.forEach(function(rawEvent){
          console.log('===RAW EVENT INFO=== gadget ID: ' + rawEvent.gadgetId +
          ' timestamp: ' + rawEvent.timestamp +
          ', action: ' + rawEvent.action +
          ', color: ' + rawEvent.color);
      });
   });

   return handlerInput.responseBuilder
      .speak(infoToSpeak)
      .withShouldEndSession(false)
      .getResponse();
  }
};

Copied to clipboard.

This sample code uses the Alexa Skills Kit SDK for Java.

package com.amazon.ask.buttonsamples.handlers;

import com.amazon.ask.dispatcher.request.handler.HandlerInput;
import com.amazon.ask.dispatcher.request.handler.RequestHandler;
import com.amazon.ask.model.Response;
import com.amazon.ask.response.ResponseBuilder;
import com.amazon.ask.model.RequestEnvelope;
import com.amazon.ask.model.services.gameEngine.*;
import com.amazon.ask.model.interfaces.gameEngine.*;
import static com.amazon.ask.request.Predicates.requestType;
import java.util.Optional;
import java.util.List;


public class InputHandlerEventHandler implements RequestHandler {

    @Override
    public boolean canHandle(HandlerInput handlerInput) {
        return handlerInput.matches(requestType(InputHandlerEventRequest.class));
    }

    @Override
    public Optional<Response> handle(HandlerInput handlerInput) {

      InputHandlerEventRequest request =
           (InputHandlerEventRequest)handlerInput.getRequestEnvelope().getRequest();
      List<InputHandlerEvent> events = request.getEvents();
      int numEvents = events.size();
      String infoToSpeak = "";

      // Loop over the list of Input Handler events that triggered this
      // request. When an Input Handler event's conditions become true,
      // the event is sent to your skill only once. However, there may
      // be multiple Input Handler events within one request if more
      // than one such event became true at the same time.
      for (int i = 0; i < numEvents; i++) {

        InputHandlerEvent event = events.get(i);
        List<InputEvent> rawEvents = event.getInputEvents();
        int numRawEvents = rawEvents.size();
        System.out.println("===INPUT HANDLER EVENT INFO=== name: " + event.getName() +
            ", number of raw events: " + numRawEvents);

        infoToSpeak = "There was an Input Handler event of type " + event.getName();

        // Loop over the list of raw button events that contributed
        // to this Input Handler event.
        for (int j = 0; j < numRawEvents; j++) {
          InputEvent rawEvent = rawEvents.get(j);
          System.out.println("===RAW EVENT INFO=== gadget ID: " + rawEvent.getGadgetId() +
            ", timestamp: " + rawEvent.getTimestamp() +
            ", action: " + rawEvent.getAction() +
            ", color: " + rawEvent.getColor());
          }
        }

      // Build a response.
      Optional<Response> response = handlerInput.getResponseBuilder()
        .withSpeech(infoToSpeak)
        .withShouldEndSession(false)
        .build();

      // Write the response to CloudWatch.
      String responseLog = response.toString();
      responseLog = responseLog.replace("\n", " ").replace("\r", " ");
      System.out.println("===RESPONSE=== " + responseLog);

      // Return the response.
      return response;

    }

}

Copied to clipboard.

This sample code uses the Alexa Skills Kit SDK for Python.

from ask_sdk_core.dispatch_components import AbstractRequestHandler
from ask_sdk_core.handler_input import HandlerInput
from ask_sdk_core.utils import is_request_type
from ask_sdk_model import Response


class InputHandlerEventHandler(AbstractRequestHandler):
    def can_handle(self, handler_input):
        # type: (HandlerInput) -> bool
        return is_request_type("InputHandlerEventRequest")(handler_input)

    def handle(self, handler_input):
        # type: (HandlerInput) -> Response

        request = handler_input.request_envelope.request
        info_to_speak = ""
        events = request.events()

        #  Loop over the list of Input Handler events that triggered this
        #  request. When an Input Handler event's conditions become true,
        #  the event is sent to your skill only once. However, there may
        #  be multiple Input Handler events within one request if more
        #  than one such event became true at the same time.
        for event in events:
            raw_events = event.input_events()

            print(
                "===INPUT HANDLER EVENT INFO=== name: {}, "
                "number of raw events: {}".format(
                    event.name, str(len(raw_events))))

            info_to_speak = ("There was an Input Handler event of "
                             "type {}".format(event.name))

            # Loop over the list of raw button events that contributed
            # to this Input Handler event.
            for raw_event in raw_events:
                print(
                    "===RAW EVENT INFO=== gadget ID: {}, timestamp: {}, "
                    "action: {}, color: {}".format(
                        raw_event.gadget_id, raw_event.timestamp,
                        raw_event.action, raw_event.color)
                      )

        # Build the response.
        response = handler_input.response_builder.speak(
            speech=info_to_speak).set_should_end_session(False).response

        # Write the response to CloudWatch.
        print("===RESPONSE===\n {}".format(response))

        # Return the response.
        return response

Service Interface Reference (JSON)

Request Format and Standard Request Types:

Interfaces: