user7660047
user7660047

Reputation: 166

How to get user screen_name in Tweepy with V2 API?

I'm specifically using V2 API with tweepy and am struggling to get what was user screen_name. The best I have is:

tweets = client.search_recent_tweets(query=query,expansions='author_id',max_results=10)

This would need a round trip to get user_name. Surely there has to be a way to do it in a single query?

Also, screen_name is username in V2, but that still has me no closer as that's not an accepted parameter for either fields or expansions.

Reference https://developer.twitter.com/en/docs/twitter-api/users/lookup/migrate/standard-to-twitter-api-v2

Well after more searching ... it was not obvious:

tweets = client.search_recent_tweets(query=query,tweet_fields=['context_annotations', 'created_at'], expansions='entities.mentions.username',max_results=10)

Reference https://developer.twitter.com/en/docs/twitter-api/tweets/search/api-reference/get-tweets-search-recent#Optional

But the user.fields parameter mentioned in the above still doesn't work.

Upvotes: 0

Views: 2189

Answers (1)

Mickaël Martinez
Mickaël Martinez

Reputation: 1843

Yet the username is listed as an available field in the user.fields enum.

You can add it to your last request:

tweets = client.search_recent_tweets(query=query,tweet_fields=['context_annotations', 'created_at'], expansions='entities.mentions.username', max_results=10, user_fields=['username']

But you should use the author_id expansion if you want the username of the tweet's author.

Please also note that the username will be in the includes dict (at the root), not in the data one.

Upvotes: 2

Related Questions