linvi / tweetinvi

Tweetinvi, an intuitive Twitter C# library for the REST and Stream API. It supports .NET, .NETCore, UAP (Xamarin)...
MIT License
1.01k stars 220 forks source link

Unable to authenticate at all #1183

Open Devtr0n opened 2 years ago

Devtr0n commented 2 years ago

Hello, I am trying to run the example from the "Getting Started" instructions., using this code example:

static async Task Main(string[] args)
{
    var userClient = new TwitterClient("CONSUMER_KEY", "CONSUMER_SECRET", "ACCESS_TOKEN", "ACCESS_TOKEN_SECRET");
    var user = await userClient.Users.GetAuthenticatedUserAsync();
    Console.WriteLine(user);
}

I am unable to authenticate no matter what I try. I have tried my keys and tokens. I have also regenerated my keys and tokens, and I still get the same error message, which is:

Reason : Bad Request Details : Bad Authentication data. (215) Code : 400 Date : 9/23/2022 5:27:02 PM -05:00 URL : https://api.twitter.com/1.1/account/verify_credentials.json?include_email=true Twitter documentation description : Bad Request - The request was invalid or cannot be otherwise served. An accompanying error message will explain further. In API v1.1, requests without authentication are considered invalid and will yield this response.

I have also tried the different overloads of the TwitterCredentials class, like so:

static async Task Main(string[] args)
{
    var userClient = new TwitterClient("CONSUMER_KEY", "CONSUMER_SECRET", "ACCESS_TOKEN"); // only 3 parameters here
}

but I get a different error message:

{"errors":[{"message":"You currently have Essential access which includes access to Twitter API v2 endpoints only. If you need access to this endpoint, you’ll need to apply for Elevated access via the Developer Portal. You can learn more here: https://developer.twitter.com/en/docs/twitter-api/getting-started/about-twitter-api#v2-access-leve","code":453}]}

I am unsure what I am missing or doing wrong. I copied and pasted my keys directly from twitter. Also, I checked my Twitter developer account and verified I have "Essential" permissions, but not "Elevated" permissions. Do I need "Elevated" to be setup?? I wouldn't think so....

image

I have been able to use Curl and PowerShell to hit the "sample stream" example straight from Twitter's documentation, and that does work, so I know my bearer token is valid.

Any help is greatly appreciated, as I would ultimately like to stream the API for the "sample stream V2" example.

Devtr0n commented 2 years ago

When I use the example in the documentation for V2 sample stream, I get an error response like this:

Reason : {
Code : -1
Date : 9/26/2022 10:37:44 AM -05:00
URL : https://api.twitter.com/2/tweets/sample/stream?expansions=attachments.poll_ids%2Cattachments.media_keys%2Cauthor_id%2Centities.mentions.username%2Cgeo.place_id%2Cin_reply_to_user_id%2Creferenced_tweets.id%2Creferenced_tweets.id.author_id&media.fields=duration_ms%2Cheight%2Cmedia_key%2Cpreview_image_url%2Ctype%2Curl%2Cwidth&place.fields=contained_within%2Ccountry%2Ccountry_code%2Cfull_name%2Cgeo%2Cid%2Cname%2Cplace_type&poll.fields=duration_minutes%2Cend_datetime%2Cid%2Coptions%2Cvoting_status&tweet.fields=attachments%2Cauthor_id%2Ccontext_annotations%2Cconversation_id%2Ccreated_at%2Centities%2Cgeo%2Cid%2Cin_reply_to_user_id%2Clang%2Cpossibly_sensitive%2Creferenced_tweets%2Csource%2Ctext%2Cwithheld%2Cpublic_metrics&user.fields=created_at%2Cdescription%2Centities%2Cid%2Clocation%2Cname%2Cpinned_tweet_id%2Cprofile_image_url%2Cprotected%2Curl%2Cusername%2Cverified%2Cwithheld%2Cpublic_metrics
Twitter documentation description : 

What is Error Code -1 ? I tried searching for it but I do not receive much information about it?

StyptoAlgo commented 2 years ago

Same issue

Devtr0n commented 2 years ago

@StyptoAlgo I eventually figured it out. There are different "client" types but they are not mentioned in the beginning of the examples. You have to dig and dig and find the TwitterClient wiki page. I ended up using a variation of the "appClient", although it's not the same in the example on the wiki!

I eventually noticed in some examples throughout the wiki, that the "TwitterClient" is constructed differently. There are also overloaded methods for the "TwitterCredientals" method.

Here is what I ended up using (in .NET 6, so it's a little bit different than regular "Startup.cs" files):

builder.Services.AddSingleton(sp =>
{
    var config = configuration.Build();
    var consumerKey = config["Twitter:ConsumerKey"];
    var consumerSecret = config["Twitter:ConsumerSecret"];
    var bearerToken = config["Twitter:BearerToken"];
    var userCredentials = new TwitterCredentials(consumerKey, consumerSecret, bearerToken);
    return new TwitterClient(userCredentials);
});

I store the consumer key, secret and bearer token in my appSettings.json configuration file. And the "TwitterCredentials" uses the overload method that needs the bearer token.

Now in my service layer, I can access it easily like so:

 public class TweetProcessor
 {
      private readonly TwitterClient _twitterClient;

      public TweetProcessor(TwitterClient twitterClient)
      {
          _twitterClient = twitterClient;
      }
      // etc
 }

and then finally, viola!

// call the twitter API stream
var sampleStreamV2 = _twitterClient.StreamsV2.CreateSampleStream();
sampleStreamV2.TweetReceived += (sender, args) =>
{
       // do some stuff here, etc
       // find any hashtags included in the "tweet"
       var hashTags = args.Tweet.Entities?.Hashtags;
 };
 await sampleStreamV2.StartAsync();

I hope this helps put you in the right direction. I really pulled my hair out a few days on this...