skip to Main Content

Hi I’m currently working on a Twitter bot with the Twitter API and Node.JS. I want the bot to return all of my followers and some of their features in an javascript object. Something like :

{[‘id’, ‘screen_name’, ‘name’, ‘screen_name’, ‘followers_count’,
‘friends_count’]}

RN my code is :

var Twitter = new TwitterPackage(config);


var options = 
              {
                screen_name: 'mowsolicious',
              };

Twitter.get('followers/ids', options,  function (err, data) {    // returns a list of ids
  var nbFollowers = data.ids.length
  var id = []
  console.log(nbFollowers)                                       // how many followers I have
  for (i=0 ; i <= nbFollowers ; i++) {
    ids = data.ids
    var id = ids[i]
    Twitter.get('users/show/' + id, function(err, data)  {    
      console.log(id + " - " + data.name + " - " + data.screen_name + " - " + data.followers_count + " - " + data.friends_count)
    })
  }
})

I’m pretty sure something is terribly wrong with my method (more precisely when I put the Twitter.get thing in the loop) and it returns a bunch of undefined in the console.

I tried to work with the API doc but I’m experiencing some troubles understanding it. If someone could help that would be great.

Thank you

3

Answers


  1. Most likely, you get undefined because the user is not found :

    [ { code: 50, message: 'User not found.' } ]
    

    Checking err variable would take care of that. But looking at GET followers/id documentation, you should use GET users/lookup to efficiently request mutliple user objects (up to 100 user per request with user id delimited by comma)

    Also, I assume you’d like a unique callback to be called when all requests are completed, using Promises will take care of that :

    var res_array = [];
    
    function getUserInfo(id_list) {
        return Twitter.get('users/lookup', {
                "user_id": id_list
            }).then(function(data) {
                res_array.push(data);
            })
            .catch(function(error) {
                throw error;
            })
    }
    
    Twitter.get('followers/ids', function(err, data) {
    
        if (err) {
            console.log(err);
            return;
        }
    
        console.log("total followers : " + data.ids.length);
    
        var requestNum = Math.floor(data.ids.length / 100);
        var remainder = data.ids.length % 100;
    
        var promises_arr = [];
    
        for (var i = 0; i < requestNum; i++) {
            promises_arr.push(getUserInfo(data.ids.slice(i * 100, i * 100 + 100).join(",")));
        }
        if (remainder != 0) {
            promises_arr.push(getUserInfo(data.ids.slice(requestNum * 100, requestNum * 100 + 100).join(",")));
        }
    
        Promise.all(promises_arr)
            .then(function() {
                for (var i in res_array) {
                    for (var j in res_array[i]) {
                        var user = res_array[i][j];
                        console.log(user.id + " - " +
                            user.name + " - " +
                            user.screen_name + " - " +
                            user.followers_count + " - " +
                            user.friends_count)
                    }
                }
            })
            .catch(console.error);
    })
    
    Login or Signup to reply.
  2. List of followers can be retrieved with superface sdk , try it based on the example below

    npm install @superfaceai/one-sdk
    npx @superfaceai/cli install social-media/followers
    
    const { SuperfaceClient } = require('@superfaceai/one-sdk');
    
    const sdk = new SuperfaceClient();
    
    async function run() {
      // Load the installed profile
      const profile = await sdk.getProfile('social-media/followers');
    
      // Use the profile
      const result = await profile
        .getUseCase('GetFollowers')
        .perform({
          profileId: '429238130'
        });
    
      return result.unwrap();
    }
    
    run();
    Login or Signup to reply.
  3. This works pretty fine

    
    import fetch from 'node-fetch'
    
    async function getFollowers(username) {
    
      const response = await fetch(`https://api.twitter.com/1.1/followers/list.json?screen_name=${username}`, {
        headers: {
          Authorization: `Bearer ${<yourbearertoken>}`
        }
      });
    
      // Parse the response as JSON
      const data = await response.json();
      return data.users;
    }
    
    const followers = await getFollowers("<username>");
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search