How can I prioritize fetching the most recent tweets first
I am using user_tweets = await client.get_user_tweets('XXXXX') to retrieve tweet information, but it returns older tweets first. I would like to prioritize returning the most recently created tweets. How can I achieve this?
You can't, just fetch certain amount and manually check them.
@yuhai5237 Not Found Sorry, the page or file you tried to access was not found.
I am using user_tweets = await client.get_user_tweets('XXXXX') to retrieve tweet information, but it returns older tweets first. I would like to prioritize returning the most recently created tweets. How can I achieve this?
Maybe this will help (I'm shooting in the dark a little bit here)
import asyncio
from typing import Optional
from twikit import Client, Tweet
AUTH_INFO_1 = '...'
AUTH_INFO_2 = '...'
PASSWORD = '...'
# Initialize the client with authentication
client = Client(auth1=AUTH_INFO_1, auth2=AUTH_INFO_2, password=PASSWORD)
USER_ID = '44196397'
CHECK_INTERVAL = 60 * 5 # 5 minutes in seconds
def callback(tweet: Tweet) -> None:
print(f'New tweet posted: {tweet.text}')
async def get_latest_tweet() -> Optional[Tweet]:
try:
tweets = await client.get_user_tweets(USER_ID, 'Replies')
return tweets[0] if tweets else None
except Exception as e:
print(f"Error fetching tweets: {e}")
return None
async def main() -> None:
before_tweet = await get_latest_tweet()
while True:
await asyncio.sleep(CHECK_INTERVAL)
latest_tweet = await get_latest_tweet()
if (
latest_tweet
and before_tweet
and before_tweet != latest_tweet
and before_tweet.created_at_datetime < latest_tweet.created_at_datetime
):
callback(latest_tweet)
if latest_tweet:
before_tweet = latest_tweet
if __name__ == "__main__":
asyncio.run(main())