Skip to main content

Quickstart

This guide will help you make your first Twitter API calls with Twikit. By the end, you’ll have a working script that authenticates with Twitter and searches for tweets.
This guide assumes you’ve already installed Twikit. If not, install it first with pip install twikit.

Your first Twikit script

Let’s create a simple script that logs in to Twitter and searches for tweets.
1

Create your script file

Create a new Python file called twitter_bot.py:
touch twitter_bot.py
2

Import Twikit and set up credentials

Open twitter_bot.py and add your imports and credentials:
import asyncio
from twikit import Client

# Your Twitter account credentials
USERNAME = 'your_username'
EMAIL = '[email protected]'
PASSWORD = 'your_password'
Never commit your credentials to version control. Use environment variables or a secure configuration file for production applications.
3

Initialize the client

Create a Twikit client instance with your preferred language:
# Initialize client
client = Client('en-US')
The language parameter affects the language of content returned by Twitter’s API.
4

Create an async main function

Twikit is fully asynchronous, so you need to use async/await syntax:
async def main():
    # Login to Twitter
    await client.login(
        auth_info_1=USERNAME,
        auth_info_2=EMAIL,
        password=PASSWORD
    )
    
    print('Logged in successfully!')
    
    # Search for tweets
    tweets = await client.search_tweet('python', 'Latest')
    
    # Print the first 5 tweets
    for tweet in tweets[:5]:
        print(f'{tweet.user.name}: {tweet.text}')
        print(f'Likes: {tweet.favorite_count} | Retweets: {tweet.retweet_count}')
        print('-' * 50)
5

Run the async function

Add the entry point to run your async function:
if __name__ == '__main__':
    asyncio.run(main())
6

Run your script

Execute your script:
python twitter_bot.py
You should see your script log in and display recent tweets about Python!

Complete example

Here’s the full script in one place:
twitter_bot.py
import asyncio
from twikit import Client

# Your Twitter account credentials
USERNAME = 'your_username'
EMAIL = '[email protected]'
PASSWORD = 'your_password'

# Initialize client
client = Client('en-US')

async def main():
    # Login to Twitter
    await client.login(
        auth_info_1=USERNAME,
        auth_info_2=EMAIL,
        password=PASSWORD
    )
    
    print('Logged in successfully!')
    
    # Search for tweets
    tweets = await client.search_tweet('python', 'Latest')
    
    # Print the first 5 tweets
    for tweet in tweets[:5]:
        print(f'{tweet.user.name}: {tweet.text}')
        print(f'Likes: {tweet.favorite_count} | Retweets: {tweet.retweet_count}')
        print('-' * 50)

if __name__ == '__main__':
    asyncio.run(main())

Understanding async/await

Twikit is built with asynchronous Python, which means all client methods are coroutines that must be called with await.
# Correct: Using await with async methods
tweets = await client.search_tweet('python', 'Latest')
user = await client.get_user_by_screen_name('example_user')
If you’re new to async Python, the key rules are:
  1. Mark your function with async def
  2. Use await when calling async methods
  3. Run your async function with asyncio.run()

Common operations

Here are some common operations you can perform with Twikit:

Get a user’s profile

user = await client.get_user_by_screen_name('elonmusk')
print(f'Name: {user.name}')
print(f'Followers: {user.followers_count}')
print(f'Bio: {user.description}')

Create a tweet

await client.create_tweet(
    text='Hello from Twikit! 🚀'
)

Get user tweets

user = await client.get_user_by_screen_name('example_user')
tweets = await client.get_user_tweets(user.id, 'Tweets')

for tweet in tweets:
    print(tweet.text)

Like and retweet

tweet = await client.get_tweet_by_id('1234567890')
await tweet.favorite()  # Like the tweet
await tweet.retweet()   # Retweet it

Pagination

Many methods return paginated results. Use the next() method to fetch more:
# Get first page of tweets
tweets = await client.search_tweet('python', 'Latest')

for tweet in tweets:
    print(tweet.text)

# Get next page
more_tweets = await tweets.next()

for tweet in more_tweets:
    print(tweet.text)

Best practices for testing

Be careful when testing! Avoid:
  • Posting too many tweets in a short time
  • Following/unfollowing many users rapidly
  • Sending excessive DMs
  • Logging in repeatedly
These actions can trigger Twitter’s anti-spam measures and get your account suspended.

Use cookies to avoid repeated logins

Instead of logging in every time you run your script, save and reuse cookies:
async def main():
    # Login and save cookies
    await client.login(
        auth_info_1=USERNAME,
        auth_info_2=EMAIL,
        password=PASSWORD,
        cookies_file='cookies.json'  # Auto-saves cookies
    )
    
    # On subsequent runs, cookies are loaded automatically
    # if the file exists, skipping the login process
Learn more about cookie management in the Authentication guide.

Rate limits

Twitter enforces rate limits on various operations. Most limits reset every 15 minutes.
  • Search tweets: 50 requests per 15 minutes
  • Get user tweets: 50 requests per 15 minutes
  • Get user info: 95-500 requests per 15 minutes (varies by endpoint)
  • Follow user: 15 requests per 15 minutes
  • Get trends: 20,000 requests per 15 minutes
See the full rate limits table for details.
Implement delays between requests to stay under rate limits:
import asyncio

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

Error handling

Always handle potential errors in your Twikit applications:
from twikit import TooManyRequests, Unauthorized

async def main():
    try:
        await client.login(
            auth_info_1=USERNAME,
            auth_info_2=EMAIL,
            password=PASSWORD
        )
        
        tweets = await client.search_tweet('python', 'Latest')
        
    except Unauthorized:
        print('Login failed. Check your credentials.')
    except TooManyRequests:
        print('Rate limited. Wait before trying again.')
    except Exception as e:
        print(f'An error occurred: {e}')

Next steps

Now that you’ve made your first Twikit script, explore these topics:

Authentication

Learn about secure authentication and cookie management

API Reference

Explore all available methods and their parameters

Examples

Browse example scripts for common use cases

Join Discord

Get help and connect with the Twikit community

Build docs developers (and LLMs) love