【问题标题】:Python - How to obtain UserID in Alexa Skill using ask_sdk_core.handler_inputPython - 如何使用 ask_sdk_core.handler_input 在 Alexa Skill 中获取用户 ID
【发布时间】:2021-05-09 19:21:40
【问题描述】:

我正在研究一个玩具 Alexa 技能,我正在按照数字猜谜游戏 (code here) 中的示例进行操作。在示例中他们

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

这个attr 对象允许我在整个会话中保留信息。在 Alexa 开发人员控制台中,我在 JSON 中的 'session':'attributes' 下看到了这些数据 - 我还看到了 'session':'user':'userId'

如何使用此函数中的 handler_input 访问 userId 数据?

【问题讨论】:

    标签: python alexa-skills-kit


    【解决方案1】:

    您实际上可以从 2 个地方获得它:

    user_id = handler_input.request_envelope.session.user.user_id
    

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

    不需要将对象转换为字典

    【讨论】:

      【解决方案2】:

      这些答案都有效,但我更喜欢使用以下辅助函数:

      from ask_sdk_core.utils import ​get_user_id
      
      user_id = get_user_id(handler_input)
      

      【讨论】:

        【解决方案3】:

        所以当你将handler_input中的数据转换为'dict'时可以提取它

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

        也许可以用更少的步骤来完成,但这就是它对我有用的原因。

        【讨论】:

          【解决方案4】:

          如果您正在寻找 Alexa 设备 ID 来获取。

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

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2017-05-12
            • 2017-05-25
            • 1970-01-01
            • 2018-05-10
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2017-10-06
            相关资源
            最近更新 更多