Erste Schritte mit wit.ai und Node.js

stimmen
0

Ich versuche wit.ai zu verwenden quickstart Beispiel . Das Beispiel arbeitet mit den fest codierten Werte , aber wenn ich den Dritten Wetter API verwenden und versuchen , die Antwort an den Benutzer zu geben , es funktioniert nicht.

Arbeitscode:

 const actions = {
         send(request, response) {
           const {sessionId, context, entities} = request;
           const {text, quickreplies} = response;
           console.log('sending...', JSON.stringify(response));
         },
         getForecast({context, entities}) {
           var location = firstEntityValue(entities, 'location');
           if (location) {
             context.forecast = 'sunny in ' + location; // we should call a weather API here
             delete context.missingLocation;

           } else {
             context.missingLocation = true;
             delete context.forecast;
           }
           return context;
         },
       };

Jetzt habe ich Funktion GetWeather ({Kontext, Organisationen}, Ort), den Dritten Wetter API aufrufen und die Wetterinformationen für den Benutzer bestimmten Ort zu erhalten.

Nonworking Code:

var getWeather = function ({ context, entities }, location) {
  console.log('Entities: ',entities)
  var url = 'http://api.openweathermap.org/data/2.5/weather?q=' + location + '&appid=myAppID';
  request.get(url, function (error, response, body) {
    if (!error && response.statusCode == 200) {
      console.log(typeof body) 
      var weatherObj = JSON.parse(body);
      console.log('weather api res: ', weatherObj.weather[0].description);
      context.forecast = weatherObj.weather[0].description + ' ' + location; // we should call a weather API here
      delete context.missingLocation;
    }
  })
}

const actions = {
  send(request, response) {
    const {sessionId, context, entities} = request;
    const {text, quickreplies} = response;
    console.log('sending...', JSON.stringify(response));
  },
  getForecast({context, entities}) {
    var location = firstEntityValue(entities, 'location');
    if (location) {
      //Call a function which calls the third party weather API and then handles the response message.
      getWeather({ context, entities }, location);
    } else {
      context.missingLocation = true;
      delete context.forecast;
    }
    return context;
  },
};

Auch wenn ich GetWeather () Funktion leicht verändern und bewegen context.forecast = ‚sonnig in‘ + Lage; löschen context.missingLocation; außerhalb der Callback - Funktionen erzeugt von Request.get () nennt es wieder funktionieren wird, aber ich an dieser Stelle nicht Wetterinfos von 3rd - Party - api habe:

Arbeitscode:

var getWeather = function ({ context, entities }, location) {
  //Keeping context.forecast outside the request.get() callback function is useless as we yet to get the weather info from the API
  context.forecast = 'sunny in ' + location;
  delete context.missingLocation;
  console.log('Entities: ',entities)
  var url = 'http://api.openweathermap.org/data/2.5/weather?q=' + location + '&appid=myAppID';
  request.get(url, function (error, response, body) {
    if (!error && response.statusCode == 200) {
      console.log(typeof body) 
      var weatherObj = JSON.parse(body);
      console.log('weather api res: ', weatherObj.weather[0].description);
    }
  })
}

Also , wie zu machen context.forecast = apiRes + Lage; Linie der Arbeit innerhalb des Rückrufs von http Anruf? Was ich hier falsch mache?

HINWEIS: Fehlerreaktion ich von wit.ai erhalten:

Fehler: Oops, ich weiß nicht, was zu tun ist.

at F:\..\node-wit\lib\wit.js:87:15
at process._tickCallback (internal/process/next_tick.js:103:7)

Ich verwende npm Paket Anforderung zu http Anrufe innerhalb Knoten zu machen.

Veröffentlicht am 16/01/2017 um 10:30
quelle vom benutzer
In anderen Sprachen...                            


1 antworten

stimmen
1

Gelöst das Problem durch das Versprechen, richtig zu lösen. Dies ist der komplette Code:

'use strict';

let Wit = null;
let interactive = null;

var getWeather = function ( location) {
  var url = 'http://api.openweathermap.org/data/2.5/weather?q=' + location + '&appid=myAppID';
  return fetch(url, {
    method: 'GET',
    headers: {
      'Content-Type': 'application/json',
      'Accept': 'application/json',
    }
  })
    .then(rsp => {
      var res = rsp.json();
      return res;
    })
    .then(json => {
      if (json.error && json.error.message) {
        throw new Error(json.error.message);
      }
      return json;
    });
}

try {
  // if running from repo
  Wit = require('../').Wit;
  interactive = require('../').interactive;
} catch (e) {
  Wit = require('node-wit').Wit;
  interactive = require('node-wit').interactive;
}

const accessToken = (() => {
  if (process.argv.length !== 3) {
    console.log('usage: node examples/quickstart.js <wit-access-token>');
    process.exit(1);
  }
  return process.argv[2];
})();

// Quickstart example
// See https://wit.ai/ar7hur/quickstart

const firstEntityValue = (entities, entity) => {
  const val = entities && entities[entity] &&
    Array.isArray(entities[entity]) &&
    entities[entity].length > 0 &&
    entities[entity][0].value;
  if (!val) {
    return null;
  }
  return typeof val === 'object' ? val.value : val;
};

const actions = {
  send(request, response) {
    const {sessionId, context, entities} = request;
    const {text, quickreplies} = response;
    return new Promise(function (resolve, reject) {
      console.log('sending...', JSON.stringify(response));
      return resolve();
    });
  },
  getForecast({context, entities}) {
    var location = firstEntityValue(entities, 'location');
    if (location) {
      return new Promise(function (resolve, reject) {
        return getWeather(location).then(weatherJson => {
          context.forecast = weatherJson.weather[0].description + ' in the ' + location;
          delete context.missingLocation;
          return resolve(context);
        })
      });
    } else {
      context.missingLocation = true;
      delete context.forecast;
      return Promise.reject(context);
    }
    return context;
  },
};

const client = new Wit({ accessToken, actions });
interactive(client);
Beantwortet am 17/01/2017 um 06:32
quelle vom benutzer

Cookies help us deliver our services. By using our services, you agree to our use of cookies. Learn more