简体   繁体   English

如何获取 Alexa 用户 ID?

[英]How to get an Alexa userId?

I'm building an Alexa Skill, and it requires that I store the userId of a user.我正在构建 Alexa Skill,它要求我存储用户的 userId。 I've tried to retrieve it with event.session.user.userId .我试图用event.session.user.userId检索它。 However, when I call console.log(event.session.user.userId) the output is literally amzn1.ask.account.[unique-value-here] .但是,当我调用console.log(event.session.user.userId) ,输出实际上是amzn1.ask.account.[unique-value-here] I've looked at several similar questions, and none of them provide a clear enough answer for me.我看过几个类似的问题,但没有一个为我提供足够清晰的答案。

I'm not sure if this is a bug, a developer-only thing, or if the userId is simply anonymized.我不确定这是否是错误、仅限开发人员的事情,或者 userId 是否只是匿名的。 If so, is there a way to get the actual userId?如果是这样,有没有办法获得实际的用户 ID? I imagine there would be, since Amazon has written an entire guide on it here:我想会有,因为亚马逊在这里写了一个完整的指南:

https://developer.amazon.com/public/solutions/alexa/alexa-skills-kit/docs/linking-an-alexa-user-with-a-user-in-your-system . https://developer.amazon.com/public/solutions/alexa/alexa-skills-kit/docs/linking-an-alexa-user-with-a-user-in-your-system

However, after a long day of debugging, I'm not sure what's real and what's not anymore.然而,经过一整天的调试,我不确定什么是真实的,什么不再是真实的。

var request = require('request');
var firebase = require('firebase');
var config = {
    apiKey: "my-api-key",
    authDomain: "stuff...",
    databaseURL: "more stuff...",
    storageBucket: "even more stuff...",
};
firebase.initializeApp(config);
// Get a reference to the database
var database = firebase.database();

exports.handler = (event, context) => {
    try {
        // New session
        if (event.session.new) {
            // New Session
            console.log("NEW SESSION");
        }

        // Launch Request
        switch (event.request.type) {
            case "LaunchRequest":
                var url = "https://api.random.org/json-rpc/1/invoke";
                var myRequest = {
                    "jsonrpc": "2.0",
                    "method": "generateStrings",
                    "params": {
                        "apiKey": "another-api-key",
                        "n": "1",
                        "length": "3",
                        "characters": "abcdefghijklmnopqrstuvwxyz0123456789"
                    },
                    "id": 24
                }
                var pin;
                request.post(
                    url,
                    {json: myRequest},
                    function (error, response, body) {
                        if (!error && response.statusCode == 200) {
                            console.log(event.session.user.userId); // **Here**, output is literally amzn1.ask.account.[unique-value-here] 
                            pin = body.result.random.data[0];
                            writeUserPin(pin);
                            var welcome = "Welcome";
                            var pinStatement = "Your 3 letter or number pin is: " + processPinForSpeech(pin);
                            context.succeed(
                                generateResponse(
                                    buildSpeechletReponse(welcome + pinStatement, true),
                                    {}
                                )
                            );
                            console.log(pin);
                        }
                        else {
                            console.log(error);
                        }
                    }
                );
                console.log("LAUNCH REQUEST");
                break;
            // Intent Request
            case "IntentRequest":
                console.log("INTENT REQUEST");
                break;

            // Session Ended Request
            case "SessionEndedRequest":
                console.log("SESSION ENDED REQUEST");
                break;

            default:
                context.fail(`INVALID REQUEST TYPE: ${event.request.type}`);
        }
    }
    catch (error) {
        context.fail(`Exception: ${error}`);
    }

}
    // Helpers
buildSpeechletReponse = (outputText, shouldEndSession) => {
    return {
        outputSpeech : {
            type: "PlainText",
            text: outputText
        },
        shouldEndSession: shouldEndSession
    };
}

generateResponse = (speechletResponse, sessionAttributes) => {
    return {
        version: "1.0",
        sessionAttributes: sessionAttributes,
        response: speechletResponse
    };
}

function writeUserPin(pin) {
    console.log("writing stuff");
    firebase.database().ref('newPins/' + pin).set({
        num : ""
    });
}

function processPinForSpeech(pin) {
    var wordNumArr = ["zero", "one", "two", "three", "four",
     "five", "six", "seven", "eight", "nine"];
    processedPin = "";
    for (i = 0; i < pin.length; i++){
        var currentChar = pin.charAt(i);
        if (isNaN(Number(currentChar))){
            processedPin += currentChar + ". ";
        }
        else {
            processedPin += wordNumArr[Number(currentChar)] + ". ";
        }
    }
    return processedPin
}

The following is the output on the CloudWatch logs:以下是 CloudWatch 日志上的输出:


16:16:19
START RequestId: 48e335c5-d819-11e6-bc01-a939911adc24 Version: $LATEST

16:16:19
2017-01-11T16:16:19.639Z    48e335c5-d819-11e6-bc01-a939911adc24    NEW SESSION

16:16:19
2017-01-11T16:16:19.758Z    48e335c5-d819-11e6-bc01-a939911adc24    LAUNCH REQUEST

16:16:20
2017-01-11T16:16:20.457Z    48e335c5-d819-11e6-bc01-a939911adc24    amzn1.ask.account.[unique-value-here]

16:16:20
2017-01-11T16:16:20.457Z    48e335c5-d819-11e6-bc01-a939911adc24    writing stuff

16:16:20
2017-01-11T16:16:20.520Z    48e335c5-d819-11e6-bc01-a939911adc24    dd2

16:16:20
END RequestId: 48e335c5-d819-11e6-bc01-a939911adc24

16:16:20
REPORT RequestId: 48e335c5-d819-11e6-bc01-a939911adc24  Duration: 1005.48 ms    Billed Duration: 1100 ms Memory Size: 128 MB    Max Memory Used: 38 MB

You are doing it right.你做得对。 This amzn1.ask.account.[unique-value-here] is in-fact the full userId .这个amzn1.ask.account.[unique-value-here]实际上是完整的userId You can observe this for yourself by enabling your skill from an Echo, logging several requests to your alexa skill, and observing that the userId between these requests is the same value.您可以通过从 Echo 启用您的技能、将多个请求记录到您的 alexa 技能并观察这些请求之间的userId是相同值来亲自观察这一点。

Per the JSON Reference :根据JSON 参考

userId: A string that represents a unique identifier for the user who made the request. userId:一个字符串,表示发出请求的用户的唯一标识符。 The length of this identifier can vary, but is never more than 255 characters.此标识符的长度可以变化,但永远不会超过 255 个字符。 The userId is automatically generated when a user enables the skill in the Alexa app.当用户在 Alexa 应用程序中启用技能时,会自动生成 userId。

Note: Disabling and re-enabling a skill generates a new identifier.注意:禁用和重新启用技能会生成一个新标识符。

If you only need to persist user attributes between sessions, this value will be sufficient and you can use it to uniquely identify this user so long as they have the skill enabled.如果您只需要在会话之间保留用户属性,这个值就足够了,只要他们启用了该技能,您就可以使用它来唯一标识该用户。

If you need to link an account, the value you're looking for is accessToken and lives in that same user object following successful account link.如果您需要链接一个帐户,您正在寻找的值是accessToken并且在成功的帐户链接之后位于同一个user对象中。 Per the same JSON Reference as above:根据与上述相同的 JSON 参考:

accessToken: a token identifying the user in another system. accessToken:在另一个系统中标识用户的令牌。 This is only provided if the user has successfully linked their account.仅当用户成功关联其帐户时才提供此信息。 See Linking an Alexa User with a User in Your System for more details.有关更多详细信息,请参阅将 Alexa 用户与系统中的用户相关联

Well, turns out I was doing everything correctly (for once).好吧,事实证明我做的一切都是正确的(一次)。 The reason why the userId was literally amzn1.ask.account.[unique-value-here] was because I was testing it on a "Alexa Start Session" test event in the AWS Lambda console. userId字面上是amzn1.ask.account.[unique-value-here]原因是因为我在 AWS Lambda 控制台中的“Alexa Start Session”测试事件上测试它。 When I asked my Echo Dot to launch the skill, it generated the actual key.当我让 Echo Dot 启动该技能时,它生成了实际的密钥。 Problem solved.问题解决了。

You should try to read the request that is displayed in the Test console of ASK.您应该尝试读取 ASK 的测试控制台中显示的请求。 From there, you can access the different variables that are being sent to your lambda function.从那里,您可以访问发送到 lambda 函数的不同变量。 Also, you can manipulate or use them as per your requirement.此外,您可以根据需要操纵或使用它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM