twikit icon indicating copy to clipboard operation
twikit copied to clipboard

How can I prioritize fetching the most recent tweets first

Open yuhai5237 opened this issue 1 year ago • 3 comments

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?

yuhai5237 avatar Oct 24 '24 08:10 yuhai5237

You can't, just fetch certain amount and manually check them.

Davis-3450 avatar Oct 25 '24 23:10 Davis-3450

@yuhai5237 Not Found Sorry, the page or file you tried to access was not found.

szsyzx avatar Nov 01 '24 14:11 szsyzx

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())

iukea1 avatar Jan 02 '25 09:01 iukea1