I am trying to use the Tweepy python package to get the actual replies to a Tweet. I break down the process I have worked on so far:
I import my modules and configure authentication variables with tweepy:
client = tweepy.Client(bearer_token=bearer_token, wait_on_rate_limit=True)
covid_tweets = []
for mytweets in tweepy.Paginator(client.search_all_tweets, query = '#COVID lang:en',
user_fields=['username', 'public_metrics', 'description', 'location'], tweet_fields
= ['created_at', 'geo', 'public_metrics', 'text'], expansions = 'author_id',
start_time = '2019-12-30T00:00:00Z', end_time = '2020-01-15T00:00:00Z',
max_results=10):
time.sleep(2)
covid_tweets.append(mytweets)
I then search for the hashtags I want and the parameters of the Tweepy Paginator with a for loop and append unto an empty list:
client = tweepy.Client(bearer_token=bearer_token, wait_on_rate_limit=True)
covid_tweets = []
for mytweets in tweepy.Paginator(client.search_all_tweets, query = '#COVID lang:en',
user_fields=['username', 'public_metrics', 'description', 'location'], tweet_fields
= ['created_at', 'geo', 'public_metrics', 'text'], expansions = 'author_id',
start_time = '2019-12-30T00:00:00Z', end_time = '2020-01-15T00:00:00Z',
max_results=10):
time.sleep(2)
covid_tweets.append(mytweets)
Then I convert this list into a dataFrame by extracting certain key fields[a user dictionary, user_object]:
#Convert Covid-19 tweets to a DF
result = []
user_dict = {}
# Loop through each response object
for response in covid_tweets:
for user in response.includes['users']:
user_dict[user.id] = {'username': user.username,
'followers': user.public_metrics['followers_count'],
'tweets': user.public_metrics['tweet_count'],
'description': user.description,
'location': user.location
}
for tweet in response.data:
# For each tweet, find the author's information
author_info = user_dict[tweet.author_id]
#check for condition
if ('RT @' not in tweet.text):
# Put all information we want to keep in a single dictionary for each tweet
result.append({'author_id': tweet.author_id,
'tweet_id': tweet.id,
'username': author_info['username'],
'author_followers': author_info['followers'],
'author_tweets': author_info['tweets'],
'author_description': author_info['description'],
'author_location': author_info['location'],
'text': tweet.text,
'created_at': tweet.created_at,
'retweets': tweet.public_metrics['retweet_count'],
'replies': tweet.public_metrics['reply_count'],
'likes': tweet.public_metrics['like_count'],
'quote_count': tweet.public_metrics['quote_count']
})
# Change this list of dictionaries into a dataframe
df_1 = pd.DataFrame(result)
- Now my issue is, from the dataFrame, I get to see tweets and reply_count for tweets and a proof of the image is shown below:

And I checked how I can get the replies from the tweets. So I did some checks and wanted to follow this code flow function:
def get_all_replies(tweet, api, fout, depth=10, Verbose=False):
global rep
if depth < 1:
if Verbose:
print('Max depth reached')
return
user = tweet.user.screen_name
tweet_id = tweet.id
search_query = '@' + user
# filter out retweets
retweet_filter = '-filter:retweets'
query = search_query + retweet_filter
try:
myCursor = tweepy.Cursor(api.search_tweets, q=query,
since_id=tweet_id,
max_id=None,
tweet_mode='extended').items()
rep = [reply for reply in myCursor if reply.in_reply_to_status_id == tweet_id]
except tweepy.TweepyException as e:
sys.stderr.write(('Error get_all_replies: {}\n').format(e))
time.sleep(60)
if len(rep) != 0:
if Verbose:
if hasattr(tweet, 'full_text'):
print('Saving replies to: %s' % tweet.full_text)
elif hasattr(tweet, 'text'):
print('Saving replies to: %s' % tweet.text)
print("Output path: %s" % fout)
# save to file
with open(fout, 'a+') as (f):
for reply in rep:
data_to_file = json.dumps(reply._json)
f.write(data_to_file + '\n')
# recursive call
get_all_replies(reply, api, fout, depth=depth - 1, Verbose=False)
return
So basically, with this function, I loop through the dataframe and pick the "tweet_id" & "the screen_name" for the tweet, then design a search query but I realized at the section of the "rep" list returns an empty list, and debugging line by line, actually showed that the in_reply_to_status_id is different from the tweet_id and the cause for the empty list even though the reply count for the dataframe shows a non-zero.
I know this is long but I really wanted to show what I have done so far and explain each process. Thank you NB: I have access to Academic Research API