0

I'm playing around with programming a twitter bot using this great tutorial: https://shiffman.net/a2z/twitter-bots/

I'm trying to get an array of the ids of tweets my bot has replied to. I can get the array to show in the console using the below code.

var params = {
        q:'from:MYACCOUNT',
        result_type:'recent'
        }

T.get('search/tweets', params, gotData); 


function gotData(err, data, response) {
    var tweets = data.statuses;
    var arr = []
    for (var i = 0; i < tweets.length; i++) {
        arr.push(tweets[i].in_reply_to_status_id_str);
        };

        console.log(arr);
    };

Where I begin to struggle is making that array usable outside the function. I tried the following:

function gotData(err, data, response) {
    var tweets = data.statuses;
    var arr = []
    for (var i = 0; i < tweets.length; i++) {
        arr.push(tweets[i].in_reply_to_status_id_str);
        };

        return arr;
    };
    
var y = gotData();

console.log(y);

And the error output is below:

/home/ubuntu/testbot.js:28
        var tweets = data.statuses;
                          ^

TypeError: Cannot read property 'statuses' of undefined
    at gotData (/home/ubuntu/testbot.js:28:20)
    at Object.<anonymous> (/home/ubuntu/testbot.js:37:9)
    at Module._compile (module.js:652:30)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)
    at Function.Module.runMain (module.js:693:10)
    at startup (bootstrap_node.js:188:16)
    at bootstrap_node.js:609:3

This is my first go at anything like this, so any advice would be greatly appreciated.

Waterbarry
  • 55
  • 6
  • You need to call `T.get` to get the data, not `gotData` which *expects* the data. And no, you cannot make it synchronously return the array. – Bergi Jul 23 '20 at 21:57

1 Answers1

0

You are calling gotData() but you aren't passing it the arguments that it requires (err, data, response)

You can try changing it to the following:

function gotData(data) {
    var tweets = data.statuses;
    var arr = []
    for (var i = 0; i < tweets.length; i++) {
        arr.push(tweets[i].in_reply_to_status_id_str);
        };

        return arr;
    };
    
var y = gotData({
    statuses: [
    {
     in_reply_to_status_id_str: '0'
    },
    {
     in_reply_to_status_id_str: '1'
    },
    {
     in_reply_to_status_id_str: '2'
    },
  ]
});

console.log(y);
bwasilewski
  • 170
  • 7
  • This didn't quite work for me but you pointed me in the right direction with "You are calling gotData() but you aren't passing it the arguments that it requires (err, data, response)". I ended up just nesting my other functions inside the gotData function – Waterbarry Aug 01 '20 at 18:40