Search code examples
javatwittertwitter4j

How do turn twitter IDs to Username in twitter4j? Or can I use id to get a user bio?


So I get a bunch of ids from

do {
    if (0 < SklsIds.length) {
        ids = twitter.getFriendsIDs(identlong, cursor);
    } else {
        ids = twitter.getFriendsIDs(cursor);
    }
    for (long id : ids.getIDs()) {
        followers.add(id);
    }
} while ((cursor = ids.getNextCursor()) != 0);

Then I want to use these ids get a users bio:

for (Long ideez : followers) {
    System.out.println(twitter.showUser(ideez.toString()));
    String bio = ideez.toString().getDescription().toLowerCase();
}

I have this rn but I don't think you can get a user's bio with just id or whatever this is. pls help


Solution

  • We can do something like this in order to retrieve the name and bio of our Twitter user's friends:

    try {
        Twitter twitter = new TwitterFactory(cb.build()).getInstance();
        long cursor = -1;
        IDs ids;
        System.out.println("Listing followers's ids.");
        do {
            ids = twitter.getFriendsIDs(cursor);
            // Retrieve the follower IDs into an array
            long[] userIds = ids.getIDs();
            // Iterate through the array in batches of 100. We need batches of 100 because lookupUser method accept at most 100 ids
            for (int i = 0; i < userIds.length; i += 100) {
                ResponseList<User> users = twitter.lookupUsers(Arrays.copyOfRange(ids.getIDs(), i, Math.min(i + 100, userIds.length)));
                // Iterate through the users and retrieve information about them
                for (User user : users) {
                    // Do something with the user name
                    System.out.println(user.getName());
    
                    // Do something with the bio description
                    System.out.println(user.getDescription());
                }
            }
        } while ((cursor = ids.getNextCursor()) != 0);
        System.exit(0);
    } catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to get followers' ids: " + te.getMessage());
        System.exit(-1);
    }