Python - How to obtain UserID in Alexa Skill using ask_sdk_core.handler_input

Viewed 1112

I'm working on a toy Alexa skill and I'm following the example in the Number Guessing Game (code here). In the example they

from ask_sdk_core.handler_input import HandlerInput

@sb.request_handler(can_handle_func=is_request_type("LaunchRequest"))
def launch_request_handler(handler_input):
    """Handler for Skill Launch.

    Get the persistence attributes, to figure out the game state.
    """
    # type: (HandlerInput) -> Response
    attr = handler_input.attributes_manager.persistent_attributes

this attr object allows me to persist information across the session. In the Alexa Developer console I see this data in the JSON under 'session':'attributes' - I also see 'session':'user':'userId'

How do I access the userId data using the handler_input in this function?

4 Answers

You can actually get it from 2 places:

user_id = handler_input.request_envelope.session.user.user_id

or

user_id = handler_input.request_envelope.context.system.user.user_id

It's not necessary to convert the objects to dictionaries

These answers all work, but I prefer using the following helper function:

from ask_sdk_core.utils import ​get_user_id

user_id = get_user_id(handler_input)

So the data in the handler_input can be extracted when you convert it to a 'dict'

step1 = handler_input.__dict__
step2 = step1['request_envelope'].__dict__
step3 = step2['session'].__dict__
step4 = step3['user'].__dict__
userid = step4['user_id']

It may be possible to do it in fewer steps, but this is what got it working for me.

If you're looking for Alexa Device ID to get.

device_id = handler_input.request_envelope.context.system.device.device_id
Related