Building an Autonomous Grok Twitter Bot with X API v2
This article was produced with AI assistance. Editorial standards apply.
AI Edited Last updated: 26 August 2026
Key takeaways
- A Grok Twitter bot is a pipeline: X API v2 filtered stream in, Grok score/draft, then a gated
create_tweetwrite. - xAI documents a first-party X Search tool for keyword and thread fetch; posting still requires your OAuth app.
- Pay-per-use X API pricing is now the default developer path — budget stream reads separately from model tokens.
- Never auto-reply from untrusted tweet text without a dry-run preview of the outbound post.
Building an autonomous Grok Twitter bot means pairing the xAI API with Twitter API v2 so the agent can score inbound posts and dispatch replies without a human typing every tweet.
However, deploying an autonomous bot on X requires strict adherence to Twitter’s automation policies, rate limit handling, and content moderation safeguards.
Architecture of an autonomous X agent {#architecture}

The autonomous pipeline operates in 4 distinct phases:
- Filtered Stream Ingestion: Connects to Twitter API v2 Filtered Stream (
GET /2/tweets/search/stream) matching targeted industry keywords. Rules are managed onPOST /2/tweets/search/stream/rules(optionaldry_run=trueto validate a rule without committing). - Relevance & Sentiment Scoring: Grok scores each incoming tweet on relevance (0–100), sentiment, and audience resonance.
- Contextual Draft Generation: If the relevance score exceeds 85, Grok drafts a value-additive reply.
- Rate Limit Sentinel & Dispatch: Dispatches the tweet via the OAuth 1.0a / OAuth 2.0 User Context endpoint within strict rate boundaries.
For pre-trained social agents, check our grok marketing agent directory for automated campaign managers, SEO brief generators, and ad pacing trackers.
xAI’s built-in X Search tool is a read path (keyword search, handles, date range, thread fetch). A posting bot still needs your own function that calls create_tweet after a preview.
Implementing the filtered stream and Grok ingestion pipeline {#filtered-stream}
Use xAI function calling for the draft/dispatch split: the model returns a tool_call; you execute the X write.
import os
import tweepy
import aiohttp
import asyncio
BEARER_TOKEN = os.environ["TWITTER_BEARER_TOKEN"]
API_KEY = os.environ["TWITTER_API_KEY"]
API_SECRET = os.environ["TWITTER_API_SECRET"]
ACCESS_TOKEN = os.environ["TWITTER_ACCESS_TOKEN"]
ACCESS_SECRET = os.environ["TWITTER_ACCESS_SECRET"]
XAI_KEY = os.environ["XAI_API_KEY"]
client = tweepy.Client(
bearer_token=BEARER_TOKEN,
consumer_key=API_KEY,
consumer_secret=API_SECRET,
access_token=ACCESS_TOKEN,
access_token_secret=ACCESS_SECRET
)
async def evaluate_and_reply(tweet_id: str, tweet_text: str, author_username: str):
async with aiohttp.ClientSession() as session:
headers = {"Authorization": f"Bearer {XAI_KEY}", "Content-Type": "application/json"}
prompt = f"Evaluate this tweet from @{author_username}: '{tweet_text}'. If insightful, draft a 1-sentence value-add reply. Format as JSON: {{'should_reply': true/false, 'reply': '...'}}"
payload = {
"model": "grok-beta",
"messages": [{"role": "user", "content": prompt}],
"response_format": {"type": "json_object"}
}
async with session.post("https://api.x.ai/v1/chat/completions", json=payload, headers=headers) as resp:
if resp.status == 200:
result = await resp.json()
import json
decision = json.loads(result["choices"][0]["message"]["content"])
if decision.get("should_reply") and decision.get("reply"):
client.create_tweet(in_reply_to_tweet_id=tweet_id, text=decision["reply"])
Treat inbound tweet_text as untrusted. A prompt-injection payload in a mention should not become a live post. Preview the outbound text the same way CRM mutations use two-phase dry-run.
Open the marketing directory →
Rate limit defense and enterprise safety matrix {#rate-limits}

To protect your account from shadowbans or API suspension, integrate our viral tweet scout agent to filter high-probability engagement windows, and track performance using our ad pacing digest agent.
Recommended automation limits
- Maximum automated replies: 15 per hour (staggered with 180s+ random jitters).
- Maximum original posts: 4 per day.
- Zero generic engagement phrases (“Great post!”, “Check this out!”). Every response must synthesize unique technical substance.
X API cost and operator disclosure {#x-api-cost}
@XDevelopers announced the public X API Pay-Per-Use model for indie builders and startups, with legacy Free users moving onto prepaid credits (permalink, 6 Feb 2026). A later update (12 Aug 2026) said legacy Basic plans migrate to Pay-Per-Use after 1 June 2026. Budget filtered-stream reads as a separate line from Grok tokens.
Marketing inventory for social agents {#marketing-inventory}
Verified social/SEO routines live on the marketing hub. Adjacent business automation (deal desk, lead enrich) is catalogued under sales and the Grok bot for business workflows guide.
FAQ {#faq}
What X endpoint does a Grok Twitter bot listen on?
The v2 filtered stream: GET https://api.x.com/2/tweets/search/stream, with rules on /2/tweets/search/stream/rules.
Is xAI X Search enough to post replies?
No. X Search is a server-side read tool. Posting requires your app’s user-context write and a function you execute locally.
How do I keep the bot from spam-replying?
Cap hourly replies, require a relevance threshold, and human-approve the first week of commits. Treat every inbound tweet as untrusted text.