Search code examples
twitter4j

Get my Twitter ID with twitter4j


What's the best way to get my own twitter ID from twitter4j?

Say I have the following:

public static void main(String [] args)
  {
  Twitter t; 
  long cursor = -1;
  long myID = 123456789L;
  long[] friendIDs 

  try
    {
    t = TwitterFactory.getSingleton();
    friendIDs = t.getFollowersIDs(myID, cursor).getIDs();
    //do something with frienIDs ....
   }

How to I get the twitter object to generate myID?


Solution

  • From your code snippet it seems you are trying to login to your Twitter A/c and fetch your connections/followers and do something with them.

    First you need to register your app with Twitter and generate OAuth Authentication. You will get following - consumerkey, consumersecret, accesstoken and accesstokensecret.

    Using the keys and secret you would create a Twitter instance, which you can use to access your Twitter User ID.

    String consumerkey = "consumerkey";
    String consumersecret = "consumersecret";
    String accesstoken = "accesstoken";
    String accesstokensecret = "accesstokensecret";
    
    ConfigurationBuilder twitterConfigBuilder = new ConfigurationBuilder();
    twitterConfigBuilder.setDebugEnabled(true);
    twitterConfigBuilder.setOAuthConsumerKey(consumerkey);
    twitterConfigBuilder.setOAuthConsumerSecret(consumersecret);
    twitterConfigBuilder.setOAuthAccessToken(accesstoken);
    twitterConfigBuilder.setOAuthAccessTokenSecret(accesstokensecret);
    
    Twitter twitter = new TwitterFactory(twitterConfigBuilder.build()).getInstance();
    myID = twitter.getID(); // This will give the id with which application was registered.
    

    Hope this helps. Also check this - http://iag.me/socialmedia/how-to-create-a-twitter-app-in-8-easy-steps/.