I need to be able to make different Twitter
instances with same consumer key and secret but different user level access tokens.
I have already obtained the access tokens for 10 users based on consumer credentials of my app by using standard Twitter OAuth Sign In protocol. Now, I want to create a list of Twitter Instances each initialized with a separate Accesstoken
. However, I'm not able to do this.
My leading cause of confusion is, that, I don't understand how Twitter4j
instantiates Twitter instances. I don't understand the difference between TwitterFactory.getSingleton()
method and TwitterFactory().getInstance()
method.
I also don't understand if AccessTokens can work independently without supplying consumer key and secret. Or do I need to provide Consumer key and secret while using Accesstokens.
If someone can explain in detail the design for my requirement it'll be highly appreciated.
In short, you may want code like this:
TwitterFactory tf = new TwitterFactory();
Twitter user1 = tf.getInstance(new AccessToken("XXX","XXX"));
Twitter user2 = tf.getInstance(new AccessToken("XXX","XXX"));
A Twitter instance can handle only one account. To deal with multiple accounts, you need to instantiate multiple Twitter instances with TwitterFactory#getInstance(AccessToken);
Hard-coding consumer key/secret is not suggested and you may want to specify them in twitter4j.properties. http://twitter4j.org/en/configuration.html#fileconfiguration
Damn it a little bit more googling would have saved me 100 rep.
Let's be clear: there is a difference between Twitter
and TwitterStream
instances. Twitter
instances can indeed have one consumer key+ secret and multiple OAuth tokens. That answers the question by the OP.
Now, for Twitterstream
instances (that are needed to access the Twitter Streaming API), that's different. You can only have only one TwitterStream ojbect running at a given time, not several even if they have different OAuth tokens.
According to dev.twitter.com,
You'll be best served by sticking to the concept of "one account, one application, one open connection" when connecting to the stream.twitter.com endpoints. If there are other distinct applications you plan to use with stream.twitter.com, I would strive to follow the same 1:1:1 concept for it.
You may find that at times stream.twitter.com lets you get away with more open connections here or there, but that behavior shouldn't be counted on.
I give the bounty to Yusuke Yamamoto since he provided the correct answer first, and do consider upvoting this one too if it clarifies things for you! ;-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With