2017-01-16 7 views
0

wit.ai quickstart example을 사용하려고합니다. 이 예제는 하드 코딩 된 값과 함께 작동하지만 제 3 자 날씨 API를 사용하고 사용자에게 응답을 시도하면 작동하지 않습니다.wit.ai 및 Node.js 시작하기

근무 코드 :

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; 
     }, 
     }; 

는 지금은 타사 날씨 API를 호출하고 사용자의 지정된 위치에 대한 날씨 정보를 얻을 기능 getWeather ({컨텍스트 개체}, 위치)를 썼다.

휴무 번호 : 또한

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; 
    }, 
}; 

I가 getWeather() 함수를 약간 변경 = + 위치 '써니'context.forecast 이동하는 경우; context.missingLocation을 삭제하십시오; request.get의 콜백 fuction를 외부() 다시 작동을 부르지 만,이 시점에서 내가 제 3 자 API의 날씨 정보가없는 방법 : 그래서

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); 
    } 
    }) 
} 

:

작동 코드를 확인 context.forecast = apiRes + location; http 호출의 콜백 내부에서 라인 작업이 필요합니까? 내가 여기서 뭘 잘못하고 있니?

참고 : 오류 응답은 내가 wit.ai에서 얻을 : 내가 노드 내부 HTTP 통화를 할 NPM 패키지 request을 사용하고

Error: Oops, I don't know what to do.

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

.

답변

1

약속을 올바르게 해결하여 문제를 해결했습니다. 다음은 전체 코드입니다.

'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);