2

I have a list (json file) containing Twitter account ID downloaded from my Twitter account, I was wondering if there was a way to use Tweepy to get the usernames (@handle) associated with those accountid?

I am a noob when it comes to using python and would appreciate as much hand holding as I could get as to how to go by it.

karthik akinapelli
  • 710
  • 1
  • 7
  • 14
martinkem
  • 21
  • 4

1 Answers1

0

There's Tweepy API v1.1 and Tweepy API v2, for better inclusiveness we can use Tweepy API v2 for this, as it does not require Elevated Access.

This post shows an authentication example for Tweepy API v2 using the tweepy.Client class seen in the Tweepy API docs with tokens and keys which can be obtained from the Twitter Developer Portal.

Once we have the authentication set, we can use the get_user method seen in the API docs here and the most important parameter here is the id parameter for the input, so that we can convert it into its respective username. We do this by calling user_get.data.username. You can look up all of its response fields here.

With this you can iterate your JSON file however you want and print the usernames given a twitter id.

Here's an example that prints 3 Twitter IDs as their usernames:

import tweepy

client = tweepy.Client(bearer_token="YOUR_BEARER_KEY",
                   consumer_key="YOUR_CONSUMER_KEY",
                   consumer_secret="YOUR_CONSUMER_SECRET",
                   access_token="YOUR_ACCESS_TOKEN",
                   access_token_secret="YOUR_ACCESS_TOKEN_SECRET")

twitterIdList = [3255900970, 432180172, 74274804]
for id in twitterIdList:
    user_get = client.get_user(id=id)
    user_name = user_get.data.username
    print(user_name)
bytro
  • 61
  • 6