Getting tweets of a specific user with public metrics

134 views Asked by At

I've been trying to get a specific users last tweets and the public metrics of it. In playgrounds i can easily get it but when i use tweepy i can't get public metrics.

import tweepy
auth = tweepy.OAuth2BearerHandler("token")
api = tweepy.API(auth)
client = tweepy.Client("token")
allTweets = client.get_users_tweets(900437084321832960,tweet_fields=['public_metrics',])
print(allTweets)

this returns only text and id but not public metrics

{
      "id": "id",
      "text": "text"
    },

1

There are 1 answers

0
yesildaladam On

Created a small python script to get last 1000 tweets of the user. It first creates jsonObject that will store all the tweet data later. Then creates a for loop, in first if block it checks if there is a pagination token or not. After getting the tweets it changes the data into a json object.

jsonObject = []
for x in range(10):
    if(paginationToken==""):
        tweetList = client.get_users_tweets(id=id,tweet_fields=['public_metrics'],max_results=100)
        print("a")
    else:
        tweetList = client.get_users_tweets(id=id,tweet_fields=['public_metrics'],pagination_token=paginationToken,exclude=['replies','retweets'],max_results=100)
        print("b")

    meta = tweetList.meta
    data = tweetList.data
    if(meta.__contains__('next_token')):
        paginationToken = meta['next_token']
    for tweet in data:
        metrics = tweet.public_metrics
        data = {}
        data['id'] = tweet.id
        data['text'] = tweet.text
        data['retweet_count'] = metrics['retweet_count']
        data['reply_count'] = metrics['reply_count']
        data['like_count'] = metrics['like_count']
        data['quote_count'] = metrics['quote_count']
        jsonObject.append(data)