簡體   English   中英

亞馬遜Alexa技能Lambda代碼將無法執行

[英]Amazon Alexa Skill Lambda code won't execute

我正在嘗試為NodeJS中的亞馬遜Alexa技能編寫Lambda函數。 Alexa是圓柱形揚聲器,可響應您的聲音,“技能”基本上是一個語音應用程序。 此函數從Alexa設備獲取JSON輸入並創建響應,然后將新JSON發送回設備以進行輸出。

此代碼應該從BTC-e JSON中將比特幣從美元匯率中拉出,提取'avg'值,並將其輸出到Alexa設備。

我很長時間沒有做任何編碼,所以請原諒任何愚蠢的錯誤。 我拿了示例代碼並嘗試根據我的目的修改它,但是在AWS中執行時出現此錯誤:

{
  "errorMessage": "Unexpected identifier",
  "errorType": "SyntaxError",
  "stackTrace": [
    "Module._compile (module.js:439:25)",
    "Object.Module._extensions..js (module.js:474:10)",
    "Module.load (module.js:356:32)",
    "Function.Module._load (module.js:312:12)",
    "Module.require (module.js:364:17)",
    "require (module.js:380:17)"
  ]
}

我的代碼在這里 我覺得這個問題出現在第84-106行,因為那是我完成大部分工作的地方。

謝謝你的幫助!

下面的代碼應該可以工作,只需取消評論我添加的待辦事項。 您有幾個缺少的大括號,我切換到AWS lambda默認包含的不同的http請求庫。 我也改變了流量,使我更容易測試,所以現在它沒有重新提示它只是告訴你最新的硬幣價格。

var https = require('https');

// Route the incoming request based on type (LaunchRequest, IntentRequest,
// etc.) The JSON body of the request is provided in the event parameter.
exports.handler = function (event, context) {
    try {
        console.log("event.session.application.applicationId=" + event.session.application.applicationId);

        /**
         * Uncomment this if statement and populate with your skill's application ID to
         * prevent someone else from configuring a skill that sends requests to this function.
         */

         // TODO add this back in for your app
        // if (event.session.application.applicationId !== "amzn1.echo-sdk-ams.app.") {
        //     context.fail("Invalid Application ID");
        // }

        if (event.session.new) {
            onSessionStarted({requestId: event.request.requestId}, event.session);
        }

        if (event.request.type === "LaunchRequest") {
            onLaunch(event.request,
                     event.session,
                     function callback(sessionAttributes, speechletResponse) {
                        context.succeed(buildResponse(sessionAttributes, speechletResponse));
                     });
        }  else if (event.request.type === "IntentRequest") {
            onIntent(event.request,
                     event.session,
                     function callback(sessionAttributes, speechletResponse) {
                         context.succeed(buildResponse(sessionAttributes, speechletResponse));
                     });
        } else if (event.request.type === "SessionEndedRequest") {
            onSessionEnded(event.request, event.session);
            context.succeed();
        }
    } catch (e) {
        context.fail("Exception: " + e);
    }
};

/**
 * Called when the session starts.
 */
function onSessionStarted(sessionStartedRequest, session) {
    console.log("onSessionStarted requestId=" + sessionStartedRequest.requestId
                + ", sessionId=" + session.sessionId);
}

/**
 * Called when the user launches the skill without specifying what they want.
 */
function onLaunch(launchRequest, session, callback) {
    console.log("onLaunch requestId=" + launchRequest.requestId
                + ", sessionId=" + session.sessionId);

    // Dispatch to your skill's launch.
    getWelcomeResponse(callback);
}

/**
 * Called when the user specifies an intent for this skill.
 */
function onIntent(intentRequest, session, callback) {
    console.log("onIntent requestId=" + intentRequest.requestId
                + ", sessionId=" + session.sessionId);
    getWelcomeResponse(callback);
}

/**
 * Called when the user ends the session.
 * Is not called when the skill returns shouldEndSession=true.
 */
function onSessionEnded(sessionEndedRequest, session) {
    console.log("onSessionEnded requestId=" + sessionEndedRequest.requestId
                + ", sessionId=" + session.sessionId);
    // Add cleanup logic here
}

// --------------- Functions that control the skill's behavior -----------------------

function getWelcomeResponse(callback) {
        // If we wanted to initialize the session to have some attributes we could add those here.
    var sessionAttributes = {};
    var cardTitle = "Bitcoin Price";
    var speechOutput = "Welcome to the Bitcoin Price skill, "

    var repromptText = ''
    var shouldEndSession = true;

    var options = {
        host: 'btc-e.com',
        port: 443,
        path: '/api/2/btc_usd/ticker',
        method: 'GET'
    };

    var req = https.request(options, function(res) {
        var body = '';
        console.log('Status:', res.statusCode);
        console.log('Headers:', JSON.stringify(res.headers));
        res.setEncoding('utf8');
        res.on('data', function(chunk) {
            body += chunk;
        });
        res.on('end', function() {
            console.log('Successfully processed HTTPS response');

            body = JSON.parse(body);

                console.log(body);
                console.log('last price = ' + body.ticker.last);

                speechOutput += "The last price for bitcoin was : " + body.ticker.last;

                callback(sessionAttributes,
                 buildSpeechletResponse(cardTitle, speechOutput, repromptText, shouldEndSession));

             });
    });
    req.end();

}

// --------------- Helpers that build all of the responses -----------------------

function buildSpeechletResponse(title, output, repromptText, shouldEndSession) {
    return {
        outputSpeech: {
            type: "PlainText",
            text: output
        },
        card: {
            type: "Simple",
            title: "SessionSpeechlet - " + title,
            content: "SessionSpeechlet - " + output
        },
        reprompt: {
            outputSpeech: {
                type: "PlainText",
                text: repromptText
            }
        },
        shouldEndSession: shouldEndSession
    }
}

function buildResponse(sessionAttributes, speechletResponse) {
    return {
        version: "1.0",
        sessionAttributes: sessionAttributes,
        response: speechletResponse
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM