Запрос API в выполнении Dialogflow (встроенный редактор) - PullRequest
0 голосов
/ 16 июня 2019

Я пытаюсь сделать запрос к внешнему API через Dialogflow Fulfillment.

Я тестировал свой код на https://repl.it/, и он работал, но в самом Dialogflow я получаю следующую ошибку:

невозможно получить токен TypeError: запрос не является функцией

Сам код сначала генерирует токен для API (gettoken () - и затем обращается к API через getUnit ().

// See https://github.com/dialogflow/dialogflow-fulfillment-nodejs
// for Dialogflow fulfillment library docs, samples, and to report issues
'use strict';

const functions = require('firebase-functions');
const {WebhookClient} = require('dialogflow-fulfillment');
const {Card, Suggestion} = require('dialogflow-fulfillment');
var request = require('request');

process.env.DEBUG = 'dialogflow:debug'; // enables lib debugging statements

exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
  const agent = new WebhookClient({ request, response });
  console.log('Dialogflow Request headers: ' + JSON.stringify(request.headers));
  console.log('Dialogflow Request body: ' + JSON.stringify(request.body));


  function equipmentoverview_handler(agent) {
   getUnit("0");
   //agent.add("test");

  }

  // Run the proper function handler based on the matched Dialogflow intent name
  let intentMap = new Map();
  //intentMap.set('Default Welcome Intent', welcome);
  //intentMap.set('Default Fallback Intent', fallback);
  //intentMap.set('StageTest', stagehandler);
  intentMap.set('EquipmentOverview', equipmentoverview_handler);
  // intentMap.set('your intent name here', yourFunctionHandler);
  agent.handleRequest(intentMap);


  //API CONNECTION
  //Funktion um Token zu generieren
function getToken() {
    var headers = {
        'content-type': 'application/x-www-form-urlencoded',
        'Authorization': 'Basic IN-HERE-IS-MY-AUTHORIZATION TOKEN-'
    };

    var dataString = 'grant_type=client_credentials';

    var options = {
        url: 'URL-IN-HERE',
        method: 'POST',
        headers: headers,
        body: dataString
    };  

    return new Promise((resolve, reject) => {
        request(options, (error, response, body) => {
            if (error) return reject(error);
            if (response.statusCode == 200) {
                var str = body;    
                var token = str.split('\"')[3]; 
                resolve(token);
            }
        });
    });
}

//Funktion zum Aufrufen der getUnit Funktion der API und Übergabe des Token
function getUnit(param) {
  getToken()
    .then((token) => {
         // here you can access the token
          var headers = {
              'Accept': 'application/json',
              'Authorization': 'Bearer ' + token
          };

          var options = {
              url: 'URL-IN-HERE',
              headers: headers,
          };  

          function callback(error, response, body) {
              if (!error && response.statusCode == 200) {
                  var json = JSON.parse(body);
                  var desc = json['description'];
                  var en = desc['en'];
                  if(param == "0" || param == "1") {
                    var ans = "tYour appartment is equipped with the following items:\n" + en.split('\n\n')[0] + "\n\nUnluckily, we cannot provide the following stuff:\n" + en.split('\n\n')[1];
                    console.log(ans);
                    agent.add(ans);
                  }
                  else if (param =="2") {
                    var part = en.split('\n\n')[param]; 
                    console.log(part);
                  }
                  else {
                    var part = en.split('\n\n')[0]; 
                    var ans = "";
                    if(part.includes(param)) {
                      ans = "Yes, a " + param + " is available in your room.";
                    }
                    else {
                      ans = "Unfortunately, your room is not equipped with a " + param;
                    }
                    console.log(ans);
                  }
              }
          }
          request(options, callback);
    })
    .catch((error) => {
        console.error('unable to retrieve token', error);
    });
}
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...