tweety

repository·main·Indexed 20 days ago

https://github.com/mahrtayyab/tweety

A reverse-engineered Python library for interacting with the Twitter (X) frontend API. It provides the TwitterAsync class for asynchronous tasks such as fetching tweets, retrieving user information, searching keywords, managing direct messages, and automating interactions like liking, retweeting, and following users.

Tokens
28.1K
Snippets
123
Records
151
Agent score
64%

What's inside tweety

  1. Understand JSON Serializable and Iterable Data Classes

    main

    Many data classes in tweety are both JSON Serializable and Iterable. This means you can iterate over them directly (e.g., in a for loop) and convert them to JSON format for storage or API responses.

    Supported classes include:

    • UserMedia
    • SelfTimeline
    • TweetHistory
    • ScheduledTweets
    • TweetComments
    • Search
    • TopicTweets
    • TweetLikes
    • TweetRetweets
    • Mention
    • Bookmarks
    • CommunityTweets
    • CommunityMembers
    • Lists
    • ListMembers
    • ListTweets
    • UserFollowers
    • UserFollowings
    • UserSubscribers
    • MutualFollowers
    • BlockedUsers
  2. Conversation update event types

    main

    When retrieving message pages, you may encounter several update event types that describe changes to the conversation state:

    • MessageParticipantUpdate: Indicates a user has joined (JOIN) or left (LEAVE) the conversation. Includes sender_id and the sender (User).
    • MessageNameUpdate: Indicates the conversation name was changed. Includes the new name, by_user_id, and by_user (User).
    • MessageConversationCreated: Indicates the conversation was created. Includes the id and time.
    • MessageConversationAvatarUpdate: Indicates the conversation avatar was changed. Includes conversation_id and the new avatar_url.
  3. Understand the BaseGeneratorClass for pagination

    main

    The BaseGeneratorClass is the base class for all generator classes in the library. It is designed to handle paginated data (like lists of tweets or users) and is both JSON serializable and iterable.

    Attributes:

    • cursor (str): The cursor for the next page.
    • is_next_page (bool): Indicates if a next page of data is available.
    • cursor_top (str): The cursor for the previous page.

    Async Methods:

    • get_page(cursor: str): Fetches a specific page of data using the provided cursor. Returns a tuple containing the list of items (e.g., Tweet, User, etc.), the next cursor, and the top cursor.
    • get_next_page(): Fetches the next page of data using the internally saved cursor, if available.
    # Example conceptual usage of a generator
    async for item in generator:
        print(item)
    
    # Or manually fetching pages
    items, next_cursor, top_cursor = await generator.get_page(cursor="some_cursor")
  4. Get List Tweets and Members

    main

    Interact with the content and membership of specific Twitter Lists.

    Get Tweets from a List

    Retrieve tweets within a specific list using get_list_tweets or iter_list_tweets.

    tweets = await app.get_list_tweets("123515")
    for tweet in tweets:
        print(tweet)

    Get List Members

    Retrieve the users belonging to a specific list using get_list_member or iter_list_member.

    users = await app.get_list_member("123515")
    for user in users:
        print(user)

    Add Member to List

    Add a user to a list using add_list_member(list_id, user_id).

    _list = await app.add_list_member("123515", "elonmusk")
    print(_list)
  5. Manage Twitter Lists

    main

    Tweety provides several methods to interact with Twitter Lists for authenticated users.

    Get All Lists

    Retrieve lists belonging to the authenticated user using get_lists or iter_lists.

    lists = await app.get_lists()
    for _list in lists:
        print(_list)

    Create a List

    Create a new list with create_list(name, description="", is_private=False).

    _list = await app.create_list("list_name")
    print(_list)

    Delete a List

    Delete a list using its ID via delete_list(list_id). This requires the authenticated user to be an Admin of the list.

    _list = await app.delete_list("123515")
    print(_list)

    Get a Specific List

    Retrieve details for a single list using get_list(list_id).

    _list = await app.get_list("123515")
    print(_list)
  6. Quick-start with TwitterAsync to fetch user info and tweets

    main

    To interact with Twitter asynchronously, use the TwitterAsync class. You can sign in using credentials and then retrieve user information and their associated tweets.

    Key methods used in this workflow:

    • sign_in(username, password): Authenticates the session.
    • get_user_info(target_username): Returns a User class instance for the specified username.
    • get_tweets(user): Takes a User instance and returns a UserTweets class instance containing the user's tweets.
    from tweety import TwitterAsync
    
    async def main():
        # Initialize with a session name
        app = TwitterAsync("session")
        
        # Sign in with credentials
        await app.sign_in(username, password)
        
        target_username = "elonmusk"
    
        # Retrieve user information (returns a User instance)
        user = await app.get_user_info(target_username)
        
        # Retrieve tweets (returns a UserTweets instance)
        all_tweets = await app.get_tweets(user)
    
        # Iterate over the tweets
        for tweet in all_tweets:
            print(tweet)
  7. Resume a previous session with connect()

    main

    If you have already authenticated and a session file (e.g., session.tw_session) exists in your current directory, you can bypass the login flow by using the connect() method.

    Ensure that the name passed to the Twitter constructor matches the prefix of your existing .tw_session file. If the file is in a different directory, provide the relative path in the constructor.

    from tweety import TwitterAsync
    
    # If 'session.tw_session' exists in the current directory
    app = Twitter("session")
    await app.connect()
    
    print(app.me)
  8. Update tweety to the latest version from GitHub

    main

    Since PyPI (pip) might not always have the most recent fixes, you can ensure you are using the latest version by installing directly from the main branch on GitHub.

    pip install https://github.com/mahrtayyab/tweety/archive/main.zip --upgrade 
  9. Handle Resource Not Found Exceptions

    main

    Tweety raises specific exceptions when the requested Twitter resource (user, tweet, list, or conversation) cannot be located.

    • UserNotFound: The requested user account was not found.
    • InvalidTweetIdentifier: The tweet being queried is invalid or not found.
    • ListNotFound: The requested list was not found.
    • ConversationNotFound: The requested conversation was not found.
  10. Handle Rate Limits and System Errors

    main

    Use these exceptions to manage API limits and unexpected failures:

    • RateLimitReached: You have exceeded the Twitter rate limit. You should implement a delay before retrying.
    • GuestTokenNotFound: The guest token could not be obtained (often affects unauthenticated requests).
    • UnknownError: An error occurred that is unknown to Tweety.
  11. Handle Authentication and Credential Exceptions

    main

    When working with authenticated methods in Tweety, you may encounter exceptions related to your session or credentials. Use these to determine if you need to re-authenticate or update your cookies.

    • AuthenticationRequired: Raised when a method requires an authenticated user but none was provided.
    • InvalidCredentials: Raised when the provided cookies for authentication are invalid.
    • DeniedLogin: Raised when Twitter denies a login request, often due to multiple failed or repeated login attempts.
    • ActionRequired: Raised when an additional step (like a challenge) is required to complete the login process.
    • LockedAccount: Raised when the logged-in account is locked and may require a CAPTCHA check.
    • SuspendedAccount: Raised when the logged-in account has been suspended.
  12. Handle Privacy and Access Exceptions

    main

    If you attempt to access content that is restricted by privacy settings, Tweety will raise one of the following:

    • UserProtected: The user has a private profile. You can typically resolve this by authenticating the request using valid cookies.
    • ProtectedTweet: The specific tweet is private/protected and requires authorization to access.