Search code examples
pythontwittertweepy

Querying Most Popular Tweets using Tweepy V2 API


I am scraping Twitter tweets using the Tweepy V2 API, but am having trouble querying for more popular tweets with higher retweets and likes.

My application requires that I ignore retweets and replies for tweets via -is:retweet -is:reply. I am searching for the original tweets themselves.

However, I currently have numerous tweets which have very low likes and retweets, which is inadequate for my application.

Is there any method to query based on popularity or retweets count in Tweepy V2? The popularity filter seems to only exist in Tweepy V1 (Is there a way to search for Top tweets with tweepy instead of latest tweets?).

Code is shown below:

query_str = "#chosen_topic lang:en -is:retweet -is:reply"

client = tweepy.Client(bearer_token=config.BEARER_TOKEN, consumer_key=
config.CONSUMER_KEY,consumer_secret= config.CONSUMER_SECRET,access_token=
config.ACCESS_TOKEN,access_token_secret= config.ACCESS_TOKEN_SECRET)

for tweet_batch in tweepy.Paginator(client.search_all_tweets, query=query_str,
                                    tweet_fields=['context_annotations','created_at', 'public_metrics','author_id', 'lang', 'geo', 'entities'], 
                                    user_fields=['name','username','location','verified','description'],
                                    max_results=100, expansions='author_id'):

    tweet_data = tweet_batch.data
    for tweet in tweet_data:
        print(tweet.public_metrics['reply_count'])

Solution

  • You can add the the sort_order='relevancy' argument to your search (see here).

    I don't know if this is the exact equivalent of the result_type='popular' argument in the V1 API, but it seems to be the best way to do what you're asking for in the V2 API.