Node.Js不执行匿名功能? -aws lambda -alexa技能

时间:2018-07-10 15:05:10

标签: javascript node.js aws-lambda httprequest alexa

我目前正在为我的智能家居开发Alexa技能。 我创建了一个Lambda函数,并希望向服务器发出http请求。但它不会执行我的任何一个。功能。

lambda代码示例:

/* This code has been generated from your interaction model by skillinator.io

/* eslint-disable  func-names */
/* eslint quote-props: ["error", "consistent"]*/

// There are three sections, Text Strings, Skill Code, and Helper Function(s).
// You can copy and paste the contents as the code for a new Lambda function, using the alexa-skill-kit-sdk-factskill template.
// This code includes helper functions for compatibility with versions of the SDK prior to 1.0.9, which includes the dialog directives.



 // 1. Text strings =====================================================================================================
 //    Modify these strings and messages to change the behavior of your Lambda function

const request = require("request");
let speechOutput;
let reprompt;
let welcomeOutput = "Hallo xyz!";
let welcomeReprompt = "xy";
// 2. Skill Code =======================================================================================================
"use strict";
const Alexa = require('alexa-sdk');
const APP_ID = "my id";  // TODO replace with your app ID (OPTIONAL).
speechOutput = '';
const handlers = {
    'LaunchRequest': function () {
        this.emit(':ask', welcomeOutput, welcomeReprompt);
    },
    'AMAZON.HelpIntent': function () {
        speechOutput = 'Placeholder response for AMAZON.HelpIntent.';
        reprompt = '';
        this.emit(':ask', speechOutput, reprompt);
    },
   'AMAZON.CancelIntent': function () {
        speechOutput = 'Placeholder response for AMAZON.CancelIntent';
        this.emit(':tell', speechOutput);
    },
   'AMAZON.StopIntent': function () {
        speechOutput = 'Placeholder response for AMAZON.StopIntent.';
        this.emit(':tell', speechOutput);
   },
   'SessionEndedRequest': function () {
        speechOutput = '';
        //this.emit(':saveState', true);//uncomment to save attributes to db on session end
        this.emit(':tell', speechOutput);
   },
    'LichtIntent': function () {
        //delegate to Alexa to collect all the required slot values
       let filledSlots = delegateSlotCollection.call(this);
        speechOutput = '';
        //any intent slot variables are listed here for convenience

        let zimmerSlotRaw = this.event.request.intent.slots.zimmer.value;
        console.log(zimmerSlotRaw);
        let zimmerSlot = resolveCanonical(this.event.request.intent.slots.zimmer);
        console.log(zimmerSlot);
        let was_lichtSlotRaw = this.event.request.intent.slots.was_licht.value;
        console.log(was_lichtSlotRaw);
        let was_lichtSlot = resolveCanonical(this.event.request.intent.slots.was_licht);
        console.log(was_lichtSlot);












        //THIS IS THE PART WHERE I NEED HELP!!



        MakeRequest(function(data){
            console.log("asddd");
            speechOutput = "This is a place holder response for the intent named LichtIntent, which includes dialogs. This intent has 2 slots, which are zimmer, and was_licht. Anything else?";


            var speechOutput = data;


            this.emit(':ask', speechOutput, speechOutput);

        });

        console.log("asdww");

        //DOWN TO HERE!!








    },
    'StromIntent': function () {
        //delegate to Alexa to collect all the required slot values
       let filledSlots = delegateSlotCollection.call(this);
        speechOutput = '';
        //any intent slot variables are listed here for convenience

        let geraet_stromSlotRaw = this.event.request.intent.slots.geraet_strom.value;
        console.log(geraet_stromSlotRaw);
        let geraet_stromSlot = resolveCanonical(this.event.request.intent.slots.geraet_strom);
        console.log(geraet_stromSlot);
        let wasSlotRaw = this.event.request.intent.slots.was.value;
        console.log(wasSlotRaw);
        let wasSlot = resolveCanonical(this.event.request.intent.slots.was);
        console.log(wasSlot);

        //Your custom intent handling goes here
        speechOutput = "This is a place holder response for the intent named StromIntent, which includes dialogs. This intent has 2 slots, which are geraet_strom, and was. Anything else?";
        this.emit(':ask', speechOutput, speechOutput);
    },
    'FrageIntent': function () {
        //delegate to Alexa to collect all the required slot values
       let filledSlots = delegateSlotCollection.call(this);
        speechOutput = '';
        //any intent slot variables are listed here for convenience

        let geraetSlotRaw = this.event.request.intent.slots.geraet.value;
        console.log(geraetSlotRaw);
        let geraetSlot = resolveCanonical(this.event.request.intent.slots.geraet);
        console.log(geraetSlot);
        let was_frageSlotRaw = this.event.request.intent.slots.was_frage.value;
        console.log(was_frageSlotRaw);
        let was_frageSlot = resolveCanonical(this.event.request.intent.slots.was_frage);
        console.log(was_frageSlot);

        //Your custom intent handling goes here
        speechOutput = "This is a place holder response for the intent named FrageIntent, which includes dialogs. This intent has 2 slots, which are geraet, and was_frage. Anything else?";
        this.emit(':ask', speechOutput, speechOutput);
    },
    'TuerIntent': function () {
        //delegate to Alexa to collect all the required slot values
       let filledSlots = delegateSlotCollection.call(this);
        speechOutput = '';
        //any intent slot variables are listed here for convenience

        let zeitSlotRaw = this.event.request.intent.slots.zeit.value;
        console.log(zeitSlotRaw);
        let zeitSlot = resolveCanonical(this.event.request.intent.slots.zeit);
        console.log(zeitSlot);

        //Your custom intent handling goes here
        speechOutput = "This is a place holder response for the intent named TuerIntent, which includes dialogs. This intent has one slot, which is zeit. Anything else?";
        this.emit(':ask', speechOutput, speechOutput);
    },  
    'Unhandled': function () {
        speechOutput = "The skill didn't quite understand what you wanted.  Do you want to try something else?";
        this.emit(':ask', speechOutput, speechOutput);
    }
};

exports.handler = (event, context) => {
    const alexa = Alexa.handler(event, context);
    alexa.appId = APP_ID;
    // To enable string internationalization (i18n) features, set a resources object.
    //alexa.resources = languageStrings;
    alexa.registerHandlers(handlers);
    //alexa.dynamoDBTableName = 'DYNAMODB_TABLE_NAME'; //uncomment this line to save attributes to DB
    alexa.execute();
};

//    END of Intent Handlers {} ========================================================================================
// 3. Helper Function  =================================================================================================










//THESE ARE MY HELPER FUNCTIONS
    function url(){
        console.log("asd");
        return " my server ip";
    }
    function MakeRequest(callback){
        console.log("hallo!");
        request.get(url(), function(error, response, body){

            console.log("****************************************");
            console.log(response);
            console.log("****************************************");

        console.log(error);     
        console.log("****************************************");

        console.log(body);
        console.log("****************************************");

        callback("erfolg!");
    });
    console.log("hffggh");
}

//DOWN TO HERE!!






















function resolveCanonical(slot){
    //this function looks at the entity resolution part of request and returns the slot value if a synonyms is provided
    let canonical;
    try{
        canonical = slot.resolutions.resolutionsPerAuthority[0].values[0].value.name;
    }catch(err){
        console.log(err.message);
        canonical = slot.value;
    };
    return canonical;
};

function delegateSlotCollection(){
  console.log("in delegateSlotCollection");
  console.log("current dialogState: "+this.event.request.dialogState);
    if (this.event.request.dialogState === "STARTED") {
      console.log("in Beginning");
      let updatedIntent= null;
      // updatedIntent=this.event.request.intent;
      //optionally pre-fill slots: update the intent object with slot values for which
      //you have defaults, then return Dialog.Delegate with this updated intent
      // in the updatedIntent property
      //this.emit(":delegate", updatedIntent); //uncomment this is using ASK SDK 1.0.9 or newer

      //this code is necessary if using ASK SDK versions prior to 1.0.9 
      if(this.isOverridden()) {
            return;
        }
        this.handler.response = buildSpeechletResponse({
            sessionAttributes: this.attributes,
            directives: getDialogDirectives('Dialog.Delegate', updatedIntent, null),
            shouldEndSession: false
        });
        this.emit(':responseReady', updatedIntent);

    } else if (this.event.request.dialogState !== "COMPLETED") {
      console.log("in not completed");
      // return a Dialog.Delegate directive with no updatedIntent property.
      //this.emit(":delegate"); //uncomment this is using ASK SDK 1.0.9 or newer

      //this code necessary is using ASK SDK versions prior to 1.0.9
        if(this.isOverridden()) {
            return;
        }
        this.handler.response = buildSpeechletResponse({
            sessionAttributes: this.attributes,
            directives: getDialogDirectives('Dialog.Delegate', null, null),
            shouldEndSession: false
        });
        this.emit(':responseReady');

    } else {
      console.log("in completed");
      console.log("returning: "+ JSON.stringify(this.event.request.intent));
      // Dialog is now complete and all required slots should be filled,
      // so call your normal intent handler.
      return this.event.request.intent;
    }
}


function randomPhrase(array) {
    // the argument is an array [] of words or phrases
    let i = 0;
    i = Math.floor(Math.random() * array.length);
    return(array[i]);
}
function isSlotValid(request, slotName){
        let slot = request.intent.slots[slotName];
        //console.log("request = "+JSON.stringify(request)); //uncomment if you want to see the request
        let slotValue;

        //if we have a slot, get the text and store it into speechOutput
        if (slot && slot.value) {
            //we have a value in the slot
            slotValue = slot.value.toLowerCase();
            return slotValue;
        } else {
            //we didn't get a value in the slot.
            return false;
        }
}

//These functions are here to allow dialog directives to work with SDK versions prior to 1.0.9
//will be removed once Lambda templates are updated with the latest SDK

function createSpeechObject(optionsParam) {
    if (optionsParam && optionsParam.type === 'SSML') {
        return {
            type: optionsParam.type,
            ssml: optionsParam['speech']
        };
    } else {
        return {
            type: optionsParam.type || 'PlainText',
            text: optionsParam['speech'] || optionsParam
        };
    }
}

function buildSpeechletResponse(options) {
    let alexaResponse = {
        shouldEndSession: options.shouldEndSession
    };

    if (options.output) {
        alexaResponse.outputSpeech = createSpeechObject(options.output);
    }

    if (options.reprompt) {
        alexaResponse.reprompt = {
            outputSpeech: createSpeechObject(options.reprompt)
        };
    }

    if (options.directives) {
        alexaResponse.directives = options.directives;
    }

    if (options.cardTitle && options.cardContent) {
        alexaResponse.card = {
            type: 'Simple',
            title: options.cardTitle,
            content: options.cardContent
        };

        if(options.cardImage && (options.cardImage.smallImageUrl || options.cardImage.largeImageUrl)) {
            alexaResponse.card.type = 'Standard';
            alexaResponse.card['image'] = {};

            delete alexaResponse.card.content;
            alexaResponse.card.text = options.cardContent;

            if(options.cardImage.smallImageUrl) {
                alexaResponse.card.image['smallImageUrl'] = options.cardImage.smallImageUrl;
            }

            if(options.cardImage.largeImageUrl) {
                alexaResponse.card.image['largeImageUrl'] = options.cardImage.largeImageUrl;
            }
        }
    } else if (options.cardType === 'LinkAccount') {
        alexaResponse.card = {
            type: 'LinkAccount'
        };
    } else if (options.cardType === 'AskForPermissionsConsent') {
        alexaResponse.card = {
            type: 'AskForPermissionsConsent',
            permissions: options.permissions
        };
    }

    let returnResult = {
        version: '1.0',
        response: alexaResponse
    };

    if (options.sessionAttributes) {
        returnResult.sessionAttributes = options.sessionAttributes;
    }
    return returnResult;
}

function getDialogDirectives(dialogType, updatedIntent, slotName) {
    let directive = {
        type: dialogType
    };

    if (dialogType === 'Dialog.ElicitSlot') {
        directive.slotToElicit = slotName;
    } else if (dialogType === 'Dialog.ConfirmSlot') {
        directive.slotToConfirm = slotName;
    }

    if (updatedIntent) {
        directive.updatedIntent = updatedIntent;
    }
    return [directive];
}

我对http请求使用“请求”模块,我想大家都知道这个模块。

当我测试我的函数时,它没有运行时错误! 但是MakeRequest调用和request.get调用中的匿名函数将不会执行,我也不知道为什么。 例如,控制台输出:

Hallo!,

Asd(非常有趣。它获取了request.get的参数。错误必须在调用中的第二个参数(anon函数本身?)和anon函数的开始之间),

hffggh,

asdww

-console.logs匿名输入。功能不显示。

我也许不理解为什么MakeRequest功能。不会运行->因为它的回调从未发生。但是为什么request.get不起作用?我在一个普通的节点项目中粘贴了必要的部分(MakeRequest和帮助器函数),并且有效!! -facepalm ....我快哭了..

我的目标:我想从服务器接收响应。-就是这样。但这只是不会进入我可以访问响应对象的功能。

(向下滚动到助手功能)

请帮帮我,我真的可以把头撞在墙上。

护卫队

0 个答案:

没有答案