skip to Main Content

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

2

Answers


  1. Are you using p5.js? You should note that p5 won’t run on node server side as it is dependent on accessing the window object. Hence loadJSON function is undefined.

    you could use XMLHttpRequest for retrieving data.

     function setup() {
      var request = new XMLHttpRequest()
    
      request.open('GET', 'https://api.apixu.com/v1/current.json?key=############################&q=Colombo', true)
      request.onload = function() {
        // Begin accessing JSON data here
        var data = JSON.parse(this.response)
    
        if (request.status >= 200 && request.status < 400) {
          gotData(data)
        } else {
          console.log('error')
        }
      }
    
      request.send()
    }
    
    Login or Signup to reply.
  2. 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');
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search