Skip to main content
The Client class is the main interface for interacting with Twitter’s API. It handles authentication, request management, and provides access to all Twitter API operations.

Client initialization

Create a client instance with optional configuration parameters:
from twikit import Client

client = Client(
    language='en-US',
    proxy='http://proxy.example.com:8080',
    user_agent='Custom User Agent String'
)

Parameters

language
str
default:"en-US"
The language code to use in API requests. This affects the language of content returned by the API.
proxy
str
default:"None"
The proxy server URL to use for requests (e.g., 'http://0.0.0.0:8080'). Useful for routing traffic through a proxy.
captcha_solver
Capsolver
default:"None"
A Capsolver instance for handling CAPTCHA challenges during account unlock operations.
user_agent
str
default:"None"
Custom user agent string for HTTP requests. If not specified, uses a default browser user agent.

Authentication

Log in to Twitter with your account credentials:
await client.login(
    auth_info_1='example_user',
    auth_info_2='[email protected]',
    password='your_password'
)
The auth_info_1 and auth_info_2 parameters can be a username, email address, or phone number. The order is flexible, and auth_info_2 is optional but recommended.

Two-factor authentication

If you have 2FA enabled, provide your TOTP secret:
await client.login(
    auth_info_1='example_user',
    auth_info_2='[email protected]',
    password='your_password',
    totp_secret='YOUR_TOTP_SECRET_KEY'
)
Save and load cookies to avoid repeated logins:

Save cookies

# Save cookies after login
await client.login(
    auth_info_1='example_user',
    password='your_password',
    cookies_file='cookies.json'
)

# Or save manually
client.save_cookies('cookies.json')

Load cookies

# Load from file
client.load_cookies('cookies.json')

# Or load manually from dict
import json
with open('cookies.json', 'r') as f:
    client.set_cookies(json.load(f))

Get cookies programmatically

cookies = client.get_cookies()
print(cookies)
# {'auth_token': '...', 'ct0': '...', ...}
Store cookies securely and reuse them to skip the login process. If a cookies file is provided to login() and exists, the login will be skipped entirely.

Proxy configuration

You can set or update the proxy at any time:
# Set proxy during initialization
client = Client(proxy='http://proxy.example.com:8080')

# Or update it later
client.proxy = 'http://another-proxy.com:3128'

# Check current proxy
print(client.proxy)

Client vs GuestClient

Twikit provides two client types:

Client

  • Requires authentication: Must log in with Twitter credentials
  • Full API access: Can post tweets, send DMs, follow users, and more
  • Rate limits: Higher limits for most operations
  • Use case: Building bots, automation, or apps that need to perform actions
from twikit import Client

client = Client('en-US')
await client.login(
    auth_info_1='username',
    password='password'
)

# Full access to API operations
await client.create_tweet('Hello, world!')

GuestClient

  • No authentication required: Works without login
  • Read-only access: Can only retrieve public data (tweets, users)
  • Lower rate limits: More restricted than authenticated client
  • Use case: Reading public data without needing an account
from twikit.guest import GuestClient

guest = GuestClient('en-US')
await guest.activate()  # Generate guest token

# Read-only operations
user = await guest.get_user_by_screen_name('elonmusk')
tweet = await guest.get_tweet_by_id('1234567890')
GuestClient cannot perform actions like tweeting, following, or sending DMs. Use the regular Client for these operations.

Common patterns

Reusable authenticated session

import asyncio
from twikit import Client

client = Client('en-US')

async def setup_client():
    """Initialize client with saved cookies or login."""
    try:
        client.load_cookies('cookies.json')
        print('Loaded cookies from file')
    except FileNotFoundError:
        await client.login(
            auth_info_1='username',
            password='password'
        )
        client.save_cookies('cookies.json')
        print('Logged in and saved cookies')

async def main():
    await setup_client()
    
    # Now use the client for API operations
    user = await client.user()
    print(f'Logged in as: {user.name}')

asyncio.run(main())

Using proxies for multiple accounts

async def create_client_with_proxy(proxy_url, cookies_file):
    """Create a client instance with a specific proxy."""
    client = Client(proxy=proxy_url)
    client.load_cookies(cookies_file)
    return client

# Manage multiple accounts with different proxies
client1 = await create_client_with_proxy(
    'http://proxy1.com:8080',
    'account1_cookies.json'
)
client2 = await create_client_with_proxy(
    'http://proxy2.com:8080',
    'account2_cookies.json'
)

Delegate account access

Set an account to act as (for authorized delegate access):
# Act as another user account
client.set_delegate_account('1234567890')  # user_id

# Make requests as the delegated account
await client.create_tweet('Posting as delegate')

# Clear delegation
client.set_delegate_account(None)

Getting user information

Retrieve information about the authenticated account:
# Get user ID
user_id = await client.user_id()

# Get full user object
user = await client.user()
print(f'Name: {user.name}')
print(f'Followers: {user.followers_count}')
print(f'Bio: {user.description}')

Error handling

Handle exceptions and API errors

Rate limits

Understand rate limits and quotas

Build docs developers (and LLMs) love