Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 973
Mark Avatar asked Oct 20 '25 22:10

Mark


2 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

like image 197
Nicolò Gasparini Avatar answered Oct 22 '25 11:10

Nicolò Gasparini


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)
like image 41
Kahitar Avatar answered Oct 22 '25 12:10

Kahitar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!