Close Navigation
Learn more about IBKR accounts
How to get Tweets using Python and Twitter API v2 – Part II

How to get Tweets using Python and Twitter API v2 – Part II

Posted October 18, 2022
Udisha Alok
QuantInsti

Get Tweet(s) with Tweet Id(s) using client

We can fetch a tweet given its tweet id using the get_tweet() method.

tweet_id = '1532694058916753410'

# Get tweet with a given tweet id
tweet = client.get_tweet(id=tweet_id)
print(f"The tweet with id {tweet_id} is:\n")
print(tweet.data.text)  
get_tweet_text.py hosted with ❤ by GitHub

What if we want to get the tweets for multiple tweet ids? The approach is similar to the above.

tweet_ids= ['1532694058916753410', '1532693690224758784', '1532694050523860992']

# Get tweet with a given tweet id
tweets = client.get_tweets(ids=tweet_ids)

for tweet in tweets.data:
    print(f"The tweet with id {tweet.id} is:\n")
    print(tweet.text,"\n",50*"-")
get_tweets_from_multiple_ids.py hosted with ❤ by GitHub

Get a user’s followers using client

Would you like to now check the followers a user has? Let us see how you can do that.

id = "869660137"

followers = client.get_users_followers(id=id)

print("These are the people following this user:")

for count, follower in enumerate(followers.data):
    print(count+1,follower)
get_followers.py hosted with ❤ by GitHub

Get users that the user follows using client

And who does this user follow? You may be interested to know that too.

id = "869660137"

followed = client.get_users_following(id=id)

print(f"This user follows {len(followed[0])} users.\n")

print("This user follows the following:\n")
for count, f in enumerate(followed.data):
    print(count+1, f"User ID: {f.id}    Name: {f.name}")
get_followed_persons_from_user.py hosted with ❤ by GitHub

Get a user’s Tweets using client

Similar to how we fetched a user’s tweet using API, we can fetch a user’s tweets using the client’s get_users_tweets() method. By default, we will have values only for the tweet id and the text in the response. If we want to access the other tweet fields ⁽⁵⁾, we will have to specify them separately, as shown below.

# Shall we check out this user's tweets?
name = 'elonmusk'

# Fetch user data
user=client.get_user(username=name).data

# Extract the user id and user name
user_id = user.id
user_name = user.name

# Fetch tweets by the user
tweets = client.get_users_tweets(id=user_id, tweet_fields=['id', 'text', 'created_at', 'context_annotations'])

print(f"Here are the recent tweets by {user_name}:\n")

for tweet in tweets.data:
    print(tweet.created_at,'\n', tweet,"\n", tweet.context_annotations,"\n\n")
get_user_tweets.py hosted with ❤ by GitHub

Get Tweets that a user liked using client

id = "869660137"

tweets = client.get_liked_tweets(id=id)

for count, tweet in enumerate(tweets.data):
    print(count+1, "(", tweet.id, ")", tweet, "\n")
get_liked_tweets.py hosted with ❤ by GitHub

Get users who Retweeted a Tweet using client

tweet_id = '1533413197629296640'

retweeters = client.get_retweeters(id=tweet_id)

for count, users in enumerate(retweeters.data):
    print(count+1, users)
get_users_that_retweeted.py hosted with ❤ by GitHub

Search recent Tweets using client

The search_recent_tweets() method returns tweets from the last seven days that match the given search query. You can also specify the start and end times for the search.

By default, the search results will be in the form of a response containing the tweet ID and tweet text. Please note that the max_results parameter can only have a value between 10 and 100.

query = 'from:quantinsti -is:retweet'

tweets = client.search_recent_tweets(query=query, max_results=100)

for tweet in tweets.data:
    print(tweet.text)
search_recent_tweets.py hosted with ❤ by GitHub

Get Tweet count for a search query using client

How many tweets about Elon Musk were there recently in English which were not retweets? Let us see how we can get a count of such tweets using the get_recent_tweets_count() method.

# Search for queries in English language with 'elon musk' that are not retweets
query = 'elon musk lang:en -is:retweet'

# Granularity can be minute, hour, day
counts = client.get_recent_tweets_count(query=query, granularity='day')

for count in counts.data:
    print(count)
get_tweet_count.py hosted with ❤ by GitHub

Head to this ⁽⁶⁾ link if you would like to know more about building queries for searching tweets.

Stay tuned for Part III to learn about Pagination in client.

Visit QuantInsti for additional insights on this topic: https://blog.quantinsti.com/twitter-api-v2/.

Disclosure: Interactive Brokers

Information posted on IBKR Campus that is provided by third-parties does NOT constitute a recommendation that you should contract for the services of that third party. Third-party participants who contribute to IBKR Campus are independent of Interactive Brokers and Interactive Brokers does not make any representations or warranties concerning the services offered, their past or future performance, or the accuracy of the information provided by the third party. Past performance is no guarantee of future results.

This material is from QuantInsti and is being posted with its permission. The views expressed in this material are solely those of the author and/or QuantInsti and Interactive Brokers is not endorsing or recommending any investment or trading discussed in the material. This material is not and should not be construed as an offer to buy or sell any security. It should not be construed as research or investment advice or a recommendation to buy, sell or hold any security or commodity. This material does not and is not intended to take into account the particular financial conditions, investment objectives or requirements of individual customers. Before acting on this material, you should consider whether it is suitable for your particular circumstances and, as necessary, seek professional advice.

Disclosure: API Examples Discussed

Throughout the lesson, please keep in mind that the examples discussed are purely for technical demonstration purposes, and do not constitute trading advice. Also, it is important to remember that placing trades in a paper account is recommended before any live trading.

IBKR Campus Newsletters

This website uses cookies to collect usage information in order to offer a better browsing experience. By browsing this site or by clicking on the "ACCEPT COOKIES" button you accept our Cookie Policy.