Im trying to get the last tweet froom a twitter account using tweepy in python.
I know there are a few similiar answers for example this one Get the last tweet with tweepy
However the issue that I have is that i dont get the last tweet from a persons timeline but the second last tweet.
Im using this code here in a while loop:
tweetL = api.user_timeline(screen_name='elonmusk', tweet_mode="extended", exclude_replies, count=1) print(tweetL[0].full_text)
If i run this(at time of the writing), i get this tweet from elon:
What a beautiful day in LA
however looking at his timeline the last tweet from him was this:
Warm, sunny day & snowy mountains
So why am i not getting the last tweet? Strangely enough running this script last night it did print out his last tweet. running it now I get the same tweet, it printed out yesterday as the last tweet
and if I run the above code like this (without ‘exclude_replies’)
tweetL = api.user_timeline(screen_name='elonmusk', tweet_mode="extended") print(tweetL[0].full_text)
i get as his last tweet
@ErcXspace @smvllstvrs T/W will be ~1.5, so it will accelerate unusually fast. High T/W is important for reusable vehicles to make more efficient use of propellant, the primary cost. For expendable rockets, throwing away stages is the primary cost, so optimization is low T/W.
which was his last reply, so this works.
I just cant fetch the last actual tweet from his timeline
Advertisement
Answer
As Iain Shelvington mentioned in the comments, exclude_replies
will also ignore replies to oneself.
I don’t think there’s a direct way of getting a user’s last tweet in their timeline. You could create a function that from the retrieved tweets, gets the first one that:
a) is not a reply, i.e., in_reply_to_screen_name = None
.
b) or replies to themselves, i.e., in_reply_to_screen_name = screen_name
.
This could look something like:
def get_last_timeline_tweet(screen_name: str, tweets: list): for tw in tweets: if (tw.in_reply_to_screen_name is None or tw.in_reply_to_screen_name == screen_name): return tw return None
Then, running:
last_timeline_tweet = get_last_timeline_tweet('elonmusk', tweetL).full_text print(last_timeline_tweet)
You get:
Warm, sunny day & snowy mountains [url to the photo]
This can also be done in a one-liner with:
screen_name = 'elonmusk' last_tweet = next((tw for tw in tweetL if tw.in_reply_to_screen_name is None or tw.in_reply_to_screen_name == screen_name), None) print(last_tweet.full_text)
Note: it should be checked that last_tweet
is not None
before getting its full_text
.