Twikit Documentation

repository·main·Indexed 26 days ago

https://github.com/d60/twikit

Twikit is a Python library and Twitter API scraper that enables actions such as posting tweets, searching, and retrieving trends without an official API key. It features an asynchronous Client for authentication, session management via cookies, and a streaming API for real-time events like tweet engagements and DM updates. The library supports media uploads (Photo, Video, AnimatedGif), poll creation and voting, and provides core modules for interacting with users, messages, communities, and notifications.

Tokens
8.7K
Snippets
33
Records
50
Agent score
86%

What's inside twikit

  1. Initialize and log in to a Twikit Client

    main

    To use Twikit, you must initialize a Client with a locale (e.g., 'en-US') and log in using account credentials. It is recommended to use a cookies_file to manage session persistence.

    Note: The login method is asynchronous.

    import asyncio
    from twikit import Client
    
    USERNAME = 'example_user'
    EMAIL = 'email@example.com'
    PASSWORD = 'password0000'
    
    # Initialize client
    client = Client('en-US')
    
    async def main():
        await client.login(
            auth_info_1=USERNAME,
            auth_info_2=EMAIL,
            password=PASSWORD,
            cookies_file='cookies.json'
        )
    
    asyncio.run(main())
  2. Avoid account bans by following safety practices

    main

    Because Twikit uses an unofficial API, you must follow these safety guidelines to prevent your account from being banned:

    • Avoid excessive requests: Do not send consecutive requests without cooldowns. Avoid hitting rate limits.
    • Reuse login information: Use save_cookies and load_cookies instead of calling login repeatedly.
    • Limit messaging: Refrain from sending an excessive number of direct messages.
    • Avoid sensitive content: Do not tweet content related to sexuality, violence, politics, discrimination, or hate speech, as this violates Twitter's terms of service.
  3. Reuse login information using cookies

    main

    To avoid being flagged for suspicious behavior, do not repeatedly call the login method. Instead, log in once and use save_cookies to store your session, then use load_cookies in subsequent sessions to restore it. This reduces the number of login requests sent to Twitter.

    # Initial login
    client.login(
        auth_info_1='...',
        auth_info_2='...',
        password='...'
    )
    
    # Save the session to a file
    client.save_cookies('cookies.json')
    
    # In future sessions, load the session instead of logging in
    client.load_cookies('cookies.json')
  4. Initialize and login with Twikit Client

    main

    To use Twikit, initialize a Client instance with a language code (e.g., 'en-US') and use the login method to authenticate. The login method requires auth_info_1 (username), auth_info_2 (email), and password.

    import asyncio
    from twikit import Client
    
    USERNAME = 'example_user'
    EMAIL = 'email@example.com'
    PASSWORD = 'password0000'
    
    # Initialize client
    client = Client('en-US')
    
    async def main():
        await client.login(
            auth_info_1=USERNAME ,
            auth_info_2=EMAIL,
            password=PASSWORD
        )
    
    asyncio.run(main())
  5. Initialize the Twikit Client and Login

    main

    To use Twikit, initialize a Client instance with a locale (e.g., 'en-US') and use the login method with your account credentials. The login method requires auth_info_1 (username), auth_info_2 (email), and password.

    import asyncio
    from twikit import Client
    
    USERNAME = 'example_user'
    EMAIL = 'email@example.com'
    PASSWORD = 'password0000'
    
    # Initialize client
    client = Client('en-US')
    
    async def main():
        # Login to account
        await client.login(
            auth_info_1=USERNAME ,
            auth_info_2=EMAIL,
            password=PASSWORD
        )
    
    asyncio.run(main())
  6. Use the Streaming API for real-time events

    main

    The streaming API allows you to receive real-time events such as tweet engagements, DM updates, and DM typings.

    To use it:

    1. Define a set of Topic objects using twikit.streaming.Topic.
    2. Obtain a stream session by calling Client.get_streaming_session(topics).
    3. Iterate through the session to receive (topic, payload) pairs.
    4. Check the payload for specific event types (e.g., payload.dm_update, payload.dm_typing, or payload.tweet_engagement) to process the data.

    You can update the topics being streamed during an active session using StreamingSession.update_subscriptions.

    from twikit.streaming import Topic
    
    topics = {
        Topic.tweet_engagement('1739617652'), # Stream tweet engagement
        Topic.dm_update('17544932482-174455537996'), # Stream DM update
        Topic.dm_typing('17544932482-174455537996') # Stream DM typing
    }
    session = client.get_streaming_session(topics)
    
    for topic, payload in session:
        if payload.dm_update:
            conversation_id = payload.dm_update.conversation_id
            user_id = payload.dm_update.user_id
            print(f'{conversation_id}: {user_id} sent a message')
    
        if payload.dm_typing:
            conversation_id = payload.dm_typing.conversation_id
            user_id = payload.dm_typing.user_id
            print(f'{conversation_id}: {user_id} is typing')
    
        if payload.tweet_engagement:
            like = payload.tweet_engagement.like_count
            retweet = payload.tweet_engagement.retweet_count
            view = payload.tweet_engagement.view_count
            print(f'Tweet engagement updated likes: {like} retweets: {retweet} views: {view}')
  7. Use the Streaming API with StreamingSession

    main

    Twikit supports real-time event streaming via get_streaming_session(topics, auto_reconnect).

    1. Define a set of Topic objects (e.g., Topic.tweet_engagement(id), Topic.dm_update(id), Topic.dm_typing(id)).
    2. Call await client.get_streaming_session(topics) to get a StreamingSession.
    3. Iterate over the session asynchronously to receive (topic, payload) tuples.
    4. Use session.update_subscriptions(subscribe_topics, unsubscribe_topics) to dynamically change what you are listening to.
    from twikit.streaming import Topic
    
    topics = {
        Topic.tweet_engagement('1739617652'), # Stream tweet engagement
        Topic.dm_update('17544932482-174455537996'), # Stream DM update
        Topic.dm_typing('17544932482-174455537996') # Stream DM typing
    }
    
    session = await client.get_streaming_session(topics)
    
    async for topic, payload in session:
        if payload.dm_update:
            conversation_id = payload.dm_update.conversation_id
            user_id = payload.dm_update.user_id
            print(f'{conversation_id}: {user_id} sent a message')
        if payload.dm_typing:
            print(f'User is typing in {payload.dm_typing.conversation_id}')
        if payload.tweet_engagement:
            print(f'Likes: {payload.tweet_engagement.like_count}')
  8. Initialize and activate GuestClient

    main

    The GuestClient allows you to interact with the Twitter API without authentication. You must call activate() to generate a guest token before making most requests.

    Parameters:

    • language (str, default='en-US'): The language code for API requests.
    • proxy (str, optional): The proxy server URL (e.g., 'http://0.0.0.0:0000').
    • **kwargs: Additional arguments passed to httpx.AsyncClient.
  9. Search tweets by keyword

    main

    Use search_tweet to find tweets based on a keyword and a category (e.g., 'Latest').

    tweets = await client.search_tweet('python', 'Latest')
    
    for tweet in tweets:
        print(
            tweet.user.name,
            tweet.text,
            tweet.created_at
        )