Skip to main content

Authentication

Twikit uses your regular Twitter account credentials for authentication—no API keys required. This guide covers how to log in securely, manage sessions with cookies, and protect your account from suspension.

How authentication works

Unlike the official Twitter API that uses OAuth and API keys, Twikit authenticates by simulating a browser login. You provide your regular Twitter username/email and password, and Twikit handles the authentication flow behind the scenes.
Twikit uses unofficial authentication methods. While this eliminates the need for API approval, it requires careful usage to avoid account restrictions.

Basic login

The login() method authenticates your client with Twitter:
import asyncio
from twikit import Client

USERNAME = 'example_user'
EMAIL = '[email protected]'
PASSWORD = 'your_password'

client = Client('en-US')

async def main():
    await client.login(
        auth_info_1=USERNAME,
        auth_info_2=EMAIL,
        password=PASSWORD
    )
    
    print('Successfully logged in!')

asyncio.run(main())

Authentication parameters

auth_info_1
str
required
The first piece of authentication information. Can be your username, email address, or phone number.
auth_info_2
str
The second piece of authentication information (optional but recommended). Can be your username, email address, or phone number. Providing this reduces the chance of authentication challenges.
password
str
required
Your Twitter account password.
totp_secret
str
Your TOTP secret key for two-factor authentication. See Two-factor authentication below.
cookies_file
str
File path for automatic cookie loading and saving. If the file exists, cookies are loaded instead of logging in. After successful login, cookies are automatically saved to this file.
enable_ui_metrics
bool
default:"True"
Whether to execute obfuscated UI metrics using js2py. Enabling this may reduce the risk of account suspension by mimicking browser behavior more closely.
Logging in repeatedly can trigger Twitter’s anti-spam detection. The solution is to save your session cookies and reuse them.
Avoid repeated logins! Logging in frequently is one of the most suspicious behaviors and can lead to account suspension. Always use cookie persistence.
The simplest approach is to use the cookies_file parameter:
await client.login(
    auth_info_1=USERNAME,
    auth_info_2=EMAIL,
    password=PASSWORD,
    cookies_file='cookies.json'
)
With this approach:
  • On the first run, Twikit performs a full login and saves cookies to cookies.json
  • On subsequent runs, Twikit loads cookies from the file and skips the login process
  • The login flow only runs if the file doesn’t exist or cookies are invalid
For more control, you can manually save and load cookies:
1

First login: Save cookies

After your initial login, save the cookies:
async def main():
    # First time: perform full login
    await client.login(
        auth_info_1=USERNAME,
        auth_info_2=EMAIL,
        password=PASSWORD
    )
    
    # Save cookies for future use
    client.save_cookies('cookies.json')
    print('Cookies saved!')
2

Subsequent runs: Load cookies

On later runs, load the saved cookies instead of logging in:
async def main():
    # Load saved cookies
    client.load_cookies('cookies.json')
    
    # You're now authenticated without logging in
    tweets = await client.search_tweet('python', 'Latest')
# Save current session cookies to a file
client.save_cookies('cookies.json')
Cookies contain your authentication session and should be treated like passwords:
  • Never commit cookies to version control
  • Never share cookie files with others
  • Store securely using file permissions or encryption
  • Regenerate regularly by logging in again periodically
Add cookies to your .gitignore:
.gitignore
# Twitter cookies
cookies.json
*.cookies.json

Two-factor authentication

If you have two-factor authentication (2FA) enabled on your Twitter account, you need to provide your TOTP secret.

Getting your TOTP secret

1

Access Twitter security settings

Go to your Twitter account settings and navigate to Security and account access > Security > Two-factor authentication.
2

Set up authenticator app

If not already enabled, enable the Authentication app method. Twitter will show you a QR code.
3

Reveal the secret key

Instead of scanning the QR code, click Can’t scan the QR code? or Enter code manually to reveal the text secret key.Copy this key—it’s your TOTP secret.

Using TOTP with Twikit

Provide your TOTP secret to the login() method:
await client.login(
    auth_info_1=USERNAME,
    auth_info_2=EMAIL,
    password=PASSWORD,
    totp_secret='JBSWY3DPEHPK3PXP'  # Your TOTP secret
)
Twikit will automatically generate the time-based one-time password when needed.
Store your TOTP secret securely, just like your password. Consider using environment variables:
import os

TOTP_SECRET = os.getenv('TWITTER_TOTP_SECRET')

Protecting your account

Because Twikit uses unofficial authentication methods, improper usage can result in account suspension. Follow these guidelines to minimize risk.

Avoid excessive requests

Sending too many requests in a short period is suspicious behavior. Twitter monitors request patterns and enforces rate limits.
Key principle: Never send so many requests that you hit Twitter’s rate limits. Hitting rate limits signals aggressive automation.
Best practices:
  • Implement delays between requests (1-3 seconds minimum)
  • Respect rate limits (see rate limits table)
  • Don’t run multiple scripts simultaneously on the same account
  • Use exponential backoff when you encounter rate limit errors
Example with delays:
import asyncio

# Search multiple queries with delays
queries = ['python', 'javascript', 'rust']

for query in queries:
    tweets = await client.search_tweet(query, 'Latest')
    # Process tweets...
    
    # Wait between requests
    await asyncio.sleep(2)

Reuse login sessions

Logging in is heavily monitored by Twitter. Repeated logins are extremely suspicious.
Never call login() repeatedly in a short period. Use cookie persistence to maintain your session across script runs.
# Run this once
await client.login(
    auth_info_1=USERNAME,
    auth_info_2=EMAIL,
    password=PASSWORD,
    cookies_file='cookies.json'
)

# On subsequent runs, cookies auto-load
# No login needed!

Avoid excessive messaging

Twitter monitors direct messages carefully to prevent spam.
  • Don’t send many DMs in rapid succession
  • Avoid sending identical or similar messages to multiple users
  • Don’t send unsolicited messages to users who haven’t interacted with you
  • Implement longer delays between DMs (30-60 seconds or more)

Content restrictions

Avoid tweeting content that violates Twitter’s terms of service:
  • Sexual content
  • Violence or graphic content
  • Political extremism
  • Hate speech or discrimination
  • Spam or scams
  • Impersonation
These restrictions apply whether you’re using Twikit or tweeting manually. However, automated violations may be detected more quickly.

Account safety checklist

Use this checklist to ensure you’re using Twikit safely:
  • ✅ Using cookie persistence (cookies_file or manual save/load)
  • ✅ Not logging in more than once per session
  • ✅ Storing credentials securely (environment variables, not hardcoded)
  • ✅ Using 2FA with TOTP secret if enabled
  • ✅ Implementing delays between requests (minimum 1-3 seconds)
  • ✅ Respecting rate limits
  • ✅ Using exponential backoff for rate limit errors
  • ✅ Not running multiple scripts on the same account simultaneously
  • ✅ Not posting spam or repetitive content
  • ✅ Avoiding restricted content (sexual, violent, hateful, etc.)
  • ✅ Not sending excessive DMs
  • ✅ Following Twitter’s terms of service
  • ✅ Cookies file in .gitignore
  • ✅ Using environment variables for sensitive data
  • ✅ Secure file permissions on cookie files
  • ✅ Regular cookie regeneration (weekly or monthly)

Handling authentication errors

Common authentication issues and solutions:

Unauthorized error

from twikit import Unauthorized

try:
    await client.login(
        auth_info_1=USERNAME,
        auth_info_2=EMAIL,
        password=PASSWORD
    )
except Unauthorized:
    print('Login failed. Check your credentials.')
Causes:
  • Incorrect username, email, or password
  • 2FA enabled but no TOTP secret provided
  • Account locked or suspended
  • Too many failed login attempts

Account locked

from twikit import AccountLocked

try:
    await client.login(...)
except AccountLocked:
    print('Account is locked. Check your email for instructions from Twitter.')
If your account is locked, Twitter will send instructions to your email. You may need to verify your identity or change your password.

Cookies expired

Cookies eventually expire. If you get authentication errors after loading cookies, delete the cookie file and log in again:
import os

try:
    client.load_cookies('cookies.json')
    # Try to use the client...
    tweets = await client.search_tweet('test', 'Latest')
except Exception:
    # Cookies may be invalid
    os.remove('cookies.json')
    
    # Login fresh
    await client.login(
        auth_info_1=USERNAME,
        auth_info_2=EMAIL,
        password=PASSWORD,
        cookies_file='cookies.json'
    )

Best practices summary

Use cookie persistence

Always save and reuse cookies to avoid repeated logins

Implement delays

Add 1-3 second delays between API requests

Respect rate limits

Monitor and stay well under Twitter’s rate limits

Secure your credentials

Use environment variables and never commit secrets

Next steps

API Reference

Explore all available methods and their authentication requirements

Build docs developers (and LLMs) love