我正在设置一个推特机器人来发布城市的温度,知道为什么我的设置功能不起作用吗?
我尝试更改为不同的 API,但似乎没有任何效果。
console.log('starting twitter bot...')
var Twit = require('twit');
var config = require('./config');
var T = new Twit(config);
setup();
function setup() {
loadJSON("http://api.apixu.com/v1/current.json?key=###############&q=Colombo", gotData);
}
function gotData(data) {
console.log('Weather Data Retrieved...')
var r = data.current[2];
var tweet = {
status: 'here is ' + r + ' temperature test '
}
T.post('statuses/update', tweet);
}
我收到这个错误:
ReferenceError: loadJSON 未定义
最佳答案
我建议使用请求库来提取天气状况,特别是使用 request-promise-native库,这使得读取 API 数据变得非常容易:
只是做:
npm install request
npm install request-promise-native
然后安装:
const API_KEY = '7165..'; // Put your API key here
const Twit = require('twit');
const config = require('./config');
const rp = require('request-promise-native');
async function testWeatherTweet(location) {
const options = {
url: "http://api.apixu.com/v1/current.json",
qs: {
key: API_KEY,
q: location
},
json: true
};
let result = await rp(options);
let condition = result.current.condition.text;
let tweetText = `Conditions in ${location} are currently ${condition}, temperature is ${result.current.temp_c}°C.`;
console.log("Sending tweet: ", tweetText);
sendTweet(tweetText)
}
function sendTweet(text) {
const T = new Twit(config);
const tweet = {
status: text
}
T.post('statuses/update', tweet);
}
testWeatherTweet('Colombo');
关于javascript - 从 Weather API 中提取数据并在推特上发布,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57266796/