FeedHive / twitter-api-client

A user-friendly Node.js / JavaScript client library for interacting with the Twitter API.
MIT License
948 stars 84 forks source link

Unable to instantiate TwitterClient without accessToken and accessTokenSecret #61

Closed dvorsky closed 3 years ago

dvorsky commented 3 years ago

Describe the bug
I wish to use the client to obtain users accessToken and accessTokenSecret, but when I attempt to instantiate the client without those values provided I receive the error "ACCESS TOKEN needs to be provided". Interface for TwitterClient options indicates that both accessToken and accessTokenSecret are optional parameters.

I'm wondering if this is expected behavior and I'm doing something wrong or is this a bug?

To reproduce
Steps to reproduce the behavior:

  1. Instantiate TwitterClient without parameters accessToken and accessTokenSecret.
  2. TypeScript does not complain as the interface indicates these are optional params
  3. Run
  4. See error "ACCESS TOKEN needs to be provided".

Expected behavior
I would expect to be able to instantiate the client and use it to obtain users accessToken and accessTokenSecret, but I'm not sure how to do that.

Package Manager:
To install Twitter API Client, I used npm

Additional context
Compiled JS code: image

Interface: image

SimonHoiberg commented 3 years ago

Hi @dvorsky. I'm sorry for the late response.

Yes, this is expected behavior. You cannot instantiate the client without providing all sets of keys.

The first time you're instantiating the client (to obtain the tokens), you need to use the credentials provided when you create the app on the developer.twitter.com platform.

Now, after you instantiate with those, you can make a call to oauthRequestToken, to obtain the tokens.

const twitterClientAuthenticate = new TwitterClient({
  apiKey: process.env.TWITTER_KEY,
  apiSecret: process.env.TWITTER_SECRET,
  accessToken: process.env.TWITTER_ACCESS_TOKEN,
  accessTokenSecret: process.env.TWITTER_ACCESS_TOKEN_SECRET,
});

const tokens = await twitterClientAuthenticate.basics.oauthRequestToken({
  oauth_callback: 'https://call-back-url/callback',
});

Now, follow the authentication flow explained on the Twitter Documentation page. Then instantiate a new client using the OAuth token and secret you obtained.

const twitterClient = new TwitterClient({
  apiKey: process.env.TWITTER_KEY,
  apiSecret: process.env.TWITTER_SECRET,
  accessToken: oauth_token, // <- the one you obtained,
  accessTokenSecret: oauth_token_secret // <- the one you obtained,
});

Now, you can use the second client instance client to do stuff with Twitter on the behalf of the authenticated user :smile: