Giter Site home page Giter Site logo

alexa / alexa-skills-kit-sdk-for-python Goto Github PK

View Code? Open in Web Editor NEW
801.0 76.0 200.0 801 KB

The Alexa Skills Kit SDK for Python helps you get a skill up and running quickly, letting you focus on skill logic instead of boilerplate code.

Home Page: https://developer.amazon.com/en-US/docs/alexa/alexa-skills-kit-sdk-for-python/overview.html

License: Apache License 2.0

Python 100.00%
skills sdk alexa-skills-kit python alexa-sdk alexa software-development-kit alexa-skill alexa-skill-development sdk-python

alexa-skills-kit-sdk-for-python's Introduction


Alexa Skills Kit SDK for Python

English | 日本語

The ASK SDK for Python makes it easier for you to build highly engaging skills, by allowing you to spend more time on implementing features and less on writing boiler-plate code.

The ASK SMAPI SDK for Python provides developers a library for easily interacting with all Skill Management APIs (SMAPI), including interaction model, intent request history, and in-skill purchasing APIs.

Package Versions

Package Version
ask-sdk-runtime Version Downloads
ask-sdk-core Version Downloads
ask-sdk-dynamodb-persistence-adapter Version Downloads
ask-sdk Version Downloads
ask-sdk-local-debug Version Downloads
ask-sdk-webservice-support Version Downloads
flask-ask-sdk Version Downloads
django-ask-sdk Version Downloads
ask-sdk-jinja-renderer Version Downloads
ask-smapi-sdk Version Downloads

Technical Documentation

ASK SDK

ASK SMAPI SDK

The SDK works on model classes rather than native Alexa JSON requests and responses. These model classes are generated using the Request, Response JSON schemas from the developer docs.

The documentation for the model classes can be found here.

Samples

This code sample will allow you to hear a response from Alexa when you trigger it. It is a minimal sample to get you familiarized with the Alexa Skills Kit and AWS Lambda.

This sample shows how to create a skill using the Request Handler classes. For more information, check the Request Processing documentation.

This code sample will allow you to hear a response from Alexa when you trigger it. It is a minimal sample to get you familiarized with the Alexa Skills Kit and AWS Lambda.

This sample shows how to create a skill using the Request Handler Decorators. For more information, check the Request Processing documentation.

This is a step-up in functionality from Hello World. When the user provides their favorite color, Alexa remembers it and tells the user their favorite color.

It allows you to capture input from your user and demonstrates the use of Slots. It also demonstrates use of session attributes and request, response interceptors.

Template for a basic fact skill. You’ll provide a list of interesting facts about a topic, Alexa will select a fact at random and tell it to the user when the skill is invoked.

Demonstrates use of multiple locales and internationalization in the skill.

Template for a basic quiz game skill. Alexa quizzes the user with facts from a list you provide.

Demonstrates use of render template directives to support displays on Alexa-enabled devices with a screen.

Sample skill that shows how to request and access the configured address in the user’s device settings.

Demonstrates how to use the alexa APIs using the SDK. For more information, check the documentation on Alexa Service Clients

Sample fact skill with in-skill purchase features, by offering different packs of facts behind a purchase, and a subscription to unlock all of the packs at once.

Demonstrates calling monetization alexa service and using ASK CLI to enable in-skill purchasing.

Template for a local recommendations skill. Alexa uses the data that you provide to offer recommendations according to the user's stated preferences.

Demonstrates calling external APIs from the skill.

Sample skill that matches the user with a pet. Alexa prompts the user for the information it needs to determine a match. Once all of the required information is collected, the skill sends the data to an external web service that processes the data and returns the match.

Demonstrates how to prompt and parse multiple values from customers using Dialog Management and Entity Resolution.

Template for a basic high-low game skill. When the user guesses a number, Alexa tells the user whether the number she has in mind is higher or lower.

Demonstrates use of persistence attributes and the persistence adapter in the SDK.

Project that demonstrates how to use AudioPlayer interface and PlaybackController interface for building audioplayer skills in Alexa. The SingleStream skill sample demonstrates how to create a live radio skill, along with localization support. The MultiStream skill sample demonstrates how to create a basic podcast skill that can play multiple, pre-recorded audio streams.

This sample demonstrates 3 features of APL: the Pager Component, SpeakItem Command, and accessing device characteristics in the skill code.

Alexa Capabilities supported by SDK

Preview

Hosting Skills on Non-Lambda Resources

SDK provides ask-sdk-webservice-support package, that allows hosting skills as custom web services. It also provides framework specific adapters under flask-ask-sdk and django-ask-sdk packages, to integrate skills on the respective frameworks and deploy as web service.

More information on how to use these packages can be found on this documentation link.

Got Feedback?

  • We would like to hear about your bugs, feature requests, questions or quick feedback. Please search for existing issues before opening a new one. It would also be helpful if you follow the templates for issue and pull request creation. Please follow the contributing guidelines for pull requests!!
  • Request and vote for Alexa features! Remember to select the category as ASK SDK if your feature request is specific to SDK.

Additional Resources

Other Language Alexa Skills Kit SDKs

Community

Tutorials & Guides

  • Voice Design Guide -A great resource for learning conversational and voice user interface design.

alexa-skills-kit-sdk-for-python's People

Contributors

ask-sdk avatar cargiggles avatar doiron avatar doncicuto avatar exilit avatar hyandell avatar jcgrant avatar joshbean avatar memodoring avatar mhaddy avatar milancermak avatar nikhilym avatar pbheemag avatar priyakotwal avatar sattpat avatar schnorea avatar shreraju-amzn avatar shreyas-vgr avatar teamteatime avatar timothyaaron avatar tylercarberry avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

alexa-skills-kit-sdk-for-python's Issues

How to access status_code from slots?

I'm submitting a...


[ ] Regression (a behavior that used to work and stopped working in a new release)
[ ] Bug report  
[ ] Performance issue
[ ] Feature request
[ ] Documentation issue or request
[x] Other... Please describe: Just asking?

Hi I am trying to check the status_code from slots if it has a match. From the Color Picker example
slots = handler_input.request_envelope.request.intent.slots
I knew that the slots['slot_name'].value would result to the value. However, I also want to check if it is a match. I was looking into the pdf documentation at page 149 and saw
class ask_sdk_model.slu.entityresolution.status_code.StatusCode
so I tried running this:
if slots['slot_name'].status_code == "ER_SUCCESS_NO_MATCH"
but it returns
AttributeError: 'Slot' object has no attribute 'status_code''list' object has no attribute 'strip':
Am I doing it wrong? Or there is a correct way to do it?

skill_builder.lambda_handler's documentation showing RequestEnvelope as parameter but expects json-string

I'm submitting a...


[ ] Regression (a behavior that used to work and stopped working in a new release)
[ ] Bug report  
[ ] Performance issue
[x] Feature request
[x] Documentation issue or request
[ ] Other... Please describe:

Expected Behavior

It should be possible to pass a RequestEnvelope object to the lambda_handler returned by skill_builder as stated in the doc_string.

Current Behavior

The method expect a json-string to be passed as parameter for the RequestEnvelope instead.

Possible Solution

Either change documentation or allow to pass RequestEnvelope or string for example like:

    def lambda_handler(self):
        # type: () -> Callable[[RequestEnvelope|str, T], Dict[str, T]]
        """Create a handler function that can be used as handler in
        AWS Lambda console.

        The lambda handler provides a handler function, that acts as
        an entry point to the AWS Lambda console. Users can set the
        lambda_handler output to a variable and set the variable as
        AWS Lambda Handler on the console.

        :return: Handler function to tag on AWS Lambda console.
        """
        def wrapper(event, context):
            # type: (RequestEnvelope|str, T) -> Dict[str, T]
            skill = CustomSkill(skill_configuration=self.skill_configuration)
            if type(event) is RequestEnvelope:
                request_envelope = event
            else:
                request_envelope = skill.serializer.deserialize(
                    payload=json.dumps(event), obj_type=RequestEnvelope)
            response_envelope = skill.invoke(request_envelope=request_envelope, context=context)
            return skill.serializer.serialize(response_envelope)  # type:ignore
        return wrapper

Your Environment

  • ASK SDK for Python used: 1.10.1
  • Operating System and version: Ubuntu 18.04.2

Python version info

  • Python version used for development: 3.6

Minor doc problem in DEVELOPING_YOUR_FIRST_SKILL

I'm submitting a...


[ ] Regression (a behavior that used to work and stopped working in a new release)
[ ] Bug report  
[ ] Performance issue
[ ] Feature request
[x] Documentation issue or request
[ ] Other... Please describe:

Expected Behavior

Current Behavior

Line 93 of DEVELOPING_YOUR_FIRST_SKILL.rst is unclear. It currently says:
We strongly recommend you to not use
either of the option and stick with it through out your skill, for
better code structure.

Possible Solution

I think you meant something like:
We strongly recommend you to choose
one of the options and use it consistently throughout your skill, for
better code structure.

// Not required, but suggest a fix/reason for the bug,
// or ideas how to implement the addition or change

Steps to Reproduce (for bugs)

// Provide a self-contained, concise snippet of code
// For more complex issues provide a repo with the smallest sample that reproduces the bug
// Including business logic or unrelated code makes diagnosis more difficult

Context

Your Environment

  • ASK SDK for Python used: x.x.x
  • Operating System and version:

Python version info

  • Python version used for development:

Add more example about audio player.

I'm submitting a...


[ ] Regression (a behavior that used to work and stopped working in a new release)
[ ] Bug report  
[ ] Performance issue
[x] Feature request
[ ] Documentation issue or request
[ ] Other... Please describe:

Do you have any plan for adding skill-sample-python-audio-player ? . I saw we've already had this skill-sample-nodejs-audio-player with NodeJS .

Add support to persist data in S3

This is a feature request and a proposal.


[ ] Regression (a behavior that used to work and stopped working in a new release)
[ ] Bug report  
[ ] Performance issue
[X] Feature request
[ ] Documentation issue or request
[ ] Other... Please describe:

Expected Behavior

Being able to persist data on S3.

It might work as the DynamoDB one.

  • One S3 Data Persistence Adapter that derives from AbstractPersistenceAdapter that implements get_attributes and save_attributes.
  • An objectKeyGenerator, not that is really needed however it comes handy.

Pretty much like https://gist.github.com/germanviscuso/70c979f671660fea811ccfb63801f936
The above is an example using JS.

Current Behavior

It is not possible to compare it because it does not exist (as far as I know).

Possible Solution

I have created a rudimentary solution for this, it works as follows:

1.- I have created a new standard_s3.py based on standard.py. This is basically the same as the standard however the constructor is like:

    def __init__(
            self, bucket_name=None, s3_client=None,
            object_generator=None, path_prefix=None):

2.- Created an S3 Persistence Adapter and a ObjectKeyGenerator.

I have created a skill with this as example. if you would like to take a look
S3 Persistence

Just added:

  • standard_s3.py to ask-sdk.
  • New module called ask-sdk-s3-persistence with the adapter and object key generators.

Steps to Reproduce (for bugs)

None

Context

Your Environment

  • ASK SDK for Python used: 1.5.0
  • Operating System and version: macOS Mojave

Python version info

  • Python version used for development:
    ✗ python
    Python 3.6.5 (default, Jun 17 2018, 12:13:06)

Thank you very much

help with specific instance of certificate validation

I'm submitting a...


[ ] Regression (a behavior that used to work and stopped working in a new release)
[ ] Bug report  
[ ] Performance issue
[x] Feature request
[x] Documentation issue or request
[ ] Other... Please describe:

Opening an issue to track a request for assistance with a single specific instance of the problem trackedin #62, #56, and #53 among others, the absence of certificate & request validation code in the SDK. Having started down this road almost three weeks ago it is now apparent to me that this is a common roadblock that is preventing people from readily developing self-hosted alexa skills. It's also remarkable after 3+ years of Amazon's energetic investment in the platform developers are still faced with this obstacle. Be that as it may I am determined to push through so I am asking for some very specific guidance.

Expected Behavior

I want my code to verify Alexa's http requests that are sent to my skill Endpoint https://developer.amazon.com/docs/custom-skills/host-a-custom-skill-as-a-web-service.html#checking-the-signature-of-the-request and return 400 error as per Amazon's requirement.

Current Behavior

When I submit my skill for certification I get the error message:

The skill end-point is not validating the signatures for incoming requests and is accepting requests with an empty signature URL.
The skill end-point is not validating the signatures for incoming requests and is accepting requests with an incorrect certificate URL.
The skill end-point is not validating the signatures for incoming requests and is accepting requests with an invalid signature URL specified.
The skill end-point is not validating the signatures for incoming requests and is accepting requests when no signature URL headers are specified.

Possible Solution

I see what needs to be done but what I need guidance on is exactly where to do it. Clearly I need a function or module that does the certificate validation. I found the alexandra library which includes those functions and also some scripts by dizmo? and others. So should I call that function from inside my post function? How do ensure that flask then issues a 400?


Steps to Reproduce (for bugs)

@app.route('/altbrains-basketball', methods=['POST'])
def post():
    """
    Process the request as following :
    - Get the input request JSON
    - Deserialize it to Request Envelope
    - Verify the request was sent by Alexa
    - Invoke the skill
    - Return the serialized response
    """
    content = request.json
 **should the validation logic go here**   

e.g. alexandra.util.validate_request_certificate(content) if false then raise 400, if true proceed
**
    request_envelope = skill_obj.serializer.deserialize(
        payload=json.dumps(content), obj_type=RequestEnvelope)
    response_envelope = skill_obj.invoke(
        request_envelope=request_envelope, context=None)
    print(response_envelope)
    return jsonify(skill_obj.serializer.serialize(response_envelope))

Context

This is preventing me from deploying to the Alexa network. I should not have to write hundreds of lines of mechanical validation code just so that my server can talk to Alexa.

Your Environment

  • ASK SDK for Python used: 1.8.0
  • Operating System and version: AWS Ubuntu, Apache, mod_wsgi, flask

Python version info

  • Python version used for development: 3.6.7

Handler for Account Linking

I'm submitting a...


[ ] Regression (a behavior that used to work and stopped working in a new release)
[ ] Bug report  
[ ] Performance issue
[ ] Feature request
[ ] Documentation issue or request
[x] Other... Please describe: Asking for help.

Hi guys,
I have successfully enabled Account Linking for my skill. I am also able to get some parameters using the access token. I am in the part of handling an account linking error...
I have this checker for access token:

def checkAccessToken(handler_input):
	User = handler_input.request_envelope.session.user
	if User.access_token is None:
		return False
	else:
		# Also check if user is a user of system i.e. Car Fu
		return True

I check them for every intents and works well...

class SomeIntentHandler(AbstractRequestHandler):
	def can_handle(self, handler_input):
		return (is_intent_name("SomeIntent")(handler_input) and checkAccessToken(handler_input))

Now I want a handler to respond an account linking problem i.e. user has no access token, or user is not a user of Car Fu.

I tried this:

class CatchAccountLinkingErrorHandler(AbstractExceptionHandler):
	def can_handle(self, handler_input):
                # Boolean of (not False) when there is no access token.
		return not checkAccessToken(handler_input)

	def handle(self, handler_input):
		# type: (HandlerInput, Exception) -> Response
		logger.info("In CatchAccountLinkingErrorHandler")
		
		handler_input.response_builder.speak("Your account is not linked.")

		return handler_input.response_builder.response

I used sb.add_request_handler(CatchAccountLinkingErrorHandler()), but to no avail since
I got this error: Input should be a RequestHandler instance
Then, I also tried sb.add_exception_handler(CatchAccountLinkingErrorHandler())
It also does not work since (1) no errors where found during simulation (2) the respond was from CatchAllExceptionHandler.

Hmm, whats your take or suggest solution?
Thanks guys and hoping for an 'alexa-skills-kit-sdk-for-python' tag in StackOverflow.

module 'ask_sdk_model.interfaces.viewport.video' has no attribute 'Video'

I'm submitting a...


[ x] Regression (a behavior that used to work and stopped working in a new release)
[ ] Bug report  
[ ] Performance issue
[ ] Feature request
[] Documentation issue or request
[ ] Other... Please describe:

My basketball app was running properly using flask on a local machine accessed via ngrok. I made no changes over the weekend, and a new sdk error appeared.

Expected Behavior

Current Behavior

* Serving Flask app "basketball.py" (lazy loading)
 * Environment: development
 * Debug mode: on
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 190-149-512

[2019-05-06 19:23:32,303] ERROR in skill_adapter: Skill dispatch exception
Traceback (most recent call last):
  File "/Users/fzimmerman/anaconda3/lib/python3.6/site-packages/ask_sdk_core/serialize.py", line 252, in __load_class_from_name
    resolved_class = getattr(module, resolved_class_name)
AttributeError: module 'ask_sdk_model.interfaces.viewport.video' has no attribute 'Video'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/fzimmerman/anaconda3/lib/python3.6/site-packages/ask_sdk_core/serialize.py", line 352, in __deserialize_model
    class_deserialized_types[class_param_name]))
  File "/Users/fzimmerman/anaconda3/lib/python3.6/site-packages/ask_sdk_core/serialize.py", line 217, in __deserialize
    obj_type = self.__load_class_from_name(obj_type)
  File "/Users/fzimmerman/anaconda3/lib/python3.6/site-packages/ask_sdk_core/serialize.py", line 261, in __load_class_from_name
    "modules: {}".format(class_name, str(e)))
ask_sdk_core.exceptions.SerializationException: Unable to resolve class ask_sdk_model.interfaces.viewport.video.Video from installed modules: module 'ask_sdk_model.interfaces.viewport.video' has no attribute 'Video'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/fzimmerman/anaconda3/lib/python3.6/site-packages/ask_sdk_core/serialize.py", line 352, in __deserialize_model
    class_deserialized_types[class_param_name]))
  File "/Users/fzimmerman/anaconda3/lib/python3.6/site-packages/ask_sdk_core/serialize.py", line 228, in __deserialize
    return self.__deserialize_model(payload, obj_type)
  File "/Users/fzimmerman/anaconda3/lib/python3.6/site-packages/ask_sdk_core/serialize.py", line 364, in __deserialize_model
    raise SerializationException(str(e))
ask_sdk_core.exceptions.SerializationException: Unable to resolve class ask_sdk_model.interfaces.viewport.video.Video from installed modules: module 'ask_sdk_model.interfaces.viewport.video' has no attribute 'Video'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/fzimmerman/anaconda3/lib/python3.6/site-packages/ask_sdk_core/serialize.py", line 352, in __deserialize_model
    class_deserialized_types[class_param_name]))
  File "/Users/fzimmerman/anaconda3/lib/python3.6/site-packages/ask_sdk_core/serialize.py", line 228, in __deserialize
    return self.__deserialize_model(payload, obj_type)
  File "/Users/fzimmerman/anaconda3/lib/python3.6/site-packages/ask_sdk_core/serialize.py", line 364, in __deserialize_model
    raise SerializationException(str(e))
ask_sdk_core.exceptions.SerializationException: Unable to resolve class ask_sdk_model.interfaces.viewport.video.Video from installed modules: module 'ask_sdk_model.interfaces.viewport.video' has no attribute 'Video'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/fzimmerman/anaconda3/lib/python3.6/site-packages/flask_ask_sdk/skill_adapter.py", line 240, in dispatch_request
    http_request_body=content)
  File "/Users/fzimmerman/anaconda3/lib/python3.6/site-packages/ask_sdk_webservice_support/webservice_handler.py", line 142, in verify_request_and_dispatch
    payload=http_request_body, obj_type=RequestEnvelope)
  File "/Users/fzimmerman/anaconda3/lib/python3.6/site-packages/ask_sdk_core/serialize.py", line 167, in deserialize
    return self.__deserialize(payload, obj_type)
  File "/Users/fzimmerman/anaconda3/lib/python3.6/site-packages/ask_sdk_core/serialize.py", line 228, in __deserialize
    return self.__deserialize_model(payload, obj_type)
  File "/Users/fzimmerman/anaconda3/lib/python3.6/site-packages/ask_sdk_core/serialize.py", line 364, in __deserialize_model
    raise SerializationException(str(e))
ask_sdk_core.exceptions.SerializationException: Unable to resolve class ask_sdk_model.interfaces.viewport.video.Video from installed modules: module 'ask_sdk_model.interfaces.viewport.video' has no attribute 'Video'
127.0.0.1 - - [06/May/2019 19:23:32] "POST / HTTP/1.1" 500 -

Odd because app doesn't interact with video at all.

Possible Solution

Steps to Reproduce (for bugs)

run basketball.py on flask

Context

Your Environment

  • ASK SDK for Python used: 1.9.0
  • Operating System and version: MacOSX

Python version info

  • Python version used for development:3.6.7

management client get_list returns error

I'm submitting a...


[ ] Regression (a behavior that used to work and stopped working in a new release)
[x] Bug report  
[ ] Performance issue
[ ] Feature request
[ ] Documentation issue or request
[ ] Other... Please describe:

Expected Behavior

service_client_fact.get_list_management_service().get_list('listID', 'active') should return a list of items.

Current Behavior

Am getting error below.
argument of type 'NoneType' is not iterable: SerializationException

Possible Solution

// Not required, but suggest a fix/reason for the bug,
// or ideas how to implement the addition or change

Steps to Reproduce (for bugs)

// Provide a self-contained, concise snippet of code
from ask_sdk_core.skill_builder import CustomSkillBuilder
from ask_sdk_core.api_client import DefaultApiClient
from ask_sdk_core.dispatch_components import AbstractRequestHandler
from ask_sdk_core.dispatch_components import AbstractExceptionHandler
from ask_sdk_core.utils import is_request_type, is_intent_name
from ask_sdk_model.ui import AskForPermissionsConsentCard
from ask_sdk_model.services import ServiceException
from ask_sdk_model.services import list_management

sb = CustomSkillBuilder(api_client=DefaultApiClient())

permissions = ["read::alexa:household:list","write::alexa:household:list"]

class StartListsHandler(AbstractRequestHandler):

    def can_handle(self, handler_input):
        return is_intent_name("StartListsIntent")(handler_input)

    def handle(self, handler_input):
        print 'starting handler'
        req_envelope = handler_input.request_envelope
        response_builder = handler_input.response_builder
        service_client_fact = handler_input.service_client_factory

        if not (req_envelope.context.system.user.permissions and
                req_envelope.context.system.user.permissions.consent_token):
            response_builder.speak(NOTIFY_MISSING_PERMISSIONS)
            print 'starting handler12'
            response_builder.set_card(
                AskForPermissionsConsentCard(permissions=permissions))
            return response_builder.response

        try:
            
            device_id = req_envelope.context.system.device.device_id
            device_list_client = service_client_fact.get_list_management_service()
            
            lists = device_list_client.get_lists_metadata()

            rpiresponse = lists.to_dict() #Converts metadata to list format

            for pages in rpiresponse['lists']:
                if pages['name'] == 'mytestlist':
                    
                    sessionlistid = pages['list_id']
                    sessionitemslists = device_list_client.get_list(sessionlistid, 'active') 

            return response_builder.response
        except ServiceException:
            response_builder.speak(ERROR)
            return response_builder.response
        except Exception as e:
            raise e   

sb.add_request_handler(StartListsHandler())
lambda_handler = sb.lambda_handler()      
       
// For more complex issues provide a repo with the smallest sample that reproduces the bug
// Including business logic or unrelated code makes diagnosis more difficult

Context

I am trying a simple list read, create program. Currently stuck on reading items using the client service.

Your Environment

  • ASK SDK for Python used: 1.3.0
  • Operating System and version:
    Using AWS Lambda

Python version info

  • Python version used for development: 3.6

Access to the event's context.System.device.supportedInterfaces.Display attribute

I'm submitting a...


[ ] Regression (a behavior that used to work and stopped working in a new release)
[X] Bug report  
[ ] Performance issue
[X] Feature request
[ ] Documentation issue or request
[ ] Other... Please describe:

While writing a request handler such as:

@sb.request_handler(can_handle_func=is_intent_name("HelloWorldIntent"))
def hello_world_intent_handler(handler_input):

I've noticed the handler_input object does not provide access to the supported interfaces for the device. In many use cases the function needs access to the supported interfaces for the device. IE: It wants to return a display template for an Echo Show if a display is available.

A javascript implementation would simply check for:

this.event.context.System.device.supportedInterfaces.Display

The handler_input object in the python SDK does not appear to provide access to the System object via the context object. IE: handler_input.context.System.

Is there a correct way using the alexa-skills-kit-sdk-for-python to determine the supportedInterfaces while handling the request?

I've also noticed that the handler_input object provides :

handler_input.request_envelope.context.system.device.supported_interfaces

Perhaps this is the correct location to detect this setting.

Callable has no attribute __abc_registry

I'm submitting a...


[ ] Regression (a behavior that used to work and stopped working in a new release)
[X] Bug report  
[ ] Performance issue
[ ] Feature request
[ ] Documentation issue or request
[ ] Other... Please describe:

Expected Behavior

The SDK provides the possibility of creating a Standard Skill using the StandardSkillBuilder module from ask_sdk.standard.

Current Behavior

When just trying to execute the script I get:

Traceback (most recent call last):
  File "indexClass.py", line 1, in <module>
    from ask_sdk.standard import StandardSkillBuilder
  File "/path/to/ask_sdk/standard.py", line 18, in <module>
    import typing
  File "/path/to/typing.py", line 1356, in <module>
    class Callable(extra=collections_abc.Callable, metaclass=CallableMeta):
  File "/path/to/typing.py", line 1004, in __new__
    self._abc_registry = extra._abc_registry
AttributeError: type object 'Callable' has no attribute '_abc_registry'

Possible Solution

Still investigating. Not sure how to solve this.

Steps to Reproduce (for bugs)

Steps I have followed:

1.- Create a directory to place all my files.
2.- Created the setup.cfg file so pip can install files in that directory (I am using Homebrew this a bug)
3.- Installed the latest available version of the SDK through pip pip install ask-sdk -t .
4.- Created indexClass.py
5.- Imported the needed modules:
from ask_sdk.standard import StandardSkillBuilder
6.- Create the Skill Builder objects
ssb = StandardSkillBuilder(table_name='Preferences', auto_create_table=True)
7.- Added the classes for Launch, Help, Cancel and Stop, All Exceptions and so on.
8.- Added all the requests to the SkillBuilder object
9.- Execute the script python indexClass.py
10.- Uploaded the code to Lambda just to verify that it was not my local environment and got the same error.

You can find details of the code here Book Recommendations

Context

I am trying to create a Lambda function with persistence using DynamoDB however I always start with a basic function to check the basics and moreover now that there is a new SDK version I wanted to test it.

I have also sent the question to the Alexa Developer's Forum
Creating a StandardSkillBuilder with ASK SDK for Python 1.4

Your Environment

  • ASK SDK for Python used: 1.4.0
  • Operating System and version: macOS Mojave
  • VSCode with Python and Alexa plugin

Python version info

  • Python version used for development:
$ python --version
Python 3.7.0

ASK SDK version:

$ pip show ask-sdk
Name: ask-sdk
Version: 1.4.0
Summary: The ASK SDK Standard package provides a full distribution of the SDK, all batteries included, for building Alexa Skills.
Home-page: https://github.com/alexa/alexa-skills-kit-sdk-for-python
Author: Alexa Skills Kit
Author-email: [email protected]
License: Apache 2.0
Location: /Users/fran/Library/Python/3.7/lib/python/site-packages
Requires: ask-sdk-core, ask-sdk-dynamodb-persistence-adapter
Required-by: 

Update: I downgraded to 1.3.0 and used this command:

$ python-lambda-local -f handler indexClass.py tests/LaunchRequest.json

And seems to be working correctly now.

Update # 2:
Updated to ASK SDK 1.4.0 and updated some packages. Would it be possible that some of those are related?

$ pip list -o 
Package             Version   Latest     Type 
------------------- --------- ---------- -----
autopep8            1.4       1.4.3      sdist
aws-sam-cli         0.6.1     0.7.0      sdist
aws-sam-translator  1.7.0     1.8.0      sdist
awscli              1.16.26   1.16.59    wheel
boto3               1.9.6     1.9.49     wheel
botocore            1.12.16   1.12.49    wheel
certifi             2018.8.24 2018.10.15 wheel
click               6.7       7.0        wheel
colorama            0.3.9     0.4.0      wheel
future              0.17.0    0.17.1     sdist
keyring             15.1.0    16.1.0     wheel
MarkupSafe          1.0       1.1.0      wheel
notebook            5.7.0     5.7.2      wheel
python-dateutil     2.7.3     2.7.5      wheel
python-lambda-local 0.1.6     0.1.7      sdist
pytz                2018.6    2018.7     wheel
regex               2018.8.29 2018.11.7  sdist
requests            2.19.1    2.20.1     wheel
rsa                 3.4.2     4.0        wheel
setuptools          40.0.0    40.6.2     wheel
urllib3             1.23      1.24.1     wheel
websocket-client    0.53.0    0.54.0     wheel
wheel               0.31.1    0.32.3     wheel

Seems to be working. I am testing in Lambda now.

Updated # 3: Just tested in Lambda and I am getting the same error as described when opened this case. I will keep investigating.

Thank you very much for taking a look at this

Regression in GlobalResponseInterceptor - unexpected keyword argument 'dispatch_output'


[X] Regression (a behavior that used to work and stopped working in a new release)
[ ] Bug report  
[ ] Performance issue
[ ] Feature request
[ ] Documentation issue or request
[ ] Other... Please describe:

With the recent update to 1.10 and any resultant changes in the backend - a regression was introduced by the Alexa Skills Kit involving the usage of decorated @SkillBuilder.global_response_interceptor(). Attempting to implement a response interceptor will result in an exception during runtime: <lambda>() got an unexpected keyword argument 'dispatch_output'

Expected Behavior

I shouldn't have to comment out my response logging code. Especially from a core functional platform defect introduced as a regression.

Current Behavior

It fails with the following error:

[ERROR] 2019-05-30T00:46:47.187Z 0c4a841e-0ad3-4c66-bb6e-96d4726c2d38 () got an unexpected keyword argument 'dispatch_output'
Traceback (most recent call last):
File "/opt/python/ask_sdk_runtime/dispatch.py", line 122, in dispatch
handler_input=handler_input, dispatch_output=output)
TypeError: () got an unexpected keyword argument 'dispatch_output'
[DEBUG] 2019-05-30T00:46:47.229Z 0c4a841e-0ad3-4c66-bb6e-96d4726c2d38 get_prompt for exception: There was a problem on our end and we have recorded the issue. Please try again.

Possible Solution

// Not required, but suggest a fix/reason for the bug,
// or ideas how to implement the addition or change

Commenting out any usage of global_response_interceptor will fix it but you lose response interception.

Steps to Reproduce (for bugs)

// Provide a self-contained, concise snippet of code
// For more complex issues provide a repo with the smallest sample that reproduces the bug
// Including business logic or unrelated code makes diagnosis more difficult
  1. Configure a custom skill.
  2. Using the following Python code as a the lambda handler and including the 1.10 or 1.9 ASK SDK will reproduce the issue when attempting to launch the skill.
from ask_sdk_core.skill_builder import SkillBuilder
from ask_sdk_core.utils import is_request_type

sb = SkillBuilder()


@sb.exception_handler(can_handle_func=lambda i, e: True)
def all_exception_handler(handler_input, exception):
    print(exception)
    return handler_input \
        .response_builder \
        .speak('Exception') \
        .set_should_end_session(True) \
        .response


@sb.request_handler(can_handle_func=is_request_type('LaunchRequest'))
def launch_request_handler(handler_input):
    return handler_input \
        .response_builder \
        .speak('Launch Request') \
        .set_should_end_session(False) \
        .response


@sb.global_request_interceptor()
def request_logger(handler_input):
    print('request', handler_input.request_envelope)


@sb.global_response_interceptor()
def response_logger(handler_input, response):
    print('response', handler_input.request_envelope)
    if response is not None:
        print(response)


handler = sb.lambda_handler()

Context

This was a regression, the code was working then it was not.

Your Environment

  • ASK SDK for Python used: x.x.x
    1.9 and 1.10 were tested.
  • Operating System and version:
    Lambda

Python version info

  • Python version used for development:
    Python 3.7

API to un-link an account or re-link it.

I'm submitting a...


[ ] Regression (a behavior that used to work and stopped working in a new release)
[ ] Bug report  
[ ] Performance issue
[X] Feature request
[ ] Documentation issue or request
[ ] Other... Please describe:

Hi! I am developing a skill that would unlock / disarm a device. This has security policies such as using a PIN and resetting it after some times. I am currently in communication with someone in the Dev Support. He told me that there's should be some mechanism to un-link the account and re-link it and asking for a NEW PIN after 3 fail PIN attempts.

I was searching for an API for this and bumped in here: https://forums.developer.amazon.com/questions/171861/unlinking-an-account-after-3-incorrect-attempts.html

So I guess, there is no feature yet to support this even a "wild card" from the Alexa Skill. So maybe this would be some consideration in this SDK too if this happen. Thanks.

Alexa does not respond to Upsell request coming from the handler of an intent with auto delegation

I'm submitting a...


[ ] Regression (a behavior that used to work and stopped working in a new release)
[x] Bug report  
[ ] Performance issue
[ ] Feature request
[ ] Documentation issue or request
[ ] Other... Please describe:

Expected Behavior

Alexa should initiate the Upsell process by reading the upsellMessage and guide the user further.

Current Behavior

I am trying to call the UpsellResponseHandler in my Lambda function from another handler in order to upsell a subscription (the only premium product in the skill) to the user in a certain scenario. However, Alexa does not follow up and doesn't start the upsell process when the request is sent. The upsell message is not read and there is no other output (just silence).

Upsell directive in the handler for the intent having auto delegation:

upsell_msg = ("Sorry, noobie! You just reached the daily limit for the Free Subscription! To get access to 10 prices per day, you can upgrade to the amazing Premium Subscription. {} Want to learn more?").format(subscription_pack[0].summary)
 
handler_input.attributes_manager.session_attributes["lastSpeech"] = upsell_msg
 
return handler_input.response_builder.add_directive(
                        SendRequestDirective(
                            name = "Upsell",
                            payload = {
                                "InSkillProduct": {
                                    "productId": subscription_pack[0].product_id,
                                },
                                "upsellMessage": upsell_msg,
                            },
                            token = "correlationToken")).response

JSON output

{
    "body": {
        "version": "1.0",
        "response": {
            "directives": [
                {
                    "type": "Connections.SendRequest",
                    "name": "Upsell",
                    "payload": {
                        "InSkillProduct": {
                            "productId": "amzn1.adg.product.7a43a869-2b1e-4acb-b832-ec59ec253259"
                        },
                        "upsellMessage": "Sorry, noobie! You just reached the daily limit for the Free Subscription! To get access to 10 prices per day, you can upgrade to the amazing Premium Subscription. The Premium subscription allows you to get the real-time price of Bitcoin, Ethereum, Litecoin, XRP, or Bitcoin Cash, in US dollars, or Euros, 10 times a day! Want to learn more?"
                    },
                    "token": "correlationToken"
                }
            ],
            "type": "_DEFAULT_RESPONSE"
        },
        "sessionAttributes": {
            "counter_prices": 3,
            "lastSpeech": "Sorry, noobie! You just reached the daily limit for the Free Subscription! To get access to 10 prices per day, you can upgrade to the amazing Premium Subscription. The Premium subscription allows you to get the real-time price of Bitcoin, Ethereum, Litecoin, XRP, or Bitcoin Cash, in US dollars, or Euros, 10 times a day! Want to learn more?",
            "counter_prices_time": "06/21/19 15:07:07"
        },
        "userAgent": "ask-python/1.10.1 Python/3.7.3"
    }
}

No errors are shown in the Cloudwatch logs.

After further digging, it seems that the problem is the Upsell directive being inside a intent handler having a dialog model handled by Alexa (Dialog Delegation Strategy - auto delegation).

I have made the following test: moved the Upsell directive to another intent handler in my Lambda function (just for testing) and it works perfectly when that intent gets triggered. However, in the original intent handler (the one having the dialog delegation set to auto), the Upsell request gets no response from Alexa.

JSON (truncated only for this intent)

{
    "name": "PriceIntent",
    "slots": [
        {
            "name": "crypto",
            "type": "cryptoCoin",
            "samples": [
                "Give me the {crypto} price"
            ]
        },
        {
            "name": "fiat",
            "type": "fiatCoin",
            "samples": [
                "the {fiat} price please"
            ]
        },
        {
            "name": "exchange",
            "type": "theExchange"
        }
    ],
    "samples": [
        "what is the price of {crypto} in {fiat} on {exchange}"
    ]
}
 
...
 
"dialog": {
    "intents": [
        {
            "name": "PriceIntent",
            "delegationStrategy": "ALWAYS",
            "confirmationRequired": false,
            "prompts": {},
            "slots": [
                {
                    "name": "crypto",
                    "type": "cryptoCoin",
                    "confirmationRequired": false,
                    "elicitationRequired": true,
                    "prompts": {
                        "elicitation": "Elicit.Slot.69186907495.1229392271052"
                    }
                },
                {
                    "name": "fiat",
                    "type": "fiatCoin",
                    "confirmationRequired": false,
                    "elicitationRequired": true,
                    "prompts": {
                        "elicitation": "Elicit.Slot.69186907495.1330830443661"
                    }
                },
                {
                    "name": "exchange",
                    "type": "theExchange",
                    "confirmationRequired": false,
                    "elicitationRequired": false,
                    "prompts": {}
                }
            ]
        }
    ],
    "delegationStrategy": "ALWAYS"
},
"prompts": [
    {
        "id": "Elicit.Slot.69186907495.1419981262022",
        "variations": [
            {
                "type": "PlainText",
                "value": "I can tell you the price of {crypto} from Kraken, Coinbase, or Bitstamp. Pick one"
            }
        ]
    },
    {
        "id": "Elicit.Slot.69186907495.1330830443661",
        "variations": [
            {
                "type": "PlainText",
                "value": "Please tell me what currency would you like me to use for the price of {crypto} . US dollars, or Euros?"
            }
        ]
    },
    {
        "id": "Elicit.Slot.69186907495.1229392271052",
        "variations": [
            {
                "type": "PlainText",
                "value": "I can tell you the current price of Bitcoin, Ethereum, Litecoin, XRP, or Bitcoin Cash. Pick one"
            }
        ]
    }
]

Possible Solution

Alexa should handle the request coming from the handler of such intents.

Steps to Reproduce (for bugs)

As described above.

Context

I am unable to upsell to the user from within a handler of an intent.

Your Environment

  • ASK SDK for Python used: 1.10.1
  • Operating System and version: Ubuntu 18.04.2 LTS

Python version info

  • Python version used for development: 3.6.8

adapting skill-sample-python-helloworld-classes to run with FLask

I'm submitting a...


[ ] Regression (a behavior that used to work and stopped working in a new release)
[ ] Bug report  
[ ] Performance issue
[ ] Feature request
[x Documentation issue or request
[x ] Other... Please describe:

Expected Behavior

Exchange JSON with Alexa on local Flask

Current Behavior

"I am unable to access the requested skill." JSON = null

Flask trace:     rv = self.handle_user_exception(e)

  File "/home/ubuntu/.local/lib/python3.6/site-packages/flask/app.py", line 1598, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
**TypeError: handle() missing 2 required positional arguments: 'self' and 'handler_input'**

Possible Solution

// Not required, but suggest a fix/reason for the bug,
// or ideas how to implement the addition or change

I think I am only missing a couple of steps here.

Steps to Reproduce (for bugs)

Using Test simulator in ASK Dashboard, hit the endpoint http://www.altbrains.com:5000/hello

Context

Per issue 53 trying to get minimal Alexa app running on a local server with Python & Flask but not flask-ask.

Your Environment

  • ASK SDK for Python used: 1.6.0
  • Flask 0.12.1
  • Operating System and version:
    Ubuntu 18.04 on AWS

Python version info

  • Python version used for development:
    3.6.4

my current code

"""
# This is a simple Hello World Alexa Skill, built using
# the implementation of handler classes approach in skill builder.
import logging

from flask import Flask, request
import json

from ask_sdk_core.skill_builder import SkillBuilder
from ask_sdk_core.dispatch_components import AbstractRequestHandler
from ask_sdk_core.dispatch_components import AbstractExceptionHandler
from ask_sdk_core.utils import is_request_type, is_intent_name
from ask_sdk_core.handler_input import HandlerInput

from ask_sdk_model.ui import SimpleCard
from ask_sdk_model import Response

app = Flask(__name__)

sb = SkillBuilder()

skill_obj = sb.create()

logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)


class LaunchRequestHandler(AbstractRequestHandler):
    """Handler for Skill Launch."""

    def can_handle(self, handler_input):
        # type: (HandlerInput) -> bool
        return is_request_type("LaunchRequest")(handler_input)


    def handle(self, handler_input):
        # type: (HandlerInput) -> Response
        speech_text = "Hello, AltBrains User!!"

        handler_input.response_builder.speak(speech_text).set_card(
            SimpleCard("Hello, AltBrains User!", speech_text)).set_should_end_session(
            False)
        return handler_input.response_builder.response


class HelloWorldIntentHandler(AbstractRequestHandler):
    """Handler for Hello World Intent."""
    def can_handle(self, handler_input):
        # type: (HandlerInput) -> bool
        return is_intent_name("HelloWorldIntent")(handler_input)

    def handle(self, handler_input):
        # type: (HandlerInput) -> Response
        speech_text = "Hello from Fred Zimmerman!"

        handler_input.response_builder.speak(speech_text).set_card(
            SimpleCard("Hello from Fred Zimmerman!", speech_text)).set_should_end_session(
            True)
        return handler_input.response_builder.response


class HelpIntentHandler(AbstractRequestHandler):
    """Handler for Help Intent."""
    def can_handle(self, handler_input):
        # type: (HandlerInput) -> bool
        return is_intent_name("AMAZON.HelpIntent")(handler_input)

    def handle(self, handler_input):
        # type: (HandlerInput) -> Response
        speech_text = "You asked me for help. Here it is!"

        handler_input.response_builder.speak(speech_text).ask(
            speech_text).set_card(SimpleCard(
                "Hello World", speech_text))
        return handler_input.response_builder.response


class CancelOrStopIntentHandler(AbstractRequestHandler):
    """Single handler for Cancel and Stop Intent."""
    def can_handle(self, handler_input):
        # type: (HandlerInput) -> bool
        return (is_intent_name("AMAZON.CancelIntent")(handler_input) or
                is_intent_name("AMAZON.StopIntent")(handler_input))

    def handle(self, handler_input):
        # type: (HandlerInput) -> Response
        speech_text = "Goodbye!"

        handler_input.response_builder.speak(speech_text).set_card(
            SimpleCard("Hello World", speech_text))
        return handler_input.response_builder.response


class FallbackIntentHandler(AbstractRequestHandler):
    """AMAZON.FallbackIntent is only available in en-US locale.
    This handler will not be triggered except in that locale,
    so it is safe to deploy on any locale.
    """
    def can_handle(self, handler_input):
        # type: (HandlerInput) -> bool
        return is_intent_name("AMAZON.FallbackIntent")(handler_input)

    def handle(self, handler_input):
        # type: (HandlerInput) -> Response
        speech_text = (
            "The Hello World skill can't help you with that.  "
            "Try saying hello!")
        reprompt = "You can say hello!!"
        handler_input.response_builder.speak(speech_text).ask(reprompt)
        return handler_input.response_builder.response


class SessionEndedRequestHandler(AbstractRequestHandler):
    """Handler for Session End."""
    def can_handle(self, handler_input):
        # type: (HandlerInput) -> bool
        return is_request_type("SessionEndedRequest")(handler_input)

    def handle(self, handler_input):
        # type: (HandlerInput) -> Response
        return handler_input.response_builder.response


class CatchAllExceptionHandler(AbstractExceptionHandler):
    """Catch all exception handler, log exception and
    respond with custom message.
    """
    def can_handle(self, handler_input, exception):
        # type: (HandlerInput, Exception) -> bool
        return True

    def handle(self, handler_input, exception):
        # type: (HandlerInput, Exception) -> Response
        logger.error(exception, exc_info=True)

        speech = "Sorry, there was some problem. Please try again!!"
        handler_input.response_builder.speak(speech).ask(speech)

        return handler_input.response_builder.response

@app.route('/hello')
def post():
    """
    Process the request as following :
    - Get the input request JSON
    - Deserialize it to Request Envelope
    - Verify the request was sent by Alexa
    - Invoke the skill
    - Return the serialized response
    """
    content = request.json
    request_envelope = skill_obj.serializer.deserialize(
        payload=json.dumps(content), obj_type=RequestEnvelope)

    # https://developer.amazon.com/docs/custom-skills/host-a-custom-skill-as-a-web-service.html#verifying-that-the-request-was-sent-by-alexa
    # For eg, check if Skill ID matches
    if (request_envelope.context.system.application.application_id
            != "amzn1.ask.skill.2954cb35-f478-4408-a3d0-be731bf566b3"):
        print("Skill called with incorrect skill ID")
        return {}

    response_envelope = skill_obj.invoke(
        request_envelope=request_envelope, context=None)
    return skill_obj.serializer.serialize(response_envelope)


sb.add_request_handler(LaunchRequestHandler())
sb.add_request_handler(HelloWorldIntentHandler())
sb.add_request_handler(HelpIntentHandler())
sb.add_request_handler(CancelOrStopIntentHandler())
sb.add_request_handler(FallbackIntentHandler())
sb.add_request_handler(SessionEndedRequestHandler())

sb.add_exception_handler(CatchAllExceptionHandler())

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0')

Reprompt option similar to nodejs sdk

I'm submitting a...


[ ] Regression (a behavior that used to work and stopped working in a new release)
[ ] Bug report  
[ ] Performance issue
[x] Feature request
[ ] Documentation issue or request
[ ] Other... Please describe:

Expected Behavior

Hello !
It would be great if we could have a reprompt interface for our skills similar to the one provide in node js sdk, similar to what is described in this blog

Testing Locally

How do I test without using the Test Tab on the Amazon Developer website, or using an Alexa Device, but using a python program?

Sample code for ASK SDK without Lambda?

I'm submitting a...


[ ] Regression (a behavior that used to work and stopped working in a new release)
[ ] Bug report  
[ ] Performance issue
[x] Feature request
[x] Documentation issue or request
[ ] Other... Please describe:

All the code samples seems to be using AWS Lambda as the backend processor. Even the most basic "Hello World" ends with a line "handler = sb.lambda_handler()". At least one sample should be provided without usign Lambda. I tried gluing together all the decorators along with Django framework and got lost at last by context paramater on skill.envoke function call.

Following is from the documentation at https://alexa-skills-kit-python-sdk.readthedocs.io/en/latest/SKILL_BUILDERS.html

def invoke(self, request_envelope, context):

type: (RequestEnvelope, Any) -> ResponseEnvelope

How to generate the "context" object. RequestEnvelope is entire POST body of the request. So it should already have all the context parameters right.

Expected Behavior

At least simplest Hello World Example without using Lambda

Current Behavior

No sample available.

Possible Solution

Example with any of the popular python frameworks. Example: Django, Flask etc.

Context

Trying to host my skill on my own server.

Your Environment

Ubuntu 18.04 LTS

Python version info

  • Python version used for development: 3.6.7

Documentation issue in Developing Your First Skill

I'm submitting a...


[ ] Regression (a behavior that used to work and stopped working in a new release)
[ ] Bug report  
[ ] Performance issue
[ ] Feature request
[x ] Documentation issue or request
[ ] Other... Please describe:

In the 'Developing Your First Skill' document under the 'CancelAndStopIntent handler' section of 'Option 1: Implementation using handler classes', the documentation says that we are creating an anonymous function on the fly using Python's in-built lambda function. This seems to be a bit misleading. The function 'is_intent_name' is not used in the code sample.

Expected Behavior

Current Behavior

Possible Solution

// Not required, but suggest a fix/reason for the bug,
// or ideas how to implement the addition or change

Steps to Reproduce (for bugs)

// Provide a self-contained, concise snippet of code
// For more complex issues provide a repo with the smallest sample that reproduces the bug
// Including business logic or unrelated code makes diagnosis more difficult

Context

Your Environment

  • ASK SDK for Python used: x.x.x
  • Operating System and version:

Python version info

  • Python version used for development:

Incorrect handling of SessionEndedRequest requests where error type is "ENDPOINT_TIMEOUT"

I'm submitting a...


[ ] Regression (a behavior that used to work and stopped working in a new release)
[x] Bug report  
[ ] Performance issue
[ ] Feature request
[ ] Documentation issue or request
[ ] Other... Please describe:

If your backend takes too long to respond (I think over 8 seconds), Alexa will say "The requested skill took too long to respond" and send a SessionEndedRequest request to your skill with the error type set to ENDPOINT_TIMEOUT i.e:

{
	"version": "1.0",
	"session": {
		...
	},
	"context": {
		...
	},
	"request": {
		"type": "SessionEndedRequest",
		"requestId": "...",
		"timestamp": "...",
		"locale": "en-GB",
		"reason": "ERROR",
		"error": {
			"type": "ENDPOINT_TIMEOUT",
			"message": "An exception occurred while dispatching the request to the skill."
		}
	}
}

Instead of this request being handled by the handler for SessionEndedRequest requests, the serializer.deserialize call to create a RequestEnvelope object will throw an error: SerializationException: ENDPOINT_TIMEOUT is not a valid SessionEndedErrorType.

Expected Behavior

The request should be handled by the handler for SessionEndedRequest requests.

Current Behavior

The serializer.deserialize call will throw an error: SerializationException: ENDPOINT_TIMEOUT is not a valid SessionEndedErrorType.

Possible Solution

This can be fixed by adding ENDPOINT_TIMEOUT as one of the values in the SessionEndedErrorType Enum in https://github.com/alexa/alexa-apis-for-python/blob/master/ask-sdk-model/ask_sdk_model/session_ended_error_type.py . I could provide a PR for the change I'm suggesting but the repo where the change would be effected does not accept pull requests.

Steps to Reproduce (for bugs)

Here is a sample Django view and Alexa request handlers for reproducing the error:

import logging
import time

from ask_sdk_model import RequestEnvelope
from ask_sdk_core.skill_builder import SkillBuilder
from ask_sdk_core.utils import is_request_type
from django.http import JsonResponse, HttpResponseBadRequest
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST

logger = logging.getLogger("alexa")

skill_builder = SkillBuilder()
request_handler = skill_builder.request_handler


@request_handler(
    can_handle_func=lambda h: not is_request_type("SessionEndedRequest")(h)
)
def launch_request_handler(handler_input):
    time.sleep(10)
    logger.debug("Not SessionEndedRequest")
    """ Handles everything that is not a SessionEndedRequest. """
    return handler_input.response_builder.speak("Hello and Goodbye").response


@request_handler(can_handle_func=is_request_type("SessionEndedRequest"))
def session_ended_request_handler(handler_input):
    """ Invoked when Alexa ends the session. """
    logger.debug("SessionEndedRequest")
    return handler_input.response_builder.response


@skill_builder.exception_handler(can_handle_func=lambda i, e: True)
def all_exception_handler(handler_input, exception):
    """ Catches all exceptions raised during intent handler invocation. """
    logger.error(exception, exc_info=True)
    return handler_input.response_builder.speak("An error occurred").response


skill = skill_builder.create()


@require_POST
@csrf_exempt
def process_skill_request(request, *args, **kwargs):
    logger.debug("Request body:\n%s ", request.body)
    if not request.body:
        return HttpResponseBadRequest()
    request_envelope = skill.serializer.deserialize(
        payload=request.body, obj_type=RequestEnvelope)
    response_envelope = skill.invoke(
        request_envelope=request_envelope, context=None)
    response = skill.serializer.serialize(response_envelope)
    logger.debug("Response:\n%s", response)
    return JsonResponse(response)

Here is the traceback for the exception raised:

Traceback (most recent call last):
  File "/home/simon/envs/ask-sdk-test/local/lib/python2.7/site-packages/django/core/handlers/exception.py", line 41, in inner
    response = get_response(request)
  File "/home/simon/envs/ask-sdk-test/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/home/simon/envs/ask-sdk-test/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/simon/envs/ask-sdk-test/local/lib/python2.7/site-packages/django/views/decorators/http.py", line 40, in inner
    return func(request, *args, **kwargs)
  File "/home/simon/envs/ask-sdk-test/local/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
    return view_func(*args, **kwargs)
  File "/home/simon/oss/ask_sdk_test/alexa/views.py", line 51, in process_skill_request
    payload=request.body, obj_type=RequestEnvelope)
  File "/home/simon/envs/ask-sdk-test/local/lib/python2.7/site-packages/ask_sdk_core/serialize.py", line 167, in deserialize
    return self.__deserialize(payload, obj_type)
  File "/home/simon/envs/ask-sdk-test/local/lib/python2.7/site-packages/ask_sdk_core/serialize.py", line 228, in __deserialize
    return self.__deserialize_model(payload, obj_type)
  File "/home/simon/envs/ask-sdk-test/local/lib/python2.7/site-packages/ask_sdk_core/serialize.py", line 364, in __deserialize_model
    raise SerializationException(str(e))
SerializationException: ENDPOINT_TIMEOUT is not a valid SessionEndedErrorType

Context

Whenever my backend fails to respond within 8 seconds, I get a SerializationException error instead of my SessionEndedRequest request handler being invoked.

Your Environment

  • ASK SDK for Python used: 1.8.0
  • Operating System and version: Ubuntu 16.04

I've only tested this with a Django backend, though may be also occurring with other Python backends.

Python version info

  • Python version used for development: 2.7.12

is_intent_name returns false on valid intents for CanFulfillIntentRequests

I'm submitting a...


[ ] Regression (a behavior that used to work and stopped working in a new release)
[x] Bug report  
[ ] Performance issue
[ ] Feature request
[ ] Documentation issue or request
[ ] Other... Please describe:

Expected Behavior

is_intent_name('HelpIntent')(handler_input) should return True if a CanFulfillIntentRequest is for the HelpIntent intent.

Current Behavior

is_intent_name('HelpIntent')(handler_input) returns False if a CanFulfillIntentRequest is for the HelpIntent intent.

Alternative Solution

This does complicate pretty much every can_handle. Existing logic would send CFIRs to Intents mean to actually handle IntentRequests unless they already include and is_request_type('IntentRequest')(handler_input). So an alternative solution would be to provide a new intent name helper? That way, existing logic wouldn't be influenced.
i.e., is_canfulfill_intent_name

Does not show exception in logs

I am using ASK SDK Python 3.6 running on AWS Lambda
Whenever it gets error or exception it does not show in Logs (Cloudwatch), instead it shows:

all_exception_handler() takes 1 positional argument but 2 were given: TypeError
Traceback (most recent call last):
File "/var/task/ask_sdk_core/skill_builder.py", line 98, in wrapper
request_envelope=request_envelope, context=context)
File "/var/task/ask_sdk_core/skill.py", line 200, in invoke
handler_input=handler_input)
File "/var/task/ask_sdk_runtime/dispatch.py", line 131, in dispatch
return exception_handler.handle(handler_input, e)
File "/var/task/ask_sdk_runtime/skill_builder.py", line 170, in <lambda>
handler_input, exception)
TypeError: all_exception_handler() takes 1 positional argument but 2 were given

I have included all given methods including
def fallback_handler
def session_ended_request_handler
def all_exception_handler

is it referring to decorator

Thanks

resolutions property being stripped from updatedIntent

I'm submitting a...


[ ] Regression (a behavior that used to work and stopped working in a new release)
[X] Bug report
[ ] Performance issue
[ ] Feature request
[ ] Documentation issue or request
[ ] Other... Please describe:

When responding to multi-turn dialog intents, I'm populating a slot with default information and adding a Resolutions object to the resolutions property of the slot object. The slot looks correct when I print it out (as viewed in CloudWatch) before sending back to Alexa but the simulator in the Dev Console shows that updatedIntent slot does not contain the resolutions property.

At this point, Alexa proceeds to say something like "please respond with yes or no" since this is text I've provided if the validation for that slot fails. There are a couple of things worth mentioning at this stage in the dialog:

  1. The slot is of a custom type.
  2. Validation is enabled.
  3. The 'value' I'm providing in the slot via my handler is one of the exact values defined by the custom type and yet, Alexa still prompts the user as if they provided invalid information. I assume this is because the resolutions property is missing from the slot.

Expected Behavior

I expect the resolution property to be passed back in the response under the updatedIntent object.

Current Behavior

Summary above outlines behavior.

Possible Solution

Steps to Reproduce (for bugs)

class StartedEditIntentHandler(AbstractRequestHandler):

    def can_handle(self, handler_input):
        return (is_intent_name('EditIntent')(handler_input) and
                handler_input.request_envelope.request.dialog_state ==
                DialogState.STARTED)

    def handle(self, handler_input):
            intent = handler_input.request_envelope.request.intent
            # <snipped code>
            intent.slots['is_empty'].value = 'no'
            intent.slots['is_empty'].resolutions = Resolutions([
                Resolution(authority="foo",
                           status=Status(StatusCode.ER_SUCCESS_MATCH),
                           values=[ValueWrapper(Value(name='True'))])])

            print(f"slot = {intent.slots['is_empty']}") # This will show up in CloudWatch

        return handler_input.response_builder.add_directive(
            DelegateDirective(intent)).response

This is what I see in the JSON output window in the simulator, notice that the resolutions property is not present:

  ...
  "updatedIntent": {
    "name": "EditIntent",
    "confirmationStatus": "NONE",
    "slots": {
      "is_empty": {
        "name": "is_empty",
        "value": "no",
        "confirmationStatus": "NONE"
      },
      ...

I can see the resolutions property present in output from the print statement (taken from CloudWatch logs):

slot = {'confirmation_status': 'NONE',
'name': 'is_empty',
'resolutions': {'resolutions_per_authority': [{'authority': 'foo',
'status': {'code': 'ER_SUCCESS_MATCH'},
'values': [{'value': {'id': None,
'name': 'True'}}]}]},
'value': 'no'}

Context

My use case is that I've setup a multi-turn dialog in the dialog model. I have three slots which need to be filled. One of the slots, 'is_empty', may have a default value. If the slot does not have a default value then I want Alexa to prompt the user for the information and also validate the response from the user (this is important). If the user has a default, which I'm determining elsewhere, I want to populate the 'is_empty' slot with this default value and not have Alexa prompt the user for it.

In the dialog model, I've configured a validation rule for the slot using the "Accept only Slot Type's values and synonyms" rule. The slot type is custom, also important since resolutions are only used for custom or extended types.

Documentation does cover Manually delegate the dialog to set default values; however, this specific use case of throwing validation into the mix isn't mentioned so I'm not sure if my expectations are correct. Clearly, I could do the validation in my own code and just elicit the slot again if the user provides invalid info but it would be a lot nicer/easier to let the dialog model take care of it instead.

Your Environment

  • ASK SDK for Python used: x.x.x
    Package Version

ask-sdk 1.4.0
ask-sdk-core 1.4.0
ask-sdk-dynamodb-persistence-adapter 1.4.0
ask-sdk-model 1.4.0
ask-sdk-runtime 1.4.0
boto3 1.9.51
botocore 1.12.51

Python version info

  • Python version used for development: 3.6.7

Make python name to JSON name attribute mapping via `attribute_map` optional.

I'm submitting a...


[ ] Regression (a behavior that used to work and stopped working in a new release)
[ ] Bug report  
[ ] Performance issue
[x] Feature request
[ ] Documentation issue or request
[ ] Other... Please describe:

Expected Behavior

When serializing, use the python attribute name if not present in attribute_map.

Current Behavior

If a name of a python attribute is the same as its name in the serialized object, it still needs to be present in the attribute_map.

Possible Solution

// Not required, but suggest a fix/reason for the bug,
// or ideas how to implement the addition or change

I guess it's a one-line change in the Serializer? Sorry, didn't dig into it too much.

Steps to Reproduce (for bugs)

// Provide a self-contained, concise snippet of code
// For more complex issues provide a repo with the smallest sample that reproduces the bug
// Including business logic or unrelated code makes diagnosis more difficult
@attr.s
class Skill:
    launch_count = attr.ib()

    deserialized_type = {'launch_count': 'int'}
    attribute_map = {'launch_count': 'launch_count'} # needless
    # snip

Context

I'm using the DefaultSerializer to serialize my models for DynamoDB. It's really cool. I want to suggest of using the python's attribute name as the name of the value in the serialized object if it is not present in the attribute_map mapping. In the example posted above, the attribute_map could be removed altogether, a pattern in a lot of my models. This direct mapping is also quite common in the SDK models, for example here in SimpleCard

Your Environment

  • ASK SDK for Python used: 1.5.0
  • Operating System and version: OS X

Python version info

  • Python version used for development: 3.7

Echo Buttons supported in python ASK SDK ?

I need bit of help from you. I want to know if echo buttons are supported in python ask sdk ?

I have seen samples of echo buttons in node js but nothing in python. It would be a huge favor if i can get any sample code which demonstrates usage of echo buttons in python ask sdk.

Is there an ask cli for python ?

I'm submitting a...


[ ] Regression (a behavior that used to work and stopped working in a new release)
[ ] Bug report  
[ ] Performance issue
[ x] Feature request
[ ] Documentation issue or request
[ ] Other... Please describe:

Context

There is a cool ASK CLI for nodejs . i was wondering if we have something like that for python.

recurring failures in timestamp verification after launch request

I'm submitting a...


[x] Regression (a behavior that used to work and stopped working in a new release)
[x] Bug report  
[ ] Performance issue
[ ] Feature request
[ ] Documentation issue or request
[ ] Other... Please describe:

Expected Behavior

Submitting requests via ADC > Test > Alexa Simulator. I expect to be able to begin a dialog.
VME Presidential Race, amzn1.ask.skill.e694c788-d24c-4959-a075-cea353804a1f

Current Behavior

When I submit requests via ADC > Test > Alexa Simulator, the invocation works and runs the launch intent correctly. However, all subsequent commands produce "Timestamp verification failure."

INFO:werkzeug: * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 190-149-512
skill code version is 0.3.0
Request received: {'locale': 'en-US',
 'object_type': 'LaunchRequest',
 'request_id': 'amzn1.echo-api.request.54b6d9f7-bd63-4028-b401-9ac3526f352b',
 'timestamp': datetime.datetime(2019, 7, 1, 14, 45, tzinfo=tzutc())}
127.0.0.1 - - [01/Jul/2019 10:45:00] "POST / HTTP/1.1" 200 -
INFO:werkzeug:127.0.0.1 - - [01/Jul/2019 10:45:00] "POST / HTTP/1.1" 200 -
ERROR:flask.app:Request verification failed
Traceback (most recent call last):
  File "/Users/fzimmerman/anaconda3/lib/python3.6/site-packages/flask_ask_sdk/skill_adapter.py", line 240, in dispatch_request
    http_request_body=content)
  File "/Users/fzimmerman/anaconda3/lib/python3.6/site-packages/ask_sdk_webservice_support/webservice_handler.py", line 148, in verify_request_and_dispatch
    deserialized_request_env=request_envelope)
  File "/Users/fzimmerman/anaconda3/lib/python3.6/site-packages/ask_sdk_webservice_support/verifier.py", line 437, in verify
    raise VerificationException("Timestamp verification failed")
ask_sdk_webservice_support.verifier.VerificationException: Timestamp verification failed
127.0.0.1 - - [01/Jul/2019 10:45:10] "POST / HTTP/1.1" 400 -
INFO:werkzeug:127.0.0.1 - - [01/Jul/2019 10:45:10] "POST / HTTP/1.1" 400 -
ERROR:flask.app:Request verification failed
Traceback (most recent call last):
  File "/Users/fzimmerman/anaconda3/lib/python3.6/site-packages/flask_ask_sdk/skill_adapter.py", line 240, in dispatch_request
    http_request_body=content)
  File "/Users/fzimmerman/anaconda3/lib/python3.6/site-packages/ask_sdk_webservice_support/webservice_handler.py", line 148, in verify_request_and_dispatch
    deserialized_request_env=request_envelope)
  File "/Users/fzimmerman/anaconda3/lib/python3.6/site-packages/ask_sdk_webservice_support/verifier.py", line 437, in verify
    raise VerificationException("Timestamp verification failed")
ask_sdk_webservice_support.verifier.VerificationException: Timestamp verification failed

Possible Solution

// Not required, but suggest a fix/reason for the bug,
// or ideas how to implement the addition or change

Am I using correct deserializer (webservice v. ask-flask?) Is timeout value too short?

Steps to Reproduce (for bugs)

// Provide a self-contained, concise snippet of code
// For more complex issues provide a repo with the smallest sample that reproduces the bug
// Including business logic or unrelated code makes diagnosis more difficult

flask run attached code (presidential.py)
ADC Test: "open candidate watch"
"any candidate name" => timestamp error

Context

blocking me

Your Environment

  • ASK SDK for Python used: 1.10.2
  • Operating System and version: OSX

Python version info

Allow CanFulfillIntentRequests

I'm submitting a...

[ ] Regression (a behavior that used to work and stopped working in a new release)
[ ] Bug report  
[ ] Performance issue
[x] Feature request
[ ] Documentation issue or request
[ ] Other... Please describe:

Expected Behavior

CanFulfillIntentRequest request structures should be supported.

Current Behavior

If a request of type CanFulfillIntentRequest is received, it fails validation during Request deserialization.

Context

Notice I'm not asking for canFulfill "support" within the SDK (helper functions, etc), just allowing the request canFulfill structure to pass deserialization validation. Without it, it appears we'll have to resort to hacking the SDK itself.

Documentation display update required in RST files.

I'm submitting a...


[ ] Regression (a behavior that used to work and stopped working in a new release)
[ ] Bug report  
[ ] Performance issue
[ ] Feature request
[ ] Documentation issue or request
[x] Other... Please describe: documentation css update.

Expected Behavior

The documentation text should wrap to the next line when it's longer.

Current Behavior

The documentation text overflows when the text is longer than intended.
image

Possible Solution

Provide a global width or add custom css to wrap when the text overflows.

Steps to Reproduce (for bugs)

link to the documentation.
Note*: I have seen this in multiple locations. We should provide a fix at the global level.

skill.custom_user_agent unsupported operand type

I'm submitting a...


[ ] Regression (a behavior that used to work and stopped working in a new release)
[x] Bug report  
[ ] Performance issue
[ ] Feature request
[ ] Documentation issue or request
[ ] Other... Please describe:

Expected Behavior

I expect the skill_adapter to register properly, but it is throwing an error message.

Current Behavior

fzimmerman@mifarfzimmer-m1:~/voice/AltBrains_Basketball/selfhosted$ flask routes
Traceback (most recent call last):
  File "/Users/fzimmerman/anaconda3/bin/flask", line 10, in <module>
    sys.exit(main())
  File "/Users/fzimmerman/anaconda3/lib/python3.6/site-packages/flask/cli.py", line 894, in main
    cli.main(args=args, prog_name=name)
  File "/Users/fzimmerman/anaconda3/lib/python3.6/site-packages/flask/cli.py", line 557, in main
    return super(FlaskGroup, self).main(*args, **kwargs)
  File "/Users/fzimmerman/anaconda3/lib/python3.6/site-packages/click/core.py", line 697, in main
    rv = self.invoke(ctx)
  File "/Users/fzimmerman/anaconda3/lib/python3.6/site-packages/click/core.py", line 1066, in invoke
    return _process_result(sub_ctx.command.invoke(sub_ctx))
  File "/Users/fzimmerman/anaconda3/lib/python3.6/site-packages/click/core.py", line 895, in invoke
    return ctx.invoke(self.callback, **ctx.params)
  File "/Users/fzimmerman/anaconda3/lib/python3.6/site-packages/click/core.py", line 535, in invoke
    return callback(*args, **kwargs)
  File "/Users/fzimmerman/anaconda3/lib/python3.6/site-packages/click/decorators.py", line 17, in new_func
    return f(get_current_context(), *args, **kwargs)
  File "/Users/fzimmerman/anaconda3/lib/python3.6/site-packages/flask/cli.py", line 411, in decorator
    with __ctx.ensure_object(ScriptInfo).load_app().app_context():
  File "/Users/fzimmerman/anaconda3/lib/python3.6/site-packages/flask/cli.py", line 372, in load_app
    app = locate_app(self, import_name, name)
  File "/Users/fzimmerman/anaconda3/lib/python3.6/site-packages/flask/cli.py", line 235, in locate_app
    __import__(module_name)
  File "/Users/fzimmerman/voice/AltBrains_Basketball/selfhosted/exlambda.py", line 30, in <module>
    skill=sb.create(), skill_id="amzn1.ask.skill.5cbfc4d6-35dd-436f-9dbe-bab5dda42409", app=app)
  File "/Users/fzimmerman/anaconda3/lib/python3.6/site-packages/flask_ask_sdk/skill_adapter.py", line 151, in __init__
    self._skill.custom_user_agent += " flask-ask-sdk"
TypeError: unsupported operand type(s) for +=: 'NoneType' and 'str'

Trying to run python skill_

Possible Solution

likely my error although I don't understand what line 151 is doing -- what is it trying to do there

Steps to Reproduce (for bugs)

#import json
import logging
import random

from flask import Flask
from ask_sdk_core.skill_builder import SkillBuilder
from flask_ask_sdk.skill_adapter import SkillAdapter

from ask_sdk_core.utils import is_request_type, is_intent_name
from ask_sdk_core.handler_input import HandlerInput

from ask_sdk_model.ui import SimpleCard
from ask_sdk_model import Response, RequestEnvelope

#import ssml2text

app = Flask(__name__)

logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)

sb = SkillBuilder()

**skill_adapter = SkillAdapter(
    skill=sb.create(), skill_id="amzn1.ask.skill.5cbfc4d6-35dd-436f-9dbe-bab5dda42409", app=app)** # I believe this is correct skill id, something may be wrong here...

type_of_shot = "type_of_shot"

# game-specific functions that are not responses to Intents

def setup_situation():
    # sets up the situation for the player
    player_team = ['Your team']
    relation = [' is behind by ', ' is down by ', ' trails by ']
    points_down = 1 # two, three ...
    pointspread = ['one']
    conjunction = [' with ']
    time_remaining = ['the clock winding down', 'time almost elapsed', 'the buzzer about to sound', 'the last possession']
    possession = ['Your ball. ', 'Over to you. ', 'Your possession. ']
    stage_of_season = [' championship game ', ' conference championship ', ' conference tournament']
    NBA_stages = [' game five'] * 3 + ['game six'] * 3 + [' game seven'] * 3
    overtime = [' regulation'] * 10 + [' the first half'] * 3 + [ ' overtime' ] * 2 + [' double overtime'] * 1 + [' triple overtime'] * 1
    special_circumstances = ['Homecoming']
    situation = random.choice(player_team) +  random.choice(relation)  + random.choice(pointspread) + random.choice(conjunction) + random.choice(time_remaining) + ' in ' + random.choice(overtime) + '. '
    print(situation)

    return situation

def update_situation(myshot):
    points_down = 1
    raw_probability = 0.5
    contesteds = ['Embarrassingly open. '] * 3 + ['Wide open. '] * 5 + ['It is contested... '] * 20 + ['Fiercely contested. '] * 10
    contestedness = random.uniform(.8, 1.0)
    # distance_modifier
    adjusted_probability = raw_probability * contestedness
    this_try = random.random()

    if this_try < adjusted_probability:

        points_down = points_down - 2
        basket_made = 1
        call = random.choice(['Rattles round the rim and in. ', 'Swish! ', 'That is good. ', 'Good. ', 'Drained it. ', 'Basket. ', 'Friendly bounce! ', 'Nothing but net! '])
        compliment = random.choice(['That was clutch. ', 'Great shot. ', 'You da man. ', 'Awesome. ', 'Wow. ', 'Amazing. ', 'Wow. Just wow.'])
    else:

        points_down = points_down
        basket_made = 0
        call = random.choice(['Short. ', 'Just short. ', 'Air ball. ', 'Long. ', 'Way long. ', 'Rattles off the rim. ', 'Rattles round the rim and out. ' ])
        taunt = random.choice(['Ha ha. ', 'Choke. ', 'Tough luck. ', 'You suck. ', 'I win. ', 'I won. ', ' Go me. ', 'I have bragging rights. '])
    # report on how tough the shot was

    percentage_this_try = "{:.0%}".format(this_try)
    percentage_probability = "{:.0%}".format(adjusted_probability)
    print(percentage_this_try, percentage_probability, basket_made)


    if points_down < 0:
       outcome_description = call + random.choice(['For the win! ', 'You win! ']) + compliment
    if points_down > 0:
        outcome_description = call + random.choice(['You lose! ', 'That is an L. ']) + taunt

    print(outcome_description)

    return outcome_description


@sb.request_handler(can_handle_func=is_request_type("LaunchRequest"))
def launch_request_handler(handler_input):
    """Handler for Skill Launch."""
    # type: (HandlerInput) -> Response
    call_to_action = ['Call your shot. ', 'Your turn. ', 'Your shot. ', 'You go.', 'Say type of shot. ']
    speech_text ="Welcome to AltBrains Basketball. "  + setup_situation() + random.choice(call_to_action)

    return handler_input.response_builder.speak(speech_text).set_card(
        SimpleCard("Welcome to AltBrains Basketball", speech_text)).set_should_end_session(
        False).response

@sb.request_handler(can_handle_func=is_intent_name("TakeShotIntent"))
def take_shot_intent_handler(handler_input):
    """Handler for TakeShotIntent."""
    # type: (HandlerInput) -> Response

    slots = handler_input.request_envelope.request.intent.slots
    #myshot = slots['Item'].value
    myshot = slots["type_of_shot"].value
    print('myshot was ' + str(myshot))
    result = update_situation(myshot)
    pause = '<break time=\"3s\"/>'
    newgame = ['New game. ', 'Rematch. ', 'Play again? ', 'Lets play again. ' ]
    transition = ' Call your shot, or say goodbye. '
    intro = ['Your attempt was a ', 'You tried a ', ' ', 'That was a ']
    speech_text = random.choice(intro) + myshot + '. ' + result + pause +  random.choice(newgame) + setup_situation() + transition
    card_text = result + transition
    return handler_input.response_builder.speak(speech_text).set_card(
        SimpleCard("Your Shot", card_text)).set_should_end_session(False).response


@sb.request_handler(can_handle_func=is_intent_name("AMAZON.HelpIntent"))
def help_intent_handler(handler_input):
    """Handler for Help Intent."""
    # type: (HandlerInput) -> Response
    speech_text = "Call your shot. For example, say jump shot or sky hook."

    return handler_input.response_builder.speak(speech_text).ask(
        speech_text).set_card(SimpleCard(
            "Shot Help", speech_text)).response


@sb.request_handler(
    can_handle_func=lambda handler_input:
        is_intent_name("AMAZON.CancelIntent")(handler_input) or
        is_intent_name("AMAZON.StopIntent")(handler_input))
def cancel_and_stop_intent_handler(handler_input):
    """Single handler for Cancel and Stop Intent."""
    # type: (HandlerInput) -> Response
    speech_text = "Thanks for playing!"

    return handler_input.response_builder.speak(speech_text).set_card(
        SimpleCard("Thanks for playing!", speech_text)).response


@sb.request_handler(can_handle_func=is_intent_name("AMAZON.FallbackIntent"))
def fallback_handler(handler_input):
    """AMAZON.FallbackIntent is only available in en-US locale.
    This handler will not be triggered except in that locale,
    so it is safe to deploy on any locale.
    """
    # type: (HandlerInput) -> Response
    speech = (
        "I'm not sure what you want me to do.")
    reprompt = "You can call your shot by saying type of shot followed by distance. For example, jump shot from twenty feet."
    handler_input.response_builder.speak(speech).ask(reprompt)
    return handler_input.response_builder.response


@sb.request_handler(can_handle_func=is_request_type("SessionEndedRequest"))
def session_ended_request_handler(handler_input):
    """Handler for Session End."""
    # type: (HandlerInput) -> Response
    return handler_input.response_builder.response


@sb.exception_handler(can_handle_func=lambda i, e: True)
def all_exception_handler(handler_input, exception):
    """Catch all exception handler, log exception and
    respond with custom message.
    """
    # type: (HandlerInput, Exception) -> Response
    logger.error(exception, exc_info=True)

    speech = "Sorry, I couldn't understand your intent. Please try again!!"
    handler_input.response_builder.speak(speech).ask(speech)

    return handler_input.response_builder.response


handler = sb.lambda_handler()

Context

run flask app
(flask routes is short cut around lazy loading)

Your Environment

  • ASK SDK for Python used: 1.9.0
  • Operating System and version: OSX

Python version info

  • Python version used for development: 3.6.7

Dynamic Slots in Alexa Skill

I am developing an Alexa skill. I need to build dynamic slots using python as-sdk. I'm using a data coming from an api in JSON format that changes from time-to-time. For example,
My alexa skill prompts to the user: "Barcelona vs Real Madrid, Chelsea vs Manchester United and Arsenal vs Spurs matches are happening right now. Which match would you like to hear about" (of course this data changes from time-to-time)
User says: "Barcelona vs Read Madrid"
I should then be able to prompt the details of the match to the user from my live api. How can i make a dynamic slot of this problem handle this using ask-sdk code ?

I really need your help.

START RequestId: a16a9fa4-ac3a-11e8-911b-393c5e206000 Version: $LATEST

Can you all please help me. I am done with all the step mentioned. But I am not able to understand which folders are required inside "skill.zip" I tried with in-line editor and uploaded only that but it is also failing. Please let me know the solution. Thanks in advance. Do I have to upload all the 34 folders which are present in ask-sdk folder and create a folder 'hello_world' and place hello_world.py insider the newly created folder and zip all to skill.zip and upload whole bunch?
I am also getting "START RequestId: a16a9fa4-ac3a-11e8-911b-393c5e206000 Version: $LATEST" error as well.

Flask app runs in dev, doesn't work in apache mod_wsgi

I'm submitting a...


[ ] Regression (a behavior that used to work and stopped working in a new release)
[ ] Bug report  
[ ] Performance issue
[ ] Feature request
[x] Documentation issue or request
[x ] Other... Please describe:

Expected Behavior

App basketball.py is working correctly on Alexa Dev Console > Test > ngrok > endpoint > local dev machine > Flask.

Current Behavior

Now I want to move same app to Apache mod_wsgi since Flask is not production ready. Unfortunately when I then call the app via the wsgi, it does not work and returns null to alexa.

Possible Solution

// Not required, but suggest a fix/reason for the bug,
// or ideas how to implement the addition or change

I suppose I could try to use the generic webservice but then a) I wouldn't be getting the benefits of Flask in dev and b) I don't know how to translate into the request formats for mod_wsgi.

Steps to Reproduce (for bugs)

// Provide a self-contained, concise snippet of code
// For more complex issues provide a repo with the smallest sample that reproduces the bug
// Including business logic or unrelated code makes diagnosis more difficult

basketball.wsgi:

#! /usr/bin/python3
import sys
import logging
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)-8s %(message)s', datefmt='%a, %d %b %Y %H:%M:%S', filename='/home/ubuntu/voice/AltBrains_Basketball/altbrains-basketball.log', filemode='a+')
path = '/home/ubuntu/voice/AltBrains_Basketball/basketball.py'
if path not in sys.path:
   sys.path.insert(0, path)
logging.debug(sys.path)
logging.debug(sys.version)
import getpass
logging.debug(getpass.getuser())
from basketball import app as application
logging.debug(application)

The log shows that the endpoint triggers the wsgi (which means the apache conf is correct) and the wsgi tries to run the app, but fails returning null json.

Tue, 07 May 2019 00:23:12 DEBUG    ['/home/ubuntu/voice/AltBrains_Baske
tball/basketball.py', '/home/ubuntu/voice/AltBrains_Basketball', '/usr/
lib/python36.zip', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynloa
d', '/home/ubuntu/.local/lib/python3.6/site-packages', '/usr/local/lib/
python3.6/dist-packages', '/usr/lib/python3/dist-packages']
Tue, 07 May 2019 00:23:12 DEBUG    3.6.7 (default, Oct 22 2018, 11:32:1
7)
[GCC 8.2.0]
Tue, 07 May 2019 00:23:12 DEBUG    ubuntu
Tue, 07 May 2019 00:23:13 DEBUG    <Flask 'basketball'>

Context

Your Environment

  • ASK SDK for Python used: 1.9.0
  • Operating System and version: OS/x

Python version info

  • Python version used for development: 3.6.7

Improvements

I'm submitting a...


[ ] Regression (a behavior that used to work and stopped working in a new release)
[ ] Bug report  
[ ] Performance issue
[ ] Feature request
[ x] Documentation issue or request
[ ] Other... Please describe:

The system prompts should not use the Python prompt >>> as the instructional text is confusing.
Also the spelling in the activate command is wrong. The directory name is plural: "Scripts"

Expected Behavior

Current Behavior

Possible Solution

// Not required, but suggest a fix/reason for the bug,
// or ideas how to implement the addition or change

Steps to Reproduce (for bugs)

// Provide a self-contained, concise snippet of code
// For more complex issues provide a repo with the smallest sample that reproduces the bug
// Including business logic or unrelated code makes diagnosis more difficult

Context

Your Environment

  • ASK SDK for Python used: x.x.x
  • Operating System and version:

Python version info

  • Python version used for development:

AccessToken attribute incorrect

I'm submitting a...


[ ] Regression (a behavior that used to work and stopped working in a new release)
[ ] Bug report  
[ ] Performance issue
[ ] Feature request
[X] Documentation issue or request
[ ] Other... Please describe:

Documentation incorrectly labels the 'accessToken' attribute in the request envelope when it should be 'access_token'

Expected Behavior

Current Behavior

Possible Solution

Update documentation to reference accessToken = handler_input.request_envelope.context.system.user.access_token

Context

This is related to the AccountLinking process

Cannot use ups service models

I'm submitting a...


[ ] Regression (a behavior that used to work and stopped working in a new release)
[ x ] Bug report  
[ ] Performance issue
[ ] Feature request
[ ] Documentation issue or request
[ ] Other... Please describe:

Expected Behavior

I'm trying to build a skill that takes user email and sends an email to it.
For this I am checking for req_envelope.context.system.user.permissions and req_envelope.context.system.user.permissions.consent_token and once both values are present, I am invoking `handler_input.service_client_factory.get_ups_service().get_profile_email()

I expect to get the email id in some form in the return value of the function as described in the documentation

Current Behavior

I get the following output in my logs:

Couldn't parse response body: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<HTML><HEAD><META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-1">
<TITLE>ERROR: The request could not be satisfied</TITLE>
</HEAD><BODY>
<H1>403 ERROR</H1>
<H2>The request could not be satisfied.</H2>
<HR noshade size="1px">
Bad request.

<BR clear="all">
<HR noshade size="1px">
<PRE>
Generated by cloudfront (CloudFront)
Request ID: sSZtQPDhW9T1U5HgoA7wXUcTkY4GIr_AqG8cSIX34xz3btYwUSccMw==
</PRE>
<ADDRESS>
</ADDRESS>
</BODY></HTML>

I think there was a problem when the http request was built, not sure, please look into this at the earliest.
Also let me know if I am using it in an incorrect manner, I tried to follow the documentation at the best.

Your Environment

  • ASK SDK for Python used: 1.0.0
  • Operating System and version: Amazon Lambda
    CloudFront Logs

Missing support for type annotations in handler functions

I'm submitting a...


[ ] Regression (a behavior that used to work and stopped working in a new release)
[X] Bug report  
[ ] Performance issue
[ ] Feature request
[ ] Documentation issue or request
[ ] Other... Please describe:

Expected Behavior

I can use handlers with type annotations when using python 3:

@sb.request_handler(can_handle_func=is_request_type("LaunchRequest"))
def launch_request_handler(handler_input: HandlerInput):
    ...

Current Behavior

I cannot use type annotations because then the lambda function fails to execute:

$ serverless invoke local -f test -p events/test-event.json

Traceback (most recent call last):
  File "/usr/local/lib/node_modules/serverless/lib/plugins/aws/invokeLocal/invoke.py", line 60, in <module>

    module = import_module(args.handler_path.replace('/', '.'))
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 994, in _gcd_import
  File "<frozen importlib._bootstrap>", line 971, in _find_and_load
  File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 678, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "./lambda_function.py", line 20, in <module>
    response: ResponseFactory):
  File "./alexa_utils/skill.py", line 20, in decorator
    def wrapper(handler_input: HandlerInput):
  File "/Users/daniel/Workspace/alexa/venv/lib/python3.6/site-packages/ask_sdk_core/skill_builder.py", line 226, in wrapper
    handle_arg_spec = inspect.getargspec(handle_func)
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/inspect.py", line 1075, in getargspec
    raise ValueError("Function has keyword-only parameters or annotations"
ValueError: Function has keyword-only parameters or annotations, use getfullargspec() API which can support them

Possible Solution

The error message itself suggests to replace inspect.getargspec with inspect.getfullargspec. I am, however, not sure if this change may introduce incompatibilities with python 2.

Another solution would be to simply remove the checks and rely on the user using the interface correctly.

I guess even having a function signature with variable args or defaulting keyword arguments fail this test (e.g. def handler(handler_input, **kwargs) or def handler(*args)). The strict argument checking feels non-pythonic to me, most developers and libraries simply let the user crash into these problems. Also, the exception raised in such a case ( takes 1 positional argument but 2 were given) combined with the stack traces should be helpful enough to find the issue.

To be honest, this would be my preferred approach here as I currently see no advantages in the forced signature checking.

Steps to Reproduce (for bugs)

from ask_sdk_core.handler_input import HandlerInput
from ask_sdk_core.skill_builder import SkillBuilder
from ask_sdk_core.utils import is_request_type

sb = SkillBuilder()


@sb.request_handler(can_handle_func=is_request_type('LaunchRequest'))
def launch_request_handler(handler_input: HandlerInput):
    return handler_input.response_builder.speak('Hello World').response


lambda_handler = sb.lambda_handler()

Your Environment

ask-sdk==0.1.2
ask-sdk-core==0.1.2
ask-sdk-model==0.2.1

Python version info

Python 3.6.5 (default, Apr 25 2018, 14:26:36) 
[GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.39.2)] on darwin

This issue affects both my local development machine as well as the python36 lambda execution environment.

add emitWithState equivalent

I'm submitting a...


[ ] Regression (a behavior that used to work and stopped working in a new release)
[ ] Bug report  
[ ] Performance issue
[ X] Feature request
[ ] Documentation issue or request
[ ] Other... Please describe:

I am submitting this because I read about it on the node js side. Here is the link:

alexa/alexa-skills-kit-sdk-for-nodejs#54

Basically, I wanted to see if this feature can be added to python or if there is a way to switch intents in python that I am missing. The post of the link above talks about using emitWithState in Node.

Different returned Slot ID

I'm submitting a...


[ ] Regression (a behavior that used to work and stopped working in a new release)
[x] Bug report  
[ ] Performance issue
[ ] Feature request
[ ] Documentation issue or request
[ ] Other... Please describe:

Not sure if SDK or Skills problem...

Hi I am trying to get the slots ID where I used single digits = 1, 2, 3 and so on...
I accessed it using:

slots = handler_input.request_envelope.request.intent.slots
IDnum = slots[slot_name].resolutions.resolutions_per_authority[0].values[0].value.id
ID_num = int(IDnum)

However I think I am not getting the correct ID since it goes to

In CatchAllExceptionHandler
invalid literal for int() with base 10: '001cbc059a402b3be7c99be558eaaf73'

Already read some problems regarding this however they might be using the NodeJS SDK, so really hard to compare. Also can I just add if there some ways to debug using Python's print function?

SDK Skills are not working

I've set up an SDK as explained in Technical documentation in SETTING UP ASK SDK on the below link. All SDK folders have been installed.

https://alexa-skills-kit-python-sdk.readthedocs.io/en/latest/GETTING_STARTED.html

After that, I've followed step-by-step guide that are mentioned in DEVELOPING YOUR FIRST SKILL on below link and implemented Hello World using handler classes.

https://alexa-skills-kit-python-sdk.readthedocs.io/en/latest/DEVELOPING_YOUR_FIRST_SKILL.html

Created .zip file of all the folders that are installed in SDK with helloworld.py folder in it and uploaded in console and also tried adding my helloworld.py file in asd_sdk folder and uploaded it in .zip but it's not working. When I test my lambda function it gives me below error.

{
"errorMessage": "Handler 'lambda_handler' missing on module 'hello_world'"
}

Handler 'lambda_handler' missing on module 'hello_world': 'module' object has no attribute 'lambda_handler'

I tried renaming the file helloworld to lambda_function but still it's not picking lambda handler function from hello_world.py. Tried both Python 2.7 and 3.6.

Add ability to delete persistent attributes via attributes_manager

I'm submitting a...


[ ] Regression (a behavior that used to work and stopped working in a new release)
[ ] Bug report  
[ ] Performance issue
[x] Feature request
[ ] Documentation issue or request
[ ] Other... Please describe:

Expected Behavior

Add a delete_persistent_attributes() method that allows an existing persistent attribute key value pair to be deleted, and provide an example in the documentation of how to do this.

Current Behavior

I believe this is currently not possible using the attributes manager, and instead a significantly more complex process directly using DynamoDB must be used.

Possible Solution

This feature seems to have been recently added to the node.js sdk. Looking for the same ability in the python sdk.
// Not required, but suggest a fix/reason for the bug,
// or ideas how to implement the addition or change


## Steps to Reproduce (for bugs)

// Provide a self-contained, concise snippet of code
// For more complex issues provide a repo with the smallest sample that reproduces the bug
// Including business logic or unrelated code makes diagnosis more difficult


## Context
<!--- How has this issue affected you? What are you trying to accomplish? -->
<!--- Providing context helps us come up with a solution that is most useful in the real world -->
The behavior of my skill changes depending upon whether or not the user has previously stored "favorites" data as persistent attributes. I want the user to be able to delete that saved "favorites" data so that, should they wish, they can go back to the behavior without favorites by deleting those favorites. 
## Your Environment
<!--- Include as many relevant details about the environment where the bug was discovered -->
* ASK SDK for Python used: x.x.x
* Operating System and version:

## Python version info
* Python version used for development:

flask-ask-sdk Timestamp Verification failing from ADC Test Emulator

I'm submitting a...


[ ] Regression (a behavior that used to work and stopped working in a new release)
[ x] Bug report  
[ ] Performance issue
[ ] Feature request
[ ] Documentation issue or request
[ ] Other... Please describe:

Expected Behavior

I am submitting request from the Alexa Developer Console Test emulator to a flask-ask-sdk server running on my local dev machine. It was working Wed. and I expected it to work today.

Current Behavior

Instead, I am getting TimeStamp Verification error. It looks as if the ADC clock and my local clock are possibly out of sync.

Possible Solution

// Not required, but suggest a fix/reason for the bug,
// or ideas how to implement the addition or change

Steps to Reproduce (for bugs)

// Provide a self-contained, concise snippet of code
// For more complex issues provide a repo with the smallest sample that reproduces the bug
// Including business logic or unrelated code makes diagnosis more difficult

Alexa, open alt brains basketball

ADC console:

{
    "header": {
        "namespace": "SkillDebugger",
        "name": "CaptureError",
        "messageId": "e16d75d4-1afe-4ad4-809f-842aa2d95029"
    },
    "payload": {
        "skillId": "amzn1.ask.skill.5cbfc4d6-35dd-436f-9dbe-bab5dda42409",
        "timestamp": "**2019-05-03T15:21:43.808Z"**,
        "dialogRequestId": "9b651156-45f0-4a3e-af8e-61ecdb74fd54",
        "skillRequestId": "amzn1.echo-api.request.12f65fbc-e98c-4079-9de4-324e24e9ba2a",
        "code": "SKILL_ENDPOINT_ERROR",
        "description": "Skill execution returned an exception for requestId amzn1.echo-api.request.12f65fbc-e98c-4079-9de4-324e24e9ba2a",
        "debuggingInfo": {
            "type": "SkillExecutionInfo",
            "content": {
                "invocationRequest": {
                    "endpoint": "https://altbrains.ngrok.io/",
                    "body": {
                        "version": "1.0",
                        "session": {
                            "new": true,
                            "sessionId": "amzn1.echo-api.session.e97bbd64-96f2-4367-9f47-932d6cfeab9d",
                            "application": {
                                "applicationId": "amzn1.ask.skill.5cbfc4d6-35dd-436f-9dbe-bab5dda42409"
                            },
                            "user": {
                                "userId": "amzn1.ask.account.AF5C23VUYVYCZB6U77NZDK7XBIZ3WC3KCC6AZSLTUSIL2HOK2HPOMDCFXTVS3BUD7KONNHXKLRMEKTV6F2HSTF5YTCMYAP6UENP6PSBRULQVDDUCMCJGCB2PWGUORTN2VVIFWDYINZJNRW4RDGWRF2BQ4RWPRDQHDG4YYRJFHLORCH3EAGUFSGQIE7LNEPMAWAOBGMMLF5L7ESA"
                            }
                        },
                        "context": {
                            "System": {
                                "application": {
                                    "applicationId": "amzn1.ask.skill.5cbfc4d6-35dd-436f-9dbe-bab5dda42409"
                                },
                                "user": {
                                    "userId": "amzn1.ask.account.AF5C23VUYVYCZB6U77NZDK7XBIZ3WC3KCC6AZSLTUSIL2HOK2HPOMDCFXTVS3BUD7KONNHXKLRMEKTV6F2HSTF5YTCMYAP6UENP6PSBRULQVDDUCMCJGCB2PWGUORTN2VVIFWDYINZJNRW4RDGWRF2BQ4RWPRDQHDG4YYRJFHLORCH3EAGUFSGQIE7LNEPMAWAOBGMMLF5L7ESA"
                                },
                                "device": {
                                    "deviceId": "amzn1.ask.device.AHDOSOCQTNKPLXE2HTLPAUDSUDNWHXI2IIBO2P44LQFBHEMWGWCKUA52S3PEMULSNGTKEU3DDDUILPC44TQBTYBFXWBTESUSDAWFQD422LJTZU7JWNZXGMWTNDSEQGEZT5TF44WIW3A24PYG4XAIJT5TIQUSYWZW2NW7BS7S2LORAXSB5ZJK2",
                                    "supportedInterfaces": {}
                                },
                                "apiEndpoint": "https://api.amazonalexa.com",
                                "apiAccessToken": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6IjEifQ.eyJhdWQiOiJodHRwczovL2FwaS5hbWF6b25hbGV4YS5jb20iLCJpc3MiOiJBbGV4YVNraWxsS2l0Iiwic3ViIjoiYW16bjEuYXNrLnNraWxsLjVjYmZjNGQ2LTM1ZGQtNDM2Zi05ZGJlLWJhYjVkZGE0MjQwOSIsImV4cCI6MTU1Njg5NzIwMywiaWF0IjoxNTU2ODk2OTAzLCJuYmYiOjE1NTY4OTY5MDMsInByaXZhdGVDbGFpbXMiOnsiY29uc2VudFRva2VuIjpudWxsLCJkZXZpY2VJZCI6ImFtem4xLmFzay5kZXZpY2UuQUhET1NPQ1FUTktQTFhFMkhUTFBBVURTVUROV0hYSTJJSUJPMlA0NExRRkJIRU1XR1dDS1VBNTJTM1BFTVVMU05HVEtFVTNERERVSUxQQzQ0VFFCVFlCRlhXQlRFU1VTREFXRlFENDIyTEpUWlU3SldOWlhHTVdUTkRTRVFHRVpUNVRGNDRXSVczQTI0UFlHNFhBSUpUNVRJUVVTWVdaVzJOVzdCUzdTMkxPUkFYU0I1WkpLMiIsInVzZXJJZCI6ImFtem4xLmFzay5hY2NvdW50LkFGNUMyM1ZVWVZZQ1pCNlU3N05aREs3WEJJWjNXQzNLQ0M2QVpTTFRVU0lMMkhPSzJIUE9NRENGWFRWUzNCVUQ3S09OTkhYS0xSTUVLVFY2RjJIU1RGNVlUQ01ZQVA2VUVOUDZQU0JSVUxRVkREVUNNQ0pHQ0IyUFdHVU9SVE4yVlZJRldEWUlOWkpOUlc0UkRHV1JGMkJRNFJXUFJEUUhERzRZWVJKRkhMT1JDSDNFQUdVRlNHUUlFN0xORVBNQVdBT0JHTU1MRjVMN0VTQSJ9fQ.JojSxUfKQi3wcCbanO80T91ByBfjrzQIzooo8rjiUOFsEiDjUYfSgwZQJe9GywHE3ZBKuku-zGAwJm08Dok8lD10jZ5RU-QoVRSVsB_e9mU9wi4e-LJjtM6gZeDvBI44WH_VwS55YfTypXRoukyY092TycYifMRsl05La6et6YxvOaOu56_AtYRmWK-AOT1kupfdA4kZjXnSp-Mofyy2aCyFDS643jHRPbWTB8bjAJKlSd5Rj7QLTRayWHNtxC19rmUGDXbyOcLjUw2FQ60S_zVxBSMfRvKmRAViRvYlQRpdsdB5_3J2Jtxx2b0DCKMBg7UFkLD73An-Ooyr2YTWxQ"
                            },
                            "Viewport": {
                                "experiences": [
                                    {
                                        "arcMinuteWidth": 246,
                                        "arcMinuteHeight": 144,
                                        "canRotate": false,
                                        "canResize": false
                                    }
                                ],
                                "shape": "RECTANGLE",
                                "pixelWidth": 1024,
                                "pixelHeight": 600,
                                "dpi": 160,
                                "currentPixelWidth": 1024,
                                "currentPixelHeight": 600,
                                "touch": [
                                    "SINGLE"
                                ]
                            }
                        },
                        "request": {
                            "type": "LaunchRequest",
                            "requestId": "amzn1.echo-api.request.12f65fbc-e98c-4079-9de4-324e24e9ba2a",
                            "timestamp": "2019-05-03T15:21:43Z",
                            "locale": "en-US",
                            "shouldLinkResultBeReturned": false
                        }
                    }
                },
                "invocationResponse": **null,**
                "metrics": {
                    "skillExecutionTimeInMilliseconds": 128
                }
            }
        }
    }
}

Flask console on local machine:

[2019-05-03 11:21:29,137] ERROR in skill_adapter: Request verification failed
Traceback (most recent call last):
  File "/Users/fzimmerman/anaconda3/lib/python3.6/site-packages/flask_ask_sdk/skill_adapter.py", line 240, in dispatch_request
    http_request_body=content)
  File "/Users/fzimmerman/anaconda3/lib/python3.6/site-packages/ask_sdk_webservice_support/webservice_handler.py", line 148, in verify_request_and_dispatch
    deserialized_request_env=request_envelope)
  File "/Users/fzimmerman/anaconda3/lib/python3.6/site-packages/ask_sdk_webservice_support/verifier.py", line 437, in verify
    raise VerificationException("Timestamp verification failed")
ask_sdk_webservice_support.verifier.VerificationException: **Timestamp verification failed**
127.0.0.1 - - **[03/May/2019 11:21:29] "**POST / HTTP/1.1" 400 -

There is a 12 second gap in the reported times between ADC and my local machine, but that much time did not elapse in real life.

Context

Preventing my dev environment from being stable.

Your Environment

  • ASK SDK for Python used: 1.9.0
  • Operating System and version: OSX

Python version info

  • Python version used for development: 3.6.7

Issue with Calling Progressive Response API

I'm submitting a...


[ ] Regression (a behavior that used to work and stopped working in a new release)
[ x] Bug report  
[ ] Performance issue
[ ] Feature request
[ ] Documentation issue or request
[ ] Other... Please describe:

Expected Behavior

After invoking an intent that uses a progressive response it should return the message ("Okay, please wait") and then finish the rest of the intent.

Current Behavior

Getting these errors and no progressive response:

“Couldn't parse response body: com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'header': was expecting ('true', 'false' or 'null')”

and

"Directive not valid" even when the directive is valid according to the alexa developer docs for progressive responses. (https://developer.amazon.com/docs/custom-skills/send-the-user-a-progressive-response.html#send-directive)

Steps to Reproduce (for bugs)

Code snippet for progressive response:

from ask_sdk_model.services.directive import (
SendDirectiveRequest, Header, SpeakDirective)

def call_directive_service(handler_input):
request_id_holder = handler_input.request_envelope.request.request_id

directive_header = Header(request_id=request_id_holder)
speech = SpeakDirective(speech="Ok, please wait")

directive_request = SendDirectiveRequest(header=directive_header, directive=speech)
return handler_input.service_client_factory.get_directive_service().enqueue(directive_request)

How to call it in an intent handler:

try:
call_directive_service(handler_input)
except Exception as e:
print(e)

Python version info

  • Python version used for development: python 3.6

Missing source code for ask_sdk_model package

I'm submitting a...


[ ] Regression (a behavior that used to work and stopped working in a new release)
[ ] Bug report  
[ ] Performance issue
[ ] Feature request
[ ] Documentation issue or request
[x] Other... Please describe:

The source code for the ask_sdk_model package is not included.

PIP package includes a dependency on ask-sdk-model package which exists in pip but the source code is not available in this repo, which prevents consuming the sdk from source.

Following the sdk installation steps using pip/pipenv installs all packages correctly.

Skills that require voice code.

I'm submitting a...


[ ] Regression (a behavior that used to work and stopped working in a new release)
[ ] Bug report  
[ ] Performance issue
[ ] Feature request
[ ] Documentation issue or request
[X] Other... Please describe: Just asking for help.

Based on Section 2.4 here, it is possible to use voice code or 4-digit codes for a skill. I am searching for skills or examples and see no results with this features.
I am developing something that can open a lock and must require password for security.
Is this possible on this SDK? and how do I go about this? Thanks!

Reminders API example?


[ ] Regression (a behavior that used to work and stopped working in a new release)
[ ] Bug report  
[ ] Performance issue
[ ] Feature request
[ ] Documentation issue or request
[X] Other... Please describe:

Hey guys, anyone working with Reminders API integrated with custom skill? Please show examples. Yikes.

Provide certificate validation code

I'm submitting a...


[ ] Regression (a behavior that used to work and stopped working in a new release)
[ ] Bug report  
[ ] Performance issue
[x] Feature request
[ ] Documentation issue or request
[ ] Other... Please describe:

Expected Behavior

The SDK should handle all the steps of URL and certificate validation as described in the documentation. As this is required for certification, the API should have this built in. Various attempts exist such as https://github.com/anjishnu/ask-alexa-pykit/blob/cherrypy_0.3_release/lib/validation_utils.py or
https://www.dizmo.com/amazon-alexa-signature-verification/

Current Behavior

Ideally, this would be hooked into the request processing and handled seamlessly for custom skills that do not use AWS Lambda.

Context

Trying to develop a custom skill was greatly helped by the sample code for invocation. Even better would be to enhance that so it handles validation as well and can result in a skill that passes verification.
#53

Your Environment

  • ASK SDK for Python used: x.x.x
  • Operating System and version:

Python version info

  • Python version used for development:

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.