Home > Software design >  Preview Image Url in tweepy V2
Preview Image Url in tweepy V2

Time:08-25

I have been trying to get the "preview_image_url" from a users timeline of tweets. I have been using V2 and paginator to get all the tweets as API have limit of 100 tweets per request. I am not able to access the media_fields as it's not present or pops up using dir method as well in python. This is the code I am using right now. the code only provides the media key for a particular tweet.

client = tweepy.Client(bearer_token=my_keys.BEARER_TOKEN)

username_list =  ["coinfessions"]
user_id = client.get_user(username="coinfessions").data.id
print(user_id)

for tweet in tweepy.Paginator(client.get_users_tweets, id= str(user_id), exclude=['retweets', 'replies'], expansions = "attachments.media_keys", media_fields = ["url","preview_image_url"],max_results=5 ).flatten(10): 
    if tweet.attachments is not None:
        print(tweet.attachments)

In one of the question posted on stack overflow. Someone suggested using the response as the return type. This method includes a "include" key where you can find the type, media_key and preview_image_url. I tried this method and it worked fine with normal response. However, it's not working well with the paginator. I think, I am doing something wrong here.

Anothor response on similar question points to this official FAQ page on tweepy documentation. If anyone can help me in understanding, how to access Models in V2 response.

CodePudding user response:

You can't access the includes if you are using the flatten methods.

The only way to access them is to iterates through the responses themselves.

paginator = tweepy.Paginator(client.get_users_tweets, [...])  # Without the flatten

for page in paginator:  # Each page is a response from the API
    page.data           # All the tweets in each page
    page.includes       # All the includes in each page

On a side note, I don't understand why you are using max_results=5. Because of that, you retrieve only 5 results per request and you cancel the advantages of the paginator.

  • Related