javascript - 从 Weather API 中提取数据并在推特上发布

标签 javascript node.js json

我正在设置一个推特机器人来发布城市的温度,知道为什么我的设置功能不起作用吗?

我尝试更改为不同的 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/

相关文章:

javascript - Notepad++ 无法打开我的 html 文件,而是打开 google 主页

javascript - geoCoder respsone 循环 - 无法读取未定义的属性 '0'

javascript - 如何正确测试函数

node.js - 在 WSL Ubuntu 20.04 上安装 npm 后,我收到消息 "/usr/bin/env: ‘bash\r’ : No such file or directory"

json - 在 Bigquery json_extract() 函数中转义字符

java - 如何在 Spring/Java 中使用 JSON 未命名值来使用 REST?

javascript - 如何迭代数组 - jquery

javascript - 如何过滤掉发布的隐藏表单输入类型?

node.js - Mongoose,根据外键/填充键排序

C# JsonSerializer.Serialize 返回一个空对象