Search code examples
pythontwittertweepy

Tweepy + Twitter API v2: I want to extract the tweet.id for media_key only


What if I want to take the Tweet ID and media_keys and only get the Tweet ID that has media_keys?

I was trying to do it with this sample but I got stuck: https://docs.tweepy.org/en/stable/examples.html

client = tweepy.Client(consumer_key=API_KEY, consumer_secret=API_SECRET, access_token=ACCESS_TOKEN, access_token_secret=ACCESS_TOKEN_SECRET, bearer_token=Bearer_token)

counts = 10

search_result = client.get_list_tweets(id='list id', max_results=counts, expansions=["attachments.media_keys"])
tweets = search_result.data

includes = search_result.includes
medias = includes['media']

for tweetid in tweets:
    tid = tweetid.id

mediass = {media['media_key']: media for media in medias}
for tweet in tweets:
    print(tweet.id, mediass)

Solution

  • You can check the attachments field of Tweet objects to obtain media keys for media attached to the Tweet.