Ad

Pulling Data Off A Weather API And Tweeting It

- 1 answer

I'm setting up a twitter bot to tweet out the temperature of a city, any idea why my setup function isn't working?

I tried changing to a different API but nothing seems to work.

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

}

I get this error:

ReferenceError: loadJSON is not defined

Ad

Answer

I'd suggest using the request library to pull the weather conditions, in particular use the request-promise-native library, this makes it very easy to read API data:

Just do:

npm install request
npm install request-promise-native

To install, then:

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');
Ad
source: stackoverflow.com
Ad