Search code examples
pythonoauthtweepytwitter-oauthtwitterapi-python

How to use 3-legged OAuth in Tweepy with Twitter API v2 to read protected Tweets?


I am trying to access protected Tweets from Twitter handles using Tweepy and Twitter API v2. To do this I know I have to use 3-legged OAuth. I have done it and successfully generated an access token and access token secret. But with those access keys I am not able to see the protected Tweets of my own protected account when I am authorizing with the same account.

Does anyone know what I am doing wrong here?

This is a login.py file with the authorization function

#!/usr/bin/env python
import tweepy 


def authrize():

    CONSUMER_KEY = "XXXXXXXXXXXxx"

    CONSUMER_SECRET = "XXXXXXXXXXXXXXXXx"

    BEARER_TOKEN = "XXXXXXXXXXXXXXXX"

    auth = tweepy.OAuth1UserHandler(CONSUMER_KEY, CONSUMER_SECRET,callback="oob")

    print(auth.get_authorization_url())

    verifier = input("Input PIN: ")
    ACCESS_TOKEN, ACCESS_TOKEN_SECRET = auth.get_access_token(verifier)

    print(ACCESS_TOKEN,"******",ACCESS_TOKEN_SECRET)
    return (CONSUMER_KEY,CONSUMER_SECRET,BEARER_TOKEN,ACCESS_TOKEN,ACCESS_TOKEN_SECRET)

and my tweepy code app.py is as follows

import tweepy
import login

def get_client(CONSUMER_KEY,CONSUMER_SECRET,BEARER_TOKEN,ACCESS_TOKEN,ACCESS_TOKEN_SECRET):
    client = tweepy.Client(bearer_token=BEARER_TOKEN,
                           consumer_key=CONSUMER_KEY,
                           consumer_secret=CONSUMER_SECRET,
                           access_token=ACCESS_TOKEN,
                           access_token_secret=ACCESS_TOKEN_SECRET, wait_on_rate_limit=True)
    return client


def get_user_id(username):
    user = client.get_user(username=username)
    return user.data.id
    


def pagination(user_id):
    responses = tweepy.Paginator(client.get_users_tweets, user_id,
                                 exclude='replies,retweets',
                                 max_results=100,
                                 expansions='referenced_tweets.id',
                                 tweet_fields=['created_at', 'public_metrics', 'entities'])
    return responses

def get_original_tweets(user_id):
    tweet_list = []
    responses = pagination(user_id)
    for response in responses:
        if response.data ==None:
            continue
        else:
            for tweets in response.data:
                tweet_list.append([tweets.text,
                                tweets['public_metrics']['like_count'],
                                tweets['public_metrics']['retweet_count'],
                                tweets['created_at'].date()])

    return tweet_list


def user_details(username):
    user = {}
    user_response = client.get_user(username=username, user_fields=['public_metrics', 'description', 'url'])
    user_metrics = user_response.data['public_metrics']
    user['description'] = user_response.data['description']
    user['followers'] = user_metrics['followers_count']
    user['following'] = user_metrics['following_count']
    return user

keys = login.authrize()
client = get_client(*keys)
username = input("Username:")
userid = get_user_id(username)
print(user_details(username))
print(get_original_tweets(userid))

Solution

  • By default, Client.get_users_tweets uses your bearer token rather than OAuth 1.0a User Context to authenticate. You need to set the user_auth parameter to True.