# X (Twitter) Advanced Search Tweet Scraper 𝕏 (`mikolabs/x-twitter-advanced-search-tweet-scraper`) Actor

Twitter/X scraper is Lightning-fast in 3 sec 20 tweets with 60+ advanced filters. Extract tweets by engagement, media, users, keywords, time, and location. Supports Latest/Top sorting, threads, quotes, and polls. Returns profiles, media URLs, engagement stats, and metadata.

- **URL**: https://apify.com/mikolabs/x-twitter-advanced-search-tweet-scraper.md
- **Developed by:** [Mikolabs](https://apify.com/mikolabs) (community)
- **Categories:** Social media, Developer tools, Lead generation
- **Security:** Limited permissions
- **Stats:** 344 total users, 11 monthly users, 93.1% runs succeeded, 4 bookmarks
- **User rating**: 5.00 out of 5 stars

## Pricing

from $9.99 / 1,000 results

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.
Since this Actor supports Apify Store discounts, the price gets lower the higher subscription plan you have.

Learn more: https://docs.apify.com/actors/running/actors-in-store.md#pay-per-event

## What's an Apify Actor?

An Actor is a serverless cloud program that runs on the Apify platform. It has two run modes.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.

Apify vocabulary and the platform model are defined once, in the agent quickstart at https://apify.com/agents.md.

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.

Do not guess an integration path. Every one of them is in the agent quickstart at https://apify.com/agents.md: the Apify MCP server, Agent Skills with the Apify CLI, the JavaScript and Python clients, the REST API, and the account-free path for an agent with no human to sign in. It also carries the rule on stating cost before the first paid run.

For examples already wired to this Actor's own input schema, see the [API](#api) section below.

Each client library has reference documentation the quickstart does not restate: [JavaScript/TypeScript](https://docs.apify.com/api/client/js/docs.md) (`npm install apify-client`) and [Python](https://docs.apify.com/api/client/python/docs.md) (`pip install apify-client`).

# README

## 🚀 X (Twitter) Advanced Search Actor

**The most powerful and flexible Twitter search solution for Apify** - Unlock the full potential of X (formerly Twitter) data collection with our sophisticated search capabilities and advanced filtering system.

[![Apify](https://img.shields.io/badge/Apify-Actor-blue)](https://apify.com)
[![Python](https://img.shields.io/badge/Python-3.8+-green)](https://python.org)
[![License](https://img.shields.io/badge/License-Apache%202.0-yellow)](LICENSE)

**🌐 Available on Apify Store:** <https://apify.com/mikolabs/x-twitter-advanced-search-tweet-scraper>

**💰 Pricing:** **$20 per 1,000 results** - The most affordable Twitter scraping solution on Apify!

***

### 🌟 What Makes Us Superior?

Our X (Twitter) Advanced Search Actor represents the pinnacle of social media data extraction technology. Unlike basic scrapers that offer limited functionality, we provide:

- ✅ **No Twitter API key required** - Scrapes directly from Twitter
- 🎯 **60+ advanced filters** across 8 comprehensive categories
- 🔍 **Dual search modes** - Simple query or structured advanced filters
- ⚡ **Enterprise-grade reliability** - Built for scalability and performance
- 📊 **Rich metadata extraction** - Complete tweet data with engagement stats
- 🔄 **Smart pagination** - Automatic handling of large datasets
- 🛡️ **Robust error handling** - Comprehensive retry logic and validation

***

### 🎯 Dual Search Modes for Maximum Flexibility

#### Simple Query Mode

Use traditional X search syntax for quick, straightforward searches:

```json
{
  "query": "artificial intelligence OR AI from:elonmusk since:2024-01-01",
  "queryType": "Latest",
  "numberOfTweets": 100
}
```

#### Advanced Filter Mode

Leverage our revolutionary structured filter system for precise, complex data collection:

```json
{
  "query": "AI",
  "queryType": "Top",
  "numberOfTweets": 500,
  "engagementLevel": "high",
  "mediaTypes": ["image", "video"],
  "contentLanguage": "en",
  "timeSince": "2024-01-01",
  "timeUntil": "2024-12-31",
  "usersVerifiedOnly": true,
  "contentKeywords": ["machine learning", "neural networks"],
  "contentHashtags": ["AI", "MachineLearning"],
  "engagementMinLikes": 100,
  "engagementMinRetweets": 10
}
```

> 💡 **Tip**: You can use **either `query` OR advanced filters** — at least one must be provided.

***

### 🔍 Industry-Leading Filter System

Our proprietary filtering technology offers **8 comprehensive filter categories** with **60+ individual filter options**:

#### 1. Content Filters

- **Keywords**: Search for specific words or phrases
- **Exact Phrases**: Match complete quoted phrases
- **Hashtags**: Include/exclude specific hashtags
- **Cashtags**: Stock symbols (e.g., `$TSLA`, `$AAPL`)
- **Language**: Filter by tweet language (26+ languages supported)
- **Emoticons**: Positive (`:) :-) :P :D`) or negative (`:( :-(`) sentiment
- **Question Marks**: Find question-based tweets
- **Exclude Keywords/Hashtags**: Remove unwanted content

#### 2. User Filters

- **From Users**: Tweets from specific accounts (`from:username`)
- **To Users**: Replies to specific users (`to:username`)
- **Mention Users**: Tweets mentioning users (`@username`)
- **Exclude Users**: Filter out specific accounts
- **List Members**: Tweets from Twitter list members (`list:list_id`)
- **Verified Only**: Blue checkmark or verified users
- **Blue Verified Only**: Twitter Blue subscribers

#### 3. Geographic Filters

- **Near Location**: Geotagged tweets near a city (`near:"San Francisco"`)
- **Within Radius**: Within specific distance (`within:25km`)
- **Geocode**: Precise coordinates (`geocode:37.7764685,-122.4172004,10km`)
- **Place ID**: Twitter Place Object ID (`place:96683cc9126741d1`)

#### 4. Time Filters

- **Date Range**: Start and end dates (`since:2024-01-01`, `until:2024-12-31`)
- **Relative Time**: Last X time (`within_time:24h`, `within_time:7d`)
- **Unix Timestamps**: Precise time control
- **Tweet ID Boundaries**: Snowflake ID-based pagination (`since_id:`, `max_id:`)

#### 5. Engagement Filters

- **Minimum/Maximum Likes**: Filter by like count (`min_faves:100`)
- **Minimum/Maximum Retweets**: Filter by retweet count (`min_retweets:10`)
- **Minimum/Maximum Replies**: Filter by reply count (`min_replies:5`)
- **Smart Presets**: `low`, `medium`, `high`, `viral` engagement levels
- **Has Engagement**: Must have any engagement

#### 6. Media Filters

- **Media Types**: Images, videos, GIFs, native video, Spaces
- **Has Links**: Tweets containing URLs
- **Has Mentions**: Tweets with @mentions
- **Has Hashtags**: Tweets with hashtags
- **News Only**: Tweets linking to news sites
- **Safe Content**: Exclude potentially sensitive content

#### 7. Tweet Type Filters

- **Include Types**: Original tweets, retweets, replies, quotes
- **Exclude Types**: Filter out specific tweet types
- **Conversation ID**: Thread/conversation tweets (`conversation_id:`)
- **Quoted Tweet ID**: Quotes of specific tweets (`quoted_tweet_id:`)
- **Quoted User ID**: Quotes from specific users (`quoted_user_id:`)
- **Poll Types**: Tweets containing polls (2-4 choice polls)

#### 8. App/Source Filters

- **Sources**: Tweets from specific apps (`source:twitter_for_iphone`)
- **Exclude Sources**: Filter out specific apps
- **Card Domain**: Twitter Card domain (`card_domain:youtube.com`)
- **Card URL**: Twitter Card URL (`card_url:`)
- **Card Name**: Card types (audio, animated_gif, player, app, summary, etc.)

***

### 📦 Rich Data Extraction

Each result includes comprehensive metadata:

```json
{
  "searchType": "post",
  "type": "tweet",
  "query": "python programming",
  "data": {
    "tweet_url": "https://x.com/username/status/123456789",
    "tweet_id": "123456789",
    "author": {
      "fullname": "Python Dev",
      "username": "pythondev",
      "verified": true,
      "profile_picture": "https://pbs.twimg.com/...",
      "bio": "Python enthusiast",
      "followers": 15000,
      "following": 500
    },
    "text": "Just released a new Python library! #python #coding",
    "timestamp": "2024-01-15T10:30:00Z",
    "stats": {
      "likes": 150,
      "retweets": 45,
      "comments": 12,
      "quotes": 3
    },
    "media": [
      {
        "type": "image",
        "url": "https://pbs.twimg.com/media/..."
      }
    ],
    "urls": ["https://github.com/..."],
    "hashtags": ["python", "coding"],
    "mentions": ["@pythonorg"]
  }
}
```

***

### 🚀 Three Search Modes

#### 1. Global Search (Post Search)

Search tweets across all of Twitter using keywords, hashtags, time, geo, media, and engagement filters.

```json
{
  "query": "climate change",
  "queryType": "Latest",
  "numberOfTweets": 500,
  "timeSince": "2024-01-01",
  "contentLanguage": "en"
}
```

#### 2. Profile Search

Scrape tweets from a specific user profile with date range, keywords, and engagement filters.

```json
{
  "query": "AI",
  "username": "elonmusk",
  "numberOfTweets": 200,
  "timeSince": "2024-01-01"
}
```

#### 3. User Search

Discover Twitter user profiles based on search queries.

```json
{
  "query": "python developer",
  "searchType": "user"
}
```

***

### 📋 Complete Input Schema

#### Core Parameters

| Parameter | Type | Description | Example |
|-----------|------|-------------|---------|
| `query` | string | Base search query | `"artificial intelligence"` |
| `queryType` | enum | `Latest` or `Top` | `"Latest"` |
| `numberOfTweets` | integer | Number of tweets (20-10000) | `100` |
| `maxPages` | integer | Maximum pages to scrape | `50` |

#### Engagement Filters

| Parameter | Type | Description |
|-----------|------|-------------|
| `engagementLevel` | enum | Preset: `none`, `low`, `medium`, `high`, `viral` |
| `engagementMinLikes` | integer | Minimum likes |
| `engagementMaxLikes` | integer | Maximum likes |
| `engagementMinRetweets` | integer | Minimum retweets |
| `engagementMaxRetweets` | integer | Maximum retweets |
| `engagementMinReplies` | integer | Minimum replies |
| `engagementMaxReplies` | integer | Maximum replies |
| `engagementHasEngagement` | boolean | Must have any engagement |

#### Content Filters

| Parameter | Type | Description |
|-----------|------|-------------|
| `contentKeywords` | array | Keywords to search for |
| `contentExactPhrases` | array | Exact phrases (quoted) |
| `contentHashtags` | array | Hashtags to include |
| `contentExcludeHashtags` | array | Hashtags to exclude |
| `contentCashtags` | array | Stock symbols |
| `contentExcludeKeywords` | array | Keywords to exclude |
| `contentLanguage` | enum | Language code (`en`, `es`, `fr`, etc.) |
| `contentEmoticons` | enum | `positive` or `negative` |
| `contentQuestionMarks` | boolean | Include question marks |

#### User Filters

| Parameter | Type | Description |
|-----------|------|-------------|
| `usersFromUsers` | array | Tweets from specific users |
| `usersToUsers` | array | Replies to specific users |
| `usersMentionUsers` | array | Tweets mentioning users |
| `usersExcludeFromUsers` | array | Exclude tweets from users |
| `usersListMembers` | array | From list members |
| `usersVerifiedOnly` | boolean | Verified users only |
| `usersBlueVerifiedOnly` | boolean | Blue verified users only |

#### Time Filters

| Parameter | Type | Description |
|-----------|------|-------------|
| `timeSince` | string | Start date (`YYYY-MM-DD`) |
| `timeUntil` | string | End date (`YYYY-MM-DD`) |
| `timeWithinTime` | string | Relative time (`24h`, `7d`, `30s`) |
| `timeSinceUnix` | integer | Start Unix timestamp |
| `timeUntilUnix` | integer | End Unix timestamp |
| `timeSinceId` | string | Since tweet ID (Snowflake) |
| `timeMaxId` | string | Max tweet ID (Snowflake) |

#### Geo Filters

| Parameter | Type | Description |
|-----------|------|-------------|
| `geoNear` | string | Near location |
| `geoWithinRadius` | string | Within radius (`25km`, `15mi`) |
| `geoGeocode` | string | Coordinates (`lat,long,radius`) |
| `geoPlaceId` | string | Twitter Place ID |

#### Media Filters

| Parameter | Type | Description |
|-----------|------|-------------|
| `mediaTypes` | array | `image`, `video`, `media`, `native_video`, `spaces` |
| `mediaHasLinks` | boolean | Must contain links |
| `mediaHasMentions` | boolean | Must contain mentions |
| `mediaHasHashtags` | boolean | Must contain hashtags |
| `mediaNewsOnly` | boolean | News links only |
| `mediaSafeContentOnly` | boolean | Safe content only |

#### Tweet Type Filters

| Parameter | Type | Description |
|-----------|------|-------------|
| `tweetTypes` | array | Include types (`retweet`, `reply`, `quote`) |
| `tweetTypesExclude` | array | Exclude types |
| `tweetConversationId` | string | Conversation/thread ID |
| `tweetQuotedTweetId` | string | Quoted tweet ID |
| `tweetQuotedUserId` | string | Quoted user ID |
| `tweetPollTypes` | array | Poll types |

#### App/Source Filters

| Parameter | Type | Description |
|-----------|------|-------------|
| `appsSources` | array | App sources |
| `appsExcludeSources` | array | Exclude sources |
| `cardDomain` | string | Card domain |
| `cardUrl` | string | Card URL |
| `cardName` | enum | Card name (`audio`, `animated_gif`, `player`, etc.) |

#### Additional Parameters

| Parameter | Type | Description |
|-----------|------|-------------|
| `proxyUrl` | string | Optional proxy URL |
| `baseUrl` | string | Base URL for scraping (optional) |

***

### 📖 Advanced Search Operators Reference

Our actor supports the complete range of X's advanced search operators. Here's your comprehensive reference:

#### Content Operators

| Operator | Description | Example |
|----------|-------------|---------|
| `"exact phrase"` | Search for exact phrases | `"machine learning"` |
| `keyword1 keyword2` | Both keywords (implicit AND) | `AI technology` |
| `keyword1 OR keyword2` | Either keyword | `AI OR artificial intelligence` |
| `+forced_term` | Force inclusion (prevent spelling correction) | `+radiooooo` |
| `-excluded_term` | Exclude terms | `AI -spam` |
| `#hashtag` | Hashtag search | `#AI` |
| `$cashtag` | Stock symbol search | `$TSLA` |
| `?` | Questions only | `What ?` |
| `:)` or `:(` | Positive/negative emoticons | `:) OR :(` |
| `url:domain.com` | URL content search | `url:github.com` |
| `lang:en` | Language filter | `lang:en` |

#### User Operators

| Operator | Description | Example |
|----------|-------------|---------|
| `from:username` | Tweets from specific user | `from:elonmusk` |
| `to:username` | Replying to specific user | `to:support` |
| `@username` | Mentioning specific user | `@company_handle` |
| `list:list_id` | Tweets from list members | `list:715919216927322112` |
| `filter:verified` | Verified users only | `filter:verified` |
| `filter:blue_verified` | Blue checkmark users | `filter:blue_verified` |

#### Geographic Operators

| Operator | Description | Example |
|----------|-------------|---------|
| `near:"city"` | Geotagged in location | `near:"San Francisco"` |
| `within:radius` | Within radius of location | `within:10km` |
| `geocode:lat,long,radius` | Precise coordinates | `geocode:37.7764685,-122.4172004,10km` |
| `place:place_id` | Specific place ID | `place:96683cc9126741d1` |

#### Time Operators

| Operator | Description | Example |
|----------|-------------|---------|
| `since:2024-01-01` | From date (inclusive) | `since:2024-01-01` |
| `until:2024-12-31` | Before date (exclusive) | `until:2024-12-31` |
| `since_time:timestamp` | Unix timestamp from | `since_time:1640995200` |
| `until_time:timestamp` | Unix timestamp until | `until_time:1672531199` |
| `since_id:tweet_id` | After Snowflake ID | `since_id:1138872932887924737` |
| `max_id:tweet_id` | At or before Snowflake ID | `max_id:1144730280353247233` |
| `within_time:2d` | Relative time window | `within_time:24h` |

#### Engagement Operators

| Operator | Description | Example |
|----------|-------------|---------|
| `min_retweets:5` | Minimum retweets | `min_retweets:100` |
| `min_faves:10` | Minimum likes | `min_faves:1000` |
| `min_replies:100` | Minimum replies | `min_replies:50` |
| `filter:has_engagement` | Has any engagement | `filter:has_engagement` |

#### Media Operators

| Operator | Description | Example |
|----------|-------------|---------|
| `filter:media` | All media types | `filter:media` |
| `filter:images` | Images only | `filter:images` |
| `filter:videos` | Videos only | `filter:videos` |
| `filter:links` | Contains links | `filter:links` |
| `filter:news` | News content | `filter:news` |

#### Tweet Type Operators

| Operator | Description | Example |
|----------|-------------|---------|
| `filter:retweets` | Retweets and quotes | `filter:retweets` |
| `filter:replies` | Reply tweets | `filter:replies` |
| `filter:quote` | Quote tweets | `filter:quote` |
| `conversation_id:id` | Conversation thread | `conversation_id:1140437409710116865` |
| `quoted_tweet_id:id` | Quotes of specific tweet | `quoted_tweet_id:1138631847783608321` |
| `quoted_user_id:id` | Quotes from specific user | `quoted_user_id:11348282` |

#### App/Source Operators

| Operator | Description | Example |
|----------|-------------|---------|
| `source:client_name` | From specific app | `source:twitter_for_iphone` |
| `card_domain:domain` | Card domain | `card_domain:youtube.com` |
| `card_url:url` | Card URL | `card_url:pscp.tv` |
| `card_name:name` | Card name | `card_name:player` |

> 📚 **Complete Reference**: For the full list of operators, see [Twitter Advanced Search Operators Documentation](https://github.com/igorbrigadir/twitter-advanced-search)

***

### 🎯 Pre-Built Filter Presets

#### Viral Content

```json
{
  "engagementLevel": "viral",
  "engagementMinLikes": 1000,
  "engagementMinRetweets": 100
}
```

#### News Content

```json
{
  "mediaNewsOnly": true,
  "mediaHasLinks": true,
  "contentLanguage": "en"
}
```

#### Verified Users Only

```json
{
  "usersVerifiedOnly": true
}
```

#### Recent Tweets (24 hours)

```json
{
  "timeWithinTime": "24h"
}
```

#### Local News

```json
{
  "geoNear": "New York",
  "geoWithinRadius": "50km",
  "mediaNewsOnly": true
}
```

***

### 💡 Pro Tips for Maximum Results

#### Optimization Strategies

1. **Start Specific**: Begin with targeted filters and expand as needed
2. **Combine Filters**: Use multiple filter types for precise results
3. **Test Iteratively**: Experiment with different combinations
4. **Monitor Performance**: Track query performance and adjust accordingly

#### Advanced Techniques

- **Use Engagement Presets**: Leverage smart presets for common use cases
- **Time-Based Filtering**: Combine date ranges with engagement filters for trending content
- **Geographic Targeting**: Use location filters for local market research
- **Content Analysis**: Combine language and sentiment filters for brand monitoring

#### Best Practices

- ✅ **Validate Inputs**: Our actor validates all filter combinations automatically
- ✅ **Handle Pagination**: Use cursor-based pagination for large datasets
- ✅ **Monitor Rate Limits**: Be aware of limitations for high-volume operations
- ✅ **Data Quality**: Use exclusion filters to improve result relevance

***

### 📊 Output

Results are stored in the **default Apify dataset** with multiple built-in views:

- 📄 **All Tweets** - Complete tweet data
- 👤 **Users** - User profile information
- 🔥 **High Engagement Tweets** - Filtered by engagement
- 🖼 **Tweets with Media** - Media-rich tweets

#### Export Formats

- **JSON** - Structured data format
- **CSV** - Spreadsheet-compatible
- **Excel** - Microsoft Excel format
- **XML** - XML format

***

### 💰 Pricing

**Best Value on Apify:** Only **$20 per 1,000 results** ($0.02 per result) - The most affordable Twitter scraping solution available!

- ✅ **Transparent Pricing** - No hidden fees, pay only for what you extract
- ✅ **Pay Per Result** - Scale up or down with zero commitment
- ✅ **Automatic Query Cleaning** - Auto-corrects operator spacing, closes quotes, and deduplicates redundant filters

**Get Started:** <https://apify.com/mikolabs/x-twitter-advanced-search-tweet-scraper>

***

### ⭐ Use Cases

- **Social Listening & Trend Analysis** - Monitor brand mentions and industry trends
- **Brand Monitoring** - Track your brand across Twitter
- **Crypto & Stock Sentiment Tracking** - Analyze market sentiment
- **Lead Generation** - Find potential customers and partners
- **Academic & Research Datasets** - Collect data for research
- **Media & Journalism Research** - Investigate stories and sources
- **Competitor Analysis** - Monitor competitor activities
- **Influencer Discovery** - Find relevant influencers
- **Crisis Management** - Track negative mentions
- **Content Research** - Find trending topics and content ideas

***

### 🛡️ Legal and Ethical Considerations

Our actor operates within ethical boundaries and legal frameworks:

- ✅ **Public Data Only**: We only collect publicly available information
- ✅ **No Private Data**: We do not access private accounts or DMs
- ✅ **GDPR Compliant**: Respects privacy regulations and user consent
- ✅ **Rate Limiting**: Built-in safeguards prevent excessive usage
- ✅ **Transparent Operations**: Clear documentation of data collection

> ⚠️ **Important**: Always respect Twitter's Terms of Service and robots.txt. Use responsibly and ethically.

***

### 📞 Support and Documentation

- **Comprehensive Examples**: Extensive code samples and use cases
- **Filter Documentation**: Detailed explanations of all filter options
- **API Reference**: Complete technical documentation
- **Community Support**: Active community and expert assistance

***

### 📄 License

Licensed under **Apache License 2.0** - Free to use, modify, and integrate in commercial projects.

***

### 🚀 Getting Started

1. **Set up your Apify account** - Create an account at [apify.com](https://apify.com)
2. **Visit the Actor** - Go to <https://apify.com/mikolabs/x-twitter-advanced-search-tweet-scraper>
3. **Choose your search method** - Simple Query or Advanced Filters
4. **Configure your parameters** - Use our comprehensive filter system
5. **Execute the actor** - Run and collect your structured data
6. **Analyze and integrate** - Export in multiple formats

***

**🔥 Ready to unlock the full potential of X (Twitter) data? Start with our advanced search capabilities and experience the difference that superior technology makes.**

**💰 Best Value:** Only **$20 per 1,000 results** - The cheapest Twitter scraping solution on Apify!

Transform your social media intelligence with the most powerful X (Twitter) search solution available.

**👉 Get Started Now:** <https://apify.com/mikolabs/x-twitter-advanced-search-tweet-scraper>

# Actor input Schema

## `searchType` (type: `string`):

Select what you want to search:

- **'tweets'** (default): Universal search for tweets/posts across all users. Uses PostSearchScraper to search tweets globally with advanced filters.
- **'users'**: Universal search for X/Twitter user profiles. Uses UserSearchScraper to find users matching your criteria.
- **'profile'**: Search tweets within a specific user's profile. Uses ProfileSearchScraper to scrape a user's profile and search their tweets. **REQUIRED**: When 'profile' is selected, you MUST provide the target username in 'From Users' field (usersFromUsers) - the first entry will be used. You can also use other user filters like 'To Users', 'Mention Users', 'Exclude From Users', and verification filters to further refine the search within that profile.

## `query` (type: `string`):

Enter your search terms here for quick and easy Twitter searches. Supports Twitter's powerful search operators for precise results. You can use this simple search OR configure advanced filters below - at least one must be provided.

## `search_type` (type: `string`):

Choose your search strategy: 'Latest' for real-time results, 'Top' for popular tweets, 'Media' for tweets with images/videos, 'People' for user accounts, or 'Lists' for Twitter lists.

## `queryType` (type: `string`):

Choose your search strategy: 'Latest' for real-time, chronological results or 'Top' for the most popular and engaging tweets.

## `numberOfTweets` (type: `integer`):

Specify how many tweets you want to collect. Use 'Scrape All' to extract all available results without limit.

## `includeUserStats` (type: `boolean`):

Include detailed profile statistics (followers, following, tweets count, location, website, join date, banner) for users. When searching tweets/posts, includes author stats. When searching users, includes stats for each user found. This requires an additional request per unique user.

## `scrapeAll` (type: `boolean`):

When enabled, scrapes all available tweets from your input query, ignoring the 'Number of Tweets' limit.

## `advancedFilters` (type: `object`):

Optional nested advanced filters container (content, users, time, engagement, media, tweetTypes, geo, apps) for fine-grained search control.

## `engagementLevel` (type: `string`):

Smart presets for common engagement scenarios. Choose a preset for instant setup or customize with specific values below for precise control.

## `engagementMinRetweets` (type: `integer`):

Minimum number of retweets (shares). Leave empty for no minimum.

## `engagementMaxRetweets` (type: `integer`):

Maximum number of retweets (shares). Leave empty for no maximum.

## `engagementMinLikes` (type: `integer`):

Minimum number of likes (hearts). Leave empty for no minimum.

## `engagementMaxLikes` (type: `integer`):

Maximum number of likes (hearts). Leave empty for no maximum.

## `engagementMinReplies` (type: `integer`):

Minimum number of replies (comments). Leave empty for no minimum.

## `engagementMaxReplies` (type: `integer`):

Maximum number of replies (comments). Leave empty for no maximum.

## `engagementHasEngagement` (type: `boolean`):

Only include tweets that have at least some engagement (likes, retweets, or replies)

## `mediaTypes` (type: `array`):

Types of media to include in search results. Available options:

- **image**: Tweets containing images
- **video**: Tweets containing videos
- **native_video**: Tweets with native Twitter videos
- **spaces**: Tweets from Twitter Spaces (audio conversations)

You can select multiple types. Selecting both 'image' and 'video' will search for any media content.

## `mediaHasLinks` (type: `boolean`):

Must contain links

## `mediaHasMentions` (type: `boolean`):

Must contain mentions

## `mediaHasHashtags` (type: `boolean`):

Must contain hashtags

## `mediaNewsOnly` (type: `boolean`):

Only tweets with news links

## `mediaSafeContentOnly` (type: `boolean`):

Exclude potentially sensitive content

## `usersBlueVerifiedOnly` (type: `boolean`):

Only tweets from blue verified users

## `usersVerifiedOnly` (type: `boolean`):

Only tweets from verified users

## `usersFromUsers` (type: `array`):

Tweets from specific users (without @). **REQUIRED for profile search**: When searchType is 'profile', provide the target username here (first entry will be used). For other search types, this filters results to tweets from these users.

## `usersToUsers` (type: `array`):

Replies to specific users (without @)

## `usersMentionUsers` (type: `array`):

Tweets mentioning specific users (without @)

## `usersExcludeFromUsers` (type: `array`):

Exclude tweets from specific users (without @)

## `usersListMembers` (type: `array`):

Tweets from members of specific lists (list ID or username/listname)

## `contentLanguage` (type: `string`):

Filter tweets by language. Select the language code for tweets you want to find. Language detection is approximate and may not always be accurate. Works best when combined with other filters.

## `contentEmoticons` (type: `string`):

Filter tweets by emoticon sentiment. **Positive**: Matches tweets with positive emoticons like :) :-) :P :D. **Negative**: Matches tweets with negative emoticons like :( :-(. Useful for sentiment analysis and finding emotional content.

## `contentKeywords` (type: `array`):

Search for specific keywords in tweet content. Enter one or more keywords that should appear in tweets. Keywords are matched individually (AND logic). For exact phrase matching, use 'Exact Phrases' instead. Example: \['climate change', 'sustainability'] will find tweets containing both 'climate change' AND 'sustainability'.

## `contentExactPhrases` (type: `array`):

Search for exact phrases in tweet content. Phrases are automatically wrapped in quotes for exact matching. Use this when you need to find tweets containing specific word combinations in order. Example: \['breaking news', 'just announced'] will find tweets containing the exact phrase 'breaking news' OR 'just announced'.

## `contentExcludeKeywords` (type: `array`):

Exclude tweets containing specific keywords. Useful for filtering out unwanted content like spam, ads, or promotional material. Example: \['spam', 'ad', 'promotion'] will exclude tweets containing any of these words.

## `contentHashtags` (type: `array`):

Search for tweets containing specific hashtags. Enter hashtags without the # symbol (it's added automatically). You can include multiple hashtags - tweets matching any of them will be included. Example: \['AI', 'MachineLearning'] will find tweets with #AI OR #MachineLearning.

## `contentExcludeHashtags` (type: `array`):

Exclude tweets containing specific hashtags. Useful for filtering out tweets with unwanted hashtags like promotional tags or spam. Enter hashtags without the # symbol. Example: \['ad', 'sponsored'] will exclude tweets containing #ad OR #sponsored.

## `contentCashtags` (type: `array`):

Search for tweets containing stock symbols (cashtags). Enter stock symbols without the $ symbol (it's added automatically). Useful for tracking stock market discussions and financial content. Example: \['AAPL', 'TSLA'] will find tweets mentioning $AAPL OR $TSLA.

## `contentQuestionMarks` (type: `boolean`):

Only include tweets that contain question marks (?). Useful for finding questions, polls, or tweets seeking information. When enabled, only tweets with question marks will be returned.

## `tweetTypes` (type: `array`):

Filter to include specific types of tweets. Select one or more types to narrow your search. **Note**: If you select multiple types, tweets matching ANY of them will be included. Use 'Exclude Tweet Types' below to filter out unwanted types.

- **retweet**: Old-style retweets (RT) and quoted tweets
- **nativeretweets**: Only native retweets (created with retweet button, works within last 7-10 days)
- **reply**: Tweets that are replies to other tweets (useful for finding conversations)
- **quote**: Quote tweets (tweets that quote another tweet)
- **self_threads**: Self-replies only (tweets that are part of a thread by the same user)

## `tweetTypesExclude` (type: `array`):

Exclude specific types of tweets from results. Useful for filtering out retweets, replies, or other types you don't want. Works in combination with 'Include Tweet Types' - you can include some types while excluding others.

Available types: **retweet**, **nativeretweets**, **reply**, **quote**, **self_threads**

## `tweetConversationId` (type: `string`):

Find all tweets that are part of a specific conversation or thread. Enter the tweet ID (Snowflake ID) of any tweet in the conversation. This will return all direct replies and other replies in that thread. Useful for analyzing entire conversation threads.

## `tweetQuotedTweetId` (type: `string`):

Find all tweets that quote a specific tweet. Enter the tweet ID (Snowflake ID) of the original tweet. This will return all quote tweets that reference that specific tweet. Useful for tracking how a particular tweet spreads through quotes.

## `tweetQuotedUserId` (type: `string`):

Find all tweets that quote tweets from a specific user. Enter the numeric user ID (not username) of the user whose tweets are being quoted. This returns all quote tweets that reference any tweet from that user. **Note**: Requires numeric user ID, not username. Example: '44196397' (Elon Musk's user ID).

## `tweetPollTypes` (type: `array`):

Filter to include tweets containing polls. Select the types of polls you want to find. You can select multiple types - tweets matching ANY selected type will be included.

Available poll types:

- **poll** or **poll2choice_text_only**: 2-choice text polls
- **poll3choice_text_only**: 3-choice text polls
- **poll4choice_text_only**: 4-choice text polls
- **poll2choice_image**: 2-choice image polls
- **poll3choice_image**: 3-choice image polls
- **poll4choice_image**: 4-choice image polls

## `timeSince` (type: `string`):

Start date (YYYY-MM-DD)

## `timeUntil` (type: `string`):

End date (YYYY-MM-DD)

## `timeWithinTime` (type: `string`):

Search within last X time (e.g., '2d', '3h', '5m', '30s')

## `timeSinceUnix` (type: `integer`):

Start time as Unix timestamp in seconds

## `timeUntilUnix` (type: `integer`):

End time as Unix timestamp in seconds

## `timeSinceId` (type: `string`):

Start after this Snowflake tweet ID

## `timeMaxId` (type: `string`):

End at or before this Snowflake tweet ID

## `geoNear` (type: `string`):

Location to search near

## `geoWithinRadius` (type: `string`):

Radius for location search (e.g., '10km', '5mi')

## `geoGeocode` (type: `string`):

Exact coordinates (lat,long,radius) e.g., '37.7764685,-122.4172004,10km'

## `geoPlaceId` (type: `string`):

Twitter Place Object ID (e.g., '96683cc9126741d1' for USA)

## `apps` (type: `object`):

Filter tweets by app source, Twitter Cards, and card types. Supports filtering by source apps, card domains, card URLs, and card names. Example: {"sources": \["twitter_for_iphone", "tweetdeck"], "cardDomains": \["youtube.com"]}

## `appsSources` (type: `array`):

\[DEPRECATED] Use 'apps.sources' instead. Tweets from specific apps/sources.

## `appsExcludeSources` (type: `array`):

\[DEPRECATED] Use 'apps.excludeSources' instead. Exclude tweets from specific apps/sources.

## `cardDomain` (type: `string`):

\[DEPRECATED] Use 'apps.cardDomains' instead. Domain name in Twitter Card.

## `cardUrl` (type: `string`):

\[DEPRECATED] Use 'apps.cardUrls' instead. URL in Twitter Card.

## `cardName` (type: `string`):

\[DEPRECATED] Use 'apps.cardNames' instead. Twitter Card name.

## `maxRetry` (type: `integer`):

Maximum number of retry attempts for failed HTTP requests. When a request fails (network error, rate limit, server error, etc.), the scraper will automatically retry up to this many times before giving up. Higher values increase reliability but may slow down scraping. Default is 5 retries. Applies to all search types (tweets, users, profile) and list extraction.

## `useResidentialProxy` (type: `boolean`):

Use Apify residential proxy for all requests. Enabled by default for better success rates. Disable only if you have a custom proxy configuration.

## `proxyConfiguration` (type: `object`):

Advanced proxy configuration. Leave empty to use default residential proxy settings. Supports apifyProxyGroups (e.g., \['RESIDENTIAL']) or legacy 'groups' format.

## `proxyCountryCode` (type: `string`):

Optional country code to pin proxy to specific country (e.g., 'US', 'GB', 'DE'). Only works with residential proxy.

## `proxyUrl` (type: `string`):

Optional manual proxy URL for requests. Format: http://username:password@proxy-server:port. Only used if residential proxy is disabled. Note: Residential proxy is recommended and configured automatically.

## Actor input object example

```json
{
  "searchType": "tweets",
  "query": "btc",
  "search_type": "Latest",
  "queryType": "Latest",
  "numberOfTweets": 20,
  "includeUserStats": false,
  "scrapeAll": false,
  "engagementLevel": "none",
  "engagementMinRetweets": 10,
  "engagementMaxRetweets": 1000,
  "engagementMinLikes": 50,
  "engagementMaxLikes": 5000,
  "engagementMinReplies": 5,
  "engagementMaxReplies": 500,
  "mediaTypes": [
    "image",
    "video"
  ],
  "usersFromUsers": [
    "elonmusk",
    "OpenAI"
  ],
  "usersToUsers": [
    "support",
    "customerservice"
  ],
  "usersMentionUsers": [
    "nasa",
    "spacex"
  ],
  "usersExcludeFromUsers": [
    "spambot",
    "promotional_account"
  ],
  "usersListMembers": [
    "Twitter/verified-accounts",
    "123456789"
  ],
  "contentKeywords": [
    "climate change",
    "sustainability",
    "renewable energy"
  ],
  "contentExactPhrases": [
    "breaking news",
    "just announced"
  ],
  "contentExcludeKeywords": [
    "spam",
    "ad",
    "promotion"
  ],
  "contentHashtags": [
    "AI",
    "MachineLearning",
    "TechNews"
  ],
  "contentExcludeHashtags": [
    "ad",
    "sponsored",
    "giveaway"
  ],
  "contentCashtags": [
    "AAPL",
    "TSLA",
    "GOOGL"
  ],
  "tweetTypes": [
    "quote",
    "reply"
  ],
  "tweetTypesExclude": [
    "retweet"
  ],
  "tweetConversationId": "1234567890123456789",
  "tweetQuotedTweetId": "1234567890123456789",
  "tweetQuotedUserId": "44196397",
  "tweetPollTypes": [
    "poll",
    "poll4choice_text_only"
  ],
  "timeSinceUnix": 1704067200,
  "timeUntilUnix": 1735689599,
  "timeSinceId": "1234567890123456789",
  "timeMaxId": "9876543210987654321",
  "geoNear": "New York City",
  "geoWithinRadius": "25km",
  "geoGeocode": "40.7128,-74.0060,15mi",
  "geoPlaceId": "96683cc9126741d1",
  "appsSources": [
    "Twitter for iPhone",
    "TweetDeck"
  ],
  "appsExcludeSources": [
    "IFTTT",
    "Buffer"
  ],
  "cardDomain": "youtube.com",
  "cardUrl": "https://www.youtube.com/watch?v=example",
  "maxRetry": 5,
  "useResidentialProxy": true,
  "proxyConfiguration": {
    "apifyProxyGroups": [
      "RESIDENTIAL"
    ],
    "countryCode": "US"
  },
  "proxyCountryCode": "US",
  "proxyUrl": "http://user:pass@proxy.example.com:8080"
}
```

# Actor output Schema

## `overview` (type: `string`):

Comprehensive overview of scraped Twitter data with detailed engagement metrics, verification status, and all available data fields.

## `tweets` (type: `string`):

Complete tweet data with engagement metrics (likes, retweets, replies, quotes), verification status, media, hashtags, mentions, and URLs.

## `users` (type: `string`):

User profile information including verification status (verified, verified_type), bio, profile URLs, and social metrics.

## `highEngagement` (type: `string`):

Tweets with high engagement metrics (1000+ likes or 500+ retweets). Includes likes, retweets, replies, quotes, author verification status, and tweet details.

## `withMedia` (type: `string`):

Tweets containing images or videos. Includes media URLs, thumbnails, engagement metrics, verification status, and all tweet details.

## `engagementDetails` (type: `string`):

Detailed breakdown of engagement metrics: likes, retweets (reposts), replies (comments), and quotes for all tweets.

## `verifiedUsers` (type: `string`):

Tweets from verified accounts only. Shows verification type (blue, business, government) along with engagement metrics and tweet details.

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "query": "btc"
};

// Run the Actor and wait for it to finish
const run = await client.actor("mikolabs/x-twitter-advanced-search-tweet-scraper").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = { "query": "btc" }

# Run the Actor and wait for it to finish
run = client.actor("mikolabs/x-twitter-advanced-search-tweet-scraper").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "query": "btc"
}' |
apify call mikolabs/x-twitter-advanced-search-tweet-scraper --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,mikolabs/x-twitter-advanced-search-tweet-scraper"
        }
    }
}
```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/kYmSPYe52wPALhOii/builds/6IXt4Yi8DXENT1uEy/openapi.json
