Skip to content
xai-x-search logo

xAI X (Twitter) Search

xai-x-search

Search Twitter/X in real-time using Grok API. Use when searching X posts, tracking trends, monitoring accounts, or analyzing social discussions.

NeverSight/skills_feed0installs215stars

SKILL.md

Full skill instructions

xAI X (Twitter) Search

Real-time Twitter/​X search using Grok's native X integration - a capability unique to xAI.

Quick Start

import os
from openai import OpenAI

client = OpenAI(
    api_key=os.getenv("XAI_API_KEY"),
    base_url="https://api.x.ai/​v1"
)

# Simple X search
response = client.chat.completions.create(
    model="grok-4-1-fast",
    messages=[{
        "role": "user",
        "content": "Search X for what people are saying about Tesla stock today"
    }]
)
print(response.choices[0].message.content)

Search Capabilities

1. Topic Search

def search_x_topic(topic: str) -> str:
    """Search X for posts about a topic."""
    response = client.chat.completions.create(
        model="grok-4-1-fast",
        messages=[{
            "role": "user",
            "content": f"Search X for recent posts about {topic}. Summarize the main discussions and sentiment."
        }]
    )
    return response.choices[0].message.content

2. Ticker/​Stock Search

def search_stock_mentions(ticker: str) -> str:
    """Search X for stock ticker mentions."""
    response = client.chat.completions.create(
        model="grok-4-1-fast",
        messages=[{
            "role": "user",
            "content": f"""Search X for mentions of ${ticker} stock.
            Find:
            - Recent discussions
            - Sentiment (bullish/​bearish)
            - Key influencer opinions
            - Breaking news mentions
            Return structured analysis."""
        }]
    )
    return response.choices[0].message.content

3. Account Monitoring

def monitor_account(handle: str) -> str:
    """Get recent posts from a specific X account."""
    response = client.chat.completions.create(
        model="grok-4-1-fast",
        messages=[{
            "role": "user",
            "content": f"Search X for the most recent posts from @{handle}. Summarize their latest activity."
        }]
    )
    return response.choices[0].message.content

4. Trending Topics

def get_trending() -> str:
    """Get current trending topics on X."""
    response = client.chat.completions.create(
        model="grok-4-1-fast",
        messages=[{
            "role": "user",
            "content": "What are the current trending topics on X? List the top 10 with brief descriptions."
        }]
    )
    return response.choices[0].message.content

Agent Tools API (Advanced)

For more control, use the Agent Tools API:

# Using Responses API with x_search tool
response = client.chat.completions.create(
    model="grok-4-1-fast",
    messages=[{
        "role": "user",
        "content": "Search X for posts about Bitcoin from the last 24 hours"
    }],
    tools=[{
        "type": "x_search",
        "x_search": {
            "enabled": True,
            "date_range": {
                "start": "2025-12-04",
                "end": "2025-12-05"
            }
        }
    }]
)

Filter by Handles

# Search only specific accounts
response = client.chat.completions.create(
    model="grok-4-1-fast",
    messages=[{
        "role": "user",
        "content": "What are these financial analysts saying about the market?"
    }],
    tools=[{
        "type": "x_search",
        "x_search": {
            "enabled": True,
            "allowed_x_handles": [
                "jimcramer",
                "elonmusk",
                "chaikinadx",
                "unusual_whales"
            ]
        }
    }]
)

Common Use Cases

Financial News Monitoring

def monitor_financial_news() -> dict:
    """Monitor financial news on X."""
    response = client.chat.completions.create(
        model="grok-4-1-fast",
        messages=[{
            "role": "user",
            "content": """Search X for breaking financial news in the last hour.
            Focus on:
            - Market-moving news
            - Earnings announcements
            - Fed/​economic news
            - Major analyst calls

            Return as JSON:
            {
                "breaking_news": [...],
                "market_sentiment": "bullish/​bearish/​neutral",
                "key_events": [...]
            }"""
        }]
    )
    return response.choices[0].message.content

Earnings Reaction Tracking

def track_earnings_reaction(ticker: str) -> str:
    """Track X reaction to earnings announcement."""
    response = client.chat.completions.create(
        model="grok-4-1-fast",
        messages=[{
            "role": "user",
            "content": f"""Search X for reaction to ${ticker} earnings.
            Analyze:
            - Overall sentiment
            - Key concerns raised
            - Positive highlights mentioned
            - Notable influencer reactions
            - Volume of discussion"""
        }]
    )
    return response.choices[0].message.content

Competitor Analysis

def compare_sentiment(tickers: list) -> str:
    """Compare X sentiment across multiple stocks."""
    ticker_str = ", ".join([f"${t}" for t in tickers])
    response = client.chat.completions.create(
        model="grok-4-1-fast",
        messages=[{
            "role": "user",
            "content": f"""Compare X sentiment for: {ticker_str}
            For each, provide:
            - Current sentiment score (-1 to +1)
            - Key themes being discussed
            - Notable mentions
            Return as structured comparison."""
        }]
    )
    return response.choices[0].message.content

Search Parameters

ParameterDescriptionMax
allowed_x_handlesOnly search these accounts10
excluded_x_handlesExclude these accounts10
date_range.startStart date (ISO8601)-
date_range.endEnd date (ISO8601)-
include_mediaAnalyze images/​videos-

Rate Limits & Costs

MetricValue
Cost per search$0.005 ($5/​1,000)
Max handles filter10
Date rangeAny

Best Practices

1. Be Specific

# Bad - too vague
"Search X for stocks"

# Good - specific query
"Search X for posts about $AAPL stock price movement today from verified financial accounts"

2. Request Structured Output

# Request JSON for easier parsing
content = """Search X for $NVDA sentiment. Return JSON:
{
    "sentiment": "bullish/​bearish/​neutral",
    "score": -1 to 1,
    "key_posts": [...],
    "influencer_opinions": [...]
}"""

3. Use Handle Filters for Quality

# Filter to trusted sources
financial_handles = [
    "DeItaone",  # Breaking news
    "unusual_whales",  # Options flow
    "Fxhedgers",  # Market news
    "zaborsky"  # Analysis
]

4. Combine with Other Data

# Combine X sentiment with price data
x_sentiment = search_stock_mentions("AAPL")
price_data = finnhub_client.get_quote("AAPL")
# Analyze together

Limitations

  1. Sarcasm detection - May misinterpret sarcastic posts
  2. Bot content - Cannot always filter bot posts
  3. Historical depth - Best for recent data
  4. Rate limits - $5/​1,000 searches

Error Handling

def safe_x_search(query: str) -> dict:
    """X search with error handling."""
    try:
        response = client.chat.completions.create(
            model="grok-4-1-fast",
            messages=[{"role": "user", "content": query}],
            timeout=30
        )
        return {
            "success": True,
            "data": response.choices[0].message.content
        }
    except Exception as e:
        return {
            "success": False,
            "error": str(e)
        }

Related Skills

  • xai-sentiment - Sentiment analysis
  • xai-stock-sentiment - Stock-specific sentiment
  • xai-agent-tools - Advanced tool usage

References

More skills from NeverSight

devops-deployer logo
NeverSight/skills_feed

devops-deployer

Comprehensive DevOps and deployment workflow that orchestrates infrastructure automation, CI/CD pipelines, container orchestration, and cloud deployment. Handles everything from infrastructure as code and pipeline setup to monitoring, scaling, and disaster recovery.

215 1
View
avnu logo
NeverSight/skills_feed

avnu

Integrate avnu SDK for Starknet DeFi: token swaps with best-price routing, DCA recurring buys, native staking, gasless transactions via paymaster, and market data. Use when building Starknet trading, DEX aggregation, or DeFi automation features.

215 0
View
post-to-x logo
NeverSight/skills_feed

post-to-x

发布内容和文章到 X (Twitter)。支持带图片的普通推文和 X Articles(长文)。使用真实的 Chrome 和 CDP 来绕过自动化检测。

215 0
View
ralph-prompt-builder logo
NeverSight/skills_feed

ralph-prompt-builder

Master orchestrator for generating Ralph Wiggum-compatible prompts. Analyzes task requirements and routes to appropriate generator (single-task, multi-task, project, or research). Use when you need to create any Ralph loop prompt and want automatic selection of the right generator.

215 0
View
branch-comparison logo
NeverSight/skills_feed

branch-comparison

Use when the user asks to compare branches, analyze git diffs, review changes between branches, update specifications based on code changes, or analyze what changed. Triggers on keywords like "compare branches", "git diff", "what changed", "branch comparison", "code changes", "spec update".

215 0
View
fastapi-development logo
NeverSight/skills_feed

fastapi-development

Build high-performance FastAPI applications with async routes, validation, dependency injection, security, and automatic API documentation. Use when developing modern Python APIs with async support, automatic OpenAPI documentation, and high performance requirements.

215 0
View
zendesk-chat logo
NeverSight/skills_feed

zendesk-chat

Enables Claude to manage Zendesk Chat conversations, support tickets, and customer service operations

215 0
View
forge logo
NeverSight/skills_feed

forge

Mine transcripts for knowledge - decisions, learnings, failures, patterns. Triggers: "forge insights", "mine transcripts", "extract knowledge".

215 0
View
mixpanel logo
NeverSight/skills_feed

mixpanel

Track product analytics and user behavior with Mixpanel's event-based platform.

215 0
View
ocpp logo
NeverSight/skills_feed

ocpp

OCPP protocol reference for EV charging infrastructure development. Covers OCPP 2.0.1 and OCPP 1.6J. Use when working with OCPP messages, charging station code, CSMS/Central System backends, smart charging, transaction handling, or EV charging protocols. Activates on keywords: OCPP, charging stat...

215 0
View
bee-collect logo
NeverSight/skills_feed

bee-collect

Gather scattered ideas into organized GitHub issues. The bee collects pollen from every flower, checks if the hive already has it, and carefully deposits new work in the comb for later. Never edits code—only organizes the work ahead. Use when creating issues from TODOs or planning work.

215 0
View
vercel-react-native-skills logo
NeverSight/skills_feed

vercel-react-native-skills

Comprehensive best practices for React Native and Expo applications. Contains rules across multiple categories covering performance, animations, UI patterns, and platform-specific optimizations.

215 0
View

Popular AI tools

Kaiber logo
Video

Kaiber

Generate, edit, and beat-sync AI video with leading models in one workspace.

Paid
View
Vimcal logo
Productivity

Vimcal

The world's fastest calendar for remote work

Free
View

Transform Your Design with AI Designer by ImgCreator.ai

Freemium
View
Akool AI logo
Content & writing

Akool AI

Revolutionizing Video Production with AI-Powered Creativity

Paid
View

Extend an image past the frame and let AI fill the new aspect ratio.

Freemium
View
StarByFace logo
Security

StarByFace

Discover your celebrity doppelgänger with StarByFace!

Free
View
C

ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.

Freemium
View
Opus Clip logo
Coding & apps

Opus Clip

Opus.ai: Revolutionize Your Web Experience

Free
View