Alexa - Доступ к внешнему API через Lambda - PullRequest
0 голосов
/ 01 декабря 2018

Я делаю навык Alexa и нуждаюсь в нем для запроса API, однако, похоже, он просто не работает, и я пробовал 1 миллион различных способов.Было бы здорово, если бы кто-нибудь взглянул на приведенный ниже код и добавил базовый запрос 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();
    },
};

Ответы [ 2 ]

0 голосов
/ 01 декабря 2018

Вы можете обратиться к следующему фрагменту.Хорошо работает со 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();

    });
  });
},
0 голосов
/ 01 декабря 2018

Вы можете попробовать этот код для вызовов 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();
    },
};
...