Get count of reply to a particular tweets - python

I am using the Python tweepy library.
I was successfully able to extract the 'liked' and 're-tweet' counts of a tweet using the below code:
# Get count of handles who are following you
def get_followers_count(handle):
user = api.get_user(handle)
return user.followers_count
# Get count of handles that you are following
def get_friends_count(handle):
user = api.get_user(handle)
return user.friends_count
# Get count of tweets for a handle
def get_status_count(handle):
user = api.get_user(handle)
return user.statuses_count
# Get count of tweets liked by user
def get_favourite_count(handle):
user = api.get_user(handle)
return user.favourits_count
However, I couldn't find a way to get the reply counts of a particular tweet.
Is it possible to get reply count of a tweet using tweepy or any other library like twython or even twitter4j?

The example code below shows how you could implement a solution to finding all replies for a single tweet. It utilizes the twitter search operator to:<account> and grabs all tweets that have replies to that account. By using since_id=tweet_id, the tweets returned from api.search are restricted to those created after the time the post was created. After these tweets are obtained, the in_reply_to_status_id attribute is used to check if the tweet captured is a reply to the tweet of interest.
auth = tweepy.OAuthHandler(API_KEY, API_SECRET_KEY)
api = tweepy.API(auth)
user = 'MollyNagle3'
tweet_id = 1368278040300650497
t = api.search(q=f'to:{user}', since_id=tweet_id,)
replies = 0
for i in range(len(t)):
if t[i].in_reply_to_status_id == tweet_id:
replies += 1
print(replies)
The limitation of this code is that is inefficient. It grabs more tweets than necessary. However, it seems that it is the best way to do this. Also, if you want to get replies of a very old tweet, you can implement the parameter max_id in api.search to limit the length of time you search over for replies.

Related

Twython returns less retweets than retweets shown on tweet

So I am using Twython to get retweeters of a tweet
tweet = self.twitter.show_status(id=tweet_id)
if tweet.get('retweet_count') > 0:
try:
retweets = self.twitter.get_retweets(id=tweet.get("id"))
except TwythonRateLimitError:
self.twitter, self.Last_Acc_Id = self.switch_accounts(MAX_ACCOUNTS)
self.get_retweeters(tweet)
# pprint(f"RETWEETS: {retweets}")
print(f"RETWEET COUNT: {len(retweets)}")
screen_name_list = []
for retweet in retweets:
# print(retweet)
# print()
# print(dir(retweet))
screen_name = retweet["user"]["screen_name"]
print(screen_name, f"https://twitter.com/{screen_name}/")
screen_name_list.append(screen_name)
But it returns only 20 retweets where as the tweet has 350 retweets
Tweet
Thanks! :)
As per documentation "get_retweets" returns "up to" the first 100 retweeters of a tweet.
-> Docs
You can specify the amount of entries per request with a parameter "count=100". Furthermore to iterate through multiple requests you should use a cursor (Twython API Docs).
I confirmed with the library source code that this endpoint is used.
-> Library Code
Depending of your usecase you should consider using the Webhook API
If the webhook API does not fit your use case, you should reconsider if you only need the retweet count or the retweeters.
The retweet count can simply be requested via GET statuses/show/:id. Look at "retweeted_count".
This is also available in Twython: show_status.
I hope this helped you! :)

How to search twitter replies more than a month using tweepy.api?

I'm trying to find replies to a specific user of a specific tweet ID using code:
tweets = tweepy.Cursor(api.search,q='to:'+name, tweet_mode='extended').items()
tweets_list = [[tweet.created_at, tweet.id,
tweet.full_text.encode('utf-8'),
tweet.in_reply_to_status_id_str] for tweet in tweets]
tweets_df = pd.DataFrame(tweets_list,columns=['Datetime', 'Tweet Id', 'Text', 'Reply_ID'])
tweets_df2 = tweets_df[tweets_df['Reply_ID'] == tweet_id]
I'm using 'to:'+name to find replies to a specific user and tweets_df['Reply_ID'] == tweet_id to match the replies. However, the result of the initial data frame tweets_df before filtering the tweet ID only gives the reply tweets within a month.
How can I get more replies starting from the 25-Jan?
The legacy standard Twitter search API - which is what this Tweepy function is using - can only provide Tweets going back within the past 7 days. For a longer period, you need to use the premium 30-day or full-archive search APIs from Twitter.

Obtain tweets with hashtags in them - Teepy

I have a basic program working using the Tweepy API. It essentially grabs tweets from a user and outputs it to a terminal. Ideally, I'd like this to be automated, so when the user tweets, the program will see it and display the tweet. But that's a question for another time.
What I'd like to do now, however, is grab the tweets with only a hashtag in it.
How do I go about this? I'm hoping it's a parameter I can add with inside the timeline function..?
Here is a snippet of the code I have at the moment:
import tweepy
import twitter_credentials
auth = tweepy.OAuthHandler(twitter_credentials.CONSUMER_KEY, twitter_credentials.CONSUMER_SECRET)
auth.set_access_token(twitter_credentials.ACCESS_TOKEN, twitter_credentials.ACCESS_TOKEN_SECRET)
api = tweepy.API(auth)
stuff = api.user_timeline(screen_name = 'XXXXXX', count = 10, include_rts = False)
for status in stuff:
print(status.text)
For a simple use case you can use # in the search string, for example:
api = tweepy.API(auth,wait_on_rate_limit=True)
tweet in tweepy.Cursor(api.search,q="#",count=100).items():
print(tweet)
This will give you tweets which contain any hastags.

Replying to users who tweet my account using Tweepy

I want to reply to users who tweet me a specific keyword (only when they tweet me) using Tweepy but I'm not sure how to go on about it, most of the examples I've seen use api.search which isn't convenient in this situation:
def tweetIt():
text = tweet.status
sn = tweet.user.screen_name
reply_to = tweet.in_reply_to_screen_name
if reply_to == "myuser":
if text == "#myuser keyword":
# reply to user with an image from a specific folder
tweetIt()
time.sleep(90) # to keep it running

Get usernames for a retweet?

How can I view the usernames for each retweet from my timeline using Python-Twitter? Here is what I have so far which brings back the timeline without the re-tweet usernames:
import twitter
api = twitter.Api(xxxxxx)
statuses = api.GetUserTimeline('username', include_rts=True)
for tweet in statuses:
print tweet
The method that I think you would use is GetTweets which requires a statusID, I am not sure how you would pass the status ID from the timeline call to the GetRetweets call?
Thanks in advance!
Try this:
import twitter
t = twitter.Api(...)
statuses = t.GetUserTimeline('username', include_rts=True)
for tweet in statuses:
retweets = t.GetRetweets(tweet.GetId())
users = [retweet.GetUser().GetScreenName() for retweet in retweets]
print tweet.GetId(), users
Hope that helps.
I wanted to add to #alecxe's answer but with a comment I can't paste much code. In my application I found it useful to check if the tweet had retweets prior to getting those retweets. This saves a little when it comes to the API quota. I've modified #alecxe's code to fit my needs:
import twitter, json
t = twitter.Api(...)
statuses = t.GetUserTimeline('username', include_rts=True)
for tweet in statuses:
json_tweet = json.loads(str(tweet))
rts = 0
try:
rts = json_tweet['retweet_count']
except:
rts = 0
if rts > 0:
retweets = t.GetRetweets(tweet.GetId())
users = [retweet.GetUser().GetScreenName() for retweet in retweets]
print tweet.GetId(), users
Or you can try this too.
import twitter
t = twitter.Api(...)
statuses = t.GetUserTimeline('username', include_rts=True)
for tweet in statuses:
retweets = t.GetRetweets(tweet.GetId())
users = [retweet.GetUser().GetScreenName() for retweet in retweets]
print tweet.GetId(), users
print tweet.GetRetweets()

Categories

Resources