簡體   English   中英

Alexa-通過Lambda訪問外部API

[英]Alexa - Accessing External API via Lambda

我正在掌握Alexa技能,需要它來查詢API,但是它似乎根本不起作用,我嘗試了100萬種不同的方法。 如果有人可以看一下下面的代碼並添加基本的API查詢,那就太好了,謝謝!

const playersOnlineHandler = {
    canHandle(handlerInput) {
        const request = handlerInput.requestEnvelope.request;
        return (request.type === 'IntentRequest'
        && request.intent.name === 'playersOnlineIntent');
    },
    handle(handlerInput) {
        const data =https.get("URL");
        const x = "Hello";
        const speechOutput = "There is currently" + data + "players online";
        return handlerInput.responseBuilder
        .speak(speechOutput)
        .getResponse();
    },
};

您可以嘗試將此代碼用於HTTP GET API調用

const playersOnlineHandler = {
    canHandle(handlerInput) {
        const request = handlerInput.requestEnvelope.request;
        return (request.type === 'IntentRequest'
        && request.intent.name === 'playersOnlineIntent');
    },
    handle(handlerInput) {
        let data;
        const request = require("request");

        let options = { method: 'GET',
            url: 'http://exaple.com/api.php',
            qs: 
            { action: 'query' } };

        request(options, function (error, response, body) {
            if (error) throw new Error(error);
            let json = body;
            let obj = JSON.parse(json);
            data = obj.element.value;

        });
        const x = "Hello";
        const speechOutput = "There is currently" + data + "players online";
        return handlerInput.responseBuilder
        .speak(speechOutput)
        .getResponse();
    },
};

您可以參考以下代碼段。 https內置模塊配合使用

handle(handlerInput) {

  https.get('https://jsonplaceholder.typicode.com/todos/1', res => {
    res.setEncoding("utf8");
    let body = "";

    res.on("data", data => {
        body += data;
    });
    //On receiving the entire info from the API
    res.on("end", () => {
        body = JSON.parse(body);

        speechOutput += 'Sample Info' + body.userId;

        return handlerInput.responseBuilder
              .speak(speechOutput)
              .getResponse();

    });
  });
},

暫無
暫無

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

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