This package provides Twitter/X integration for the Eliza AI agent using a comprehensive hybrid GraphQL + Twitter API v2 approach for maximum compatibility, reliability, and feature coverage.
- π Complete Hybrid Architecture: Seamlessly combines Twitter's GraphQL API (preferred) with official Twitter API v2 (fallback) across ALL operations
- π€ Autonomous Operations: Tweet posting, timeline monitoring, mention handling, and automated interactions
- π Advanced Search & Discovery: Hybrid search with enhanced GraphQL capabilities and reliable API v2 fallback
- π¬ Full Communication Support: Direct messages, mentions, replies, quotes, and retweets
- β‘ Smart Timeline Processing: Weighted algorithms with real-time GraphQL data and API v2 reliability
- π‘οΈ Robust Authentication: Multiple authentication methods with automatic failover
- π Comprehensive Analytics: Enhanced data from GraphQL with API v2 backup coverage
- π― Intelligent Targeting: Configurable user targeting with wildcard support
- πΎ Advanced Caching: Efficient caching system optimized for both API sources
- π΅οΈ Advanced Stealth Features: X-Client-Transaction-ID generation, browser fingerprinting, and human-like behavior patterns
The client implements a smart hybrid approach that maximizes both feature availability and reliability:
- Primary API: Uses Twitter's internal GraphQL endpoints when cookie-based authentication is available
- Enhanced Features: Access to all Twitter capabilities including advanced search, DMs, real-time data, and richer data
- Performance: Faster response times with more complete and structured data
- Compatibility: Uses the same APIs as the official Twitter web interface
- Automatic Failover: Seamlessly switches to official Twitter API v2 when GraphQL is unavailable
- Guaranteed Reliability: Ensures service continuity with Twitter's officially supported API
- Standard Operations: Maintains all core functionality including posting, timeline access, and user interactions
- Rate Limit Distribution: Separate rate limits help avoid service interruption
- Transparent Operation: Both APIs return consistent, normalized data structures
- Zero Code Changes: Applications work identically regardless of which API is used
- Enhanced Parsing: Comprehensive fallback logic ensures data completeness
- Service Compatibility: All response structures are normalized for consuming services
- A Twitter/X account
- Node.js and bun installed
- Twitter API credentials (recommended for API v2 fallback)
Create or edit .env file in your project root.
The Twitter client supports three authentication methods with intelligent hybrid routing:
Most reliable - bypasses login complications entirely
# Extract these from your browser when logged into Twitter:
TWITTER_COOKIES_AUTH_TOKEN= # auth_token cookie value
TWITTER_COOKIES_CT0= # ct0 cookie value (CSRF token)
TWITTER_COOKIES_GUEST_ID= # guest_id cookie value
TWITTER_BEARER_TOKEN=your_bearer_token # REQUIRED: Custom bearer token for GraphQLBenefits:
- β Bypasses 2FA, captcha, and login rate limiting
- β Most reliable authentication method
- β Full GraphQL access with all advanced features
- β No login attempts that could trigger security measures
TWITTER_USERNAME=your_username
TWITTER_PASSWORD=your_password
TWITTER_EMAIL=your_email@example.com # Required if 2FA is enabled
TWITTER_BEARER_TOKEN=your_bearer_token # REQUIRED: Custom bearer token for GraphQLNote: May encounter login challenges (2FA, captcha, rate limiting) but automatically obtains session cookies for GraphQL access.
TWITTER_API_KEY= # Twitter API Key
TWITTER_API_SECRET_KEY= # Twitter API Secret Key
TWITTER_ACCESS_TOKEN= # Access Token for Twitter API v2
TWITTER_ACCESS_TOKEN_SECRET= # Access Token Secret for Twitter API v2Note: Limited to API v2 endpoints only - no GraphQL features like advanced search or DMs.
Bearer Token (REQUIRED for GraphQL):
- Twitter Developer Portal: Create a Twitter app and use the Bearer Token from your app credentials
- Browser Extraction: Use browser developer tools to capture the bearer token from Twitter web requests
Twitter Cookies (For Method 1):
- Open Twitter in your browser and log in
- Open Developer Tools (F12 or right-click β Inspect)
- Go to Application/Storage β Cookies β https://twitter.com
- Copy cookie values:
auth_tokenβTWITTER_COOKIES_AUTH_TOKENct0βTWITTER_COOKIES_CT0guest_idβTWITTER_COOKIES_GUEST_ID
Twitter API Credentials (For Method 3 or fallback):
- Go to https://developer.twitter.com/en/portal/dashboard
- Create a new app or use an existing one
- Navigate to "Keys and tokens"
- Generate/copy API credentials
# === AUTHENTICATION ===
# Option 1: Manual Cookie Injection (RECOMMENDED - bypasses login)
TWITTER_COOKIES_AUTH_TOKEN= # auth_token cookie value
TWITTER_COOKIES_CT0= # ct0 cookie value (CSRF token)
TWITTER_COOKIES_GUEST_ID= # guest_id cookie value
TWITTER_BEARER_TOKEN=your_bearer_token # RECOMMENDED: Custom bearer token for GraphQL (no default fallback)
# Option 2: Username/Password Authentication (automatic cookie-based login)
TWITTER_USERNAME=your_username
TWITTER_PASSWORD=your_password
TWITTER_EMAIL=your_email@example.com
# Option 3: Twitter API v2 Credentials (API v2 endpoints only)
TWITTER_API_KEY= # Twitter API Key
TWITTER_API_SECRET_KEY= # Twitter API Secret Key
TWITTER_ACCESS_TOKEN= # Access Token for Twitter API v2
TWITTER_ACCESS_TOKEN_SECRET= # Access Token Secret for Twitter API v2
# === CORE SETTINGS ===
TWITTER_DRY_RUN=false # Set to true for testing without posting
TWITTER_TARGET_USERS= # Comma-separated usernames (use "*" for all)
TWITTER_RETRY_LIMIT=5 # Maximum retry attempts for failed operations
TWITTER_POLL_INTERVAL=120 # Timeline polling interval (seconds)
# === AUTONOMOUS POSTING ===
TWITTER_POST_ENABLE=false # Enable autonomous tweet posting
TWITTER_POST_INTERVAL_MIN=90 # Minimum interval between posts (minutes)
TWITTER_POST_INTERVAL_MAX=180 # Maximum interval between posts (minutes)
TWITTER_POST_IMMEDIATELY=false # Skip intervals and post immediately
TWITTER_POST_INTERVAL_VARIANCE=0.2 # Random variance factor for posting intervals
# === INTERACTION HANDLING ===
TWITTER_SEARCH_ENABLE=true # Enable timeline monitoring and interactions
TWITTER_INTERACTION_INTERVAL_MIN=15 # Minimum interval between interactions (minutes)
TWITTER_INTERACTION_INTERVAL_MAX=30 # Maximum interval between interactions (minutes)
TWITTER_INTERACTION_INTERVAL_VARIANCE=0.3 # Random variance for interaction intervals
TWITTER_AUTO_RESPOND_MENTIONS=true # Automatically respond to mentions
TWITTER_AUTO_RESPOND_REPLIES=true # Automatically respond to replies
TWITTER_MAX_INTERACTIONS_PER_RUN=10 # Maximum interactions processed per cycle
# === TIMELINE ALGORITHM ===
TWITTER_TIMELINE_MODE= # 'following' or 'foryou' (empty for default)
TWITTER_TIMELINE_ALGORITHM=weighted # Algorithm: "weighted" or "latest"
TWITTER_TIMELINE_USER_BASED_WEIGHT=3 # Weight for user-based scoring
TWITTER_TIMELINE_TIME_BASED_WEIGHT=2 # Weight for time-based scoring
TWITTER_TIMELINE_RELEVANCE_WEIGHT=5 # Weight for relevance scoring
# === ADVANCED FEATURES ===
TWITTER_MAX_TWEET_LENGTH=4000 # Maximum tweet length (for threads)
TWITTER_DM_ONLY=false # Only interact via direct messages
TWITTER_ENABLE_ACTION_PROCESSING=false # Enable timeline action processing
TWITTER_ACTION_INTERVAL=240 # Action processing interval (minutes)import { TwitterClientInterface } from "@gnomonprime/plugin-twitter-fork13";
const twitterPlugin = {
name: "twitter",
description: "Hybrid Twitter/X Client",
services: [TwitterService],
};
// Register with your Eliza runtime
runtime.registerPlugin(twitterPlugin);When TWITTER_POST_ENABLE=true, the client automatically generates and posts tweets:
- Hybrid Posting: Uses GraphQL when available, falls back to API v2
- Smart Intervals: Configurable posting intervals with randomization
- Long-Form Support: Supports tweets up to 4000 characters with automatic threading
- Media Support: Image and video uploads via GraphQL (API v2 support planned)
- Dry-Run Mode: Test tweet generation without actually posting
Advanced timeline processing with hybrid data sources:
- Enhanced GraphQL Data: Richer tweet information and metadata when available
- Reliable API v2 Fallback: Ensures timeline access even without GraphQL
- Smart Algorithms:
- Weighted: Scores tweets based on user relationships, time, and relevance
- Latest: Processes tweets in chronological order
- Efficient Caching: Avoids duplicate processing with intelligent cache management
- Configurable Limits: Control interaction frequency and volume
Comprehensive interaction management with hybrid approach:
- Mentions: Responds to tweets mentioning the bot (GraphQL preferred, API v2 fallback)
- Replies: Handles replies to the bot's tweets with context awareness
- Direct Messages: Pure GraphQL implementation with full group chat support, including DMInboxTimeline, DMConversationTimeline, and SendDMMessage endpoints
- Quotes & Retweets: Complete social interaction support
- Target Users: Configurable user targeting with wildcard support
- Event System: Rich event emission for custom handling
Advanced search capabilities:
- Hybrid Search: GraphQL for advanced search features, API v2 for reliability
- Real-Time Monitoring: Timeline-based search and interaction
- Smart Filtering: Relevance-based filtering with configurable parameters
- User Targeting: Precise user targeting with pattern matching
- Trend Analysis: Access to trending topics and popular content
Multi-layered authentication system:
- Cookie-Based Auth: Preferred method for GraphQL access (most stealth)
- API v2 Credentials: Reliable fallback for official API access
- Automatic Failover: Seamless switching between authentication methods
- Token Management: Secure handling of bearer tokens and session cookies
- Rate Limit Management: Intelligent rate limiting across both API systems
- Anti-Detection: X-Client-Transaction-ID generation, browser fingerprinting, request timing variance
- Human-like Patterns: Natural activity cycles, typing delays, and interaction patterns
Weighted Algorithm (Recommended):
TWITTER_TIMELINE_ALGORITHM=weighted
TWITTER_TIMELINE_USER_BASED_WEIGHT=3 # Higher = prioritize known users
TWITTER_TIMELINE_TIME_BASED_WEIGHT=2 # Higher = prioritize recent content
TWITTER_TIMELINE_RELEVANCE_WEIGHT=5 # Higher = prioritize relevant content- Combines user relationship, time, and relevance scores
- Prioritizes tweets from important users and relevant content
- Enhanced with rich GraphQL metadata when available
Latest Algorithm:
TWITTER_TIMELINE_ALGORITHM=latest- Processes tweets in chronological order
- Simpler, more predictable behavior
- Good for high-volume timelines and real-time monitoring
# Interact with everyone (default)
TWITTER_TARGET_USERS=
# Interact with specific users only
TWITTER_TARGET_USERS=user1,user2,user3
# Interact with everyone (explicit wildcard)
TWITTER_TARGET_USERS=*All intervals support variance for natural, human-like behavior:
# Base interval: 90-180 minutes
TWITTER_POST_INTERVAL_MIN=90
TWITTER_POST_INTERVAL_MAX=180
# With 20% variance: actual range ~72-216 minutes
TWITTER_POST_INTERVAL_VARIANCE=0.2# Run tests
bun test
# Run with debug logging
DEBUG=eliza:* bun start
# Test without posting (safe mode)
TWITTER_DRY_RUN=true bun start
# Test specific components
TWITTER_POST_ENABLE=false TWITTER_SEARCH_ENABLE=true bun start# Enable detailed logging
LOG_LEVEL=debug
# Monitor hybrid API usage
DEBUG=twitter:* bun start
# Check authentication status
DEBUG=twitter:auth bun startCookie Authentication Problems:
- β Verify username/password are correct and account isn't locked
- β Check for 2FA requirements (provide email if enabled)
- β Ensure cookies are current (re-extract if old)
- β Verify bearer token is valid
API v2 Authentication Problems:
- β Verify all four API credentials are correctly set
- β Check that Access Token permissions match your use case
- β Ensure your developer account is in good standing
- β Verify your Twitter app has appropriate access levels
Hybrid Fallback Issues:
- β Check logs for "falling back to API v2" messages
- β Verify both authentication methods are properly configured
- β Monitor which operations are using GraphQL vs API v2
- β Ensure bearer token is set for GraphQL functionality
The client includes sophisticated rate limiting for both APIs:
- Hybrid Advantage: GraphQL and API v2 have separate rate limits
- Smart Distribution: Load is distributed across different API systems
- Automatic Backoff: Built-in exponential backoff for both APIs
- Monitoring: Track rate limit status in logs
If experiencing rate limits:
- β
Adjust
TWITTER_RETRY_LIMITif experiencing frequent failures - β Increase polling intervals for high-volume accounts
- β Consider using custom bearer token for higher limits
- β Monitor API usage in Twitter Developer Portal
Common causes and solutions:
- β
Verify
TWITTER_SEARCH_ENABLE=true - β
Check
TWITTER_TARGET_USERSconfiguration - β Ensure the timeline contains relevant content
- β
Review
TWITTER_MAX_INTERACTIONS_PER_RUNsetting - β Verify at least one authentication method is working
- β Check logs for authentication and API errors
Optimization strategies:
- β Try switching between "weighted" and "latest" algorithms
- β Adjust timeline weight parameters for better relevance
- β
Check
TWITTER_POLL_INTERVALfor timeline refresh rate - β Verify hybrid access (GraphQL provides richer timeline data)
- β Monitor cache performance and clear if needed
- π Store credentials securely in environment variables, never in code
- π Use
.env.localor similar for local development - π Regularly rotate API keys and tokens
- π Monitor API usage in Twitter Developer Portal
- π Enable only necessary permissions for Access Tokens
- π Set custom bearer token for GraphQL functionality (no default provided)
- π Be cautious with cookie-based auth in shared environments
- π Use HTTPS for all webhook endpoints if applicable
- Prefer Cookie-Based Auth: Most human-like, bypasses login detection
- Extract Fresh Cookies: Use browser DevTools when logged in normally
- Avoid Frequent Logins: Each login increases detection risk
- Use Multiple Accounts: Distribute activity across accounts (future feature)
- Enable Variance: Use
TWITTER_POST_INTERVAL_VARIANCE=0.3for natural timing - Respect Rate Limits: Stay well below Twitter's official limits
- Add Human Delays: Natural pauses between actions (built-in)
- Activity Cycles: Lower activity during off-hours
- Mix Content Types: Vary between tweets, replies, and retweets
- Natural Engagement: Like before replying, view before following
- Avoid Patterns: Don't tweet at exact intervals or with similar content
- Error Handling: Don't retry immediately on failures
- X-Client-Transaction-ID: Automatically generated for each request
- Browser Fingerprinting: Realistic headers and user agents
- Cookie Management: Proper session handling
- Request Ordering: Headers sent in browser-like order
This plugin intelligently uses both Twitter GraphQL and API v2 endpoints:
- Timeline Operations: Rich home timeline and user tweet data with enhanced metadata
- Tweet Operations: Full posting, fetching, and interaction capabilities
- User Operations: Complete profile information and relationship data
- Search Operations: Advanced search with sophisticated filtering
- Direct Messages: Pure GraphQL implementation with full group chat support (DMInboxTimeline, DMConversationTimeline, SendDMMessage)
- Real-time Features: Live timeline updates and notifications
- Timeline Operations: Standard home timeline and user tweet access
- Tweet Operations: Basic posting, fetching, and interaction support
- User Operations: Standard profile and relationship information
- Search Operations: Basic content discovery and user search
- Direct Messages: Limited to v1.1 REST endpoints (basic functionality only)
- Limited Features: Reduced functionality but guaranteed availability
- Separate Limits: GraphQL and API v2 have independent rate limits
- Load Distribution: Requests are spread across both systems
- Smart Routing: Operations use the most appropriate API
- Automatic Management: Built-in rate limit handling and backoff
Monitor your API usage in the Twitter Developer Portal. The hybrid approach helps distribute load and provides redundancy when limits are reached.
- Faster GraphQL responses with comprehensive API v2 backup
- Zero single points of failure - if one API fails, the other continues
- Enhanced data quality from GraphQL with guaranteed availability from API v2
- Intelligent caching optimized for both API response types
- Unified interface - same code works with both APIs
- Automatic failover - no manual intervention required
- Comprehensive logging - full visibility into hybrid operations
- Consistent data structures - normalized responses regardless of source
- Rate limit distribution across multiple API systems
- Feature availability - access to latest GraphQL features with API v2 stability
- Graceful degradation - maintains functionality even with partial API access
- Easy maintenance - centralized hybrid logic with clear separation of concerns
For issues, questions, or contributions:
- Check Documentation: Review this README and inline code documentation
- Enable Debug Logging: Use
LOG_LEVEL=debugfor detailed troubleshooting - Verify Configuration: Ensure authentication methods are properly configured
- Check API Status: Monitor Twitter API v2 status and GraphQL availability
- Open Issues: Provide detailed information including:
- Error messages and logs (including hybrid fallback attempts)
- Configuration details (without credentials)
- Steps to reproduce the issue
- Expected vs actual behavior
We welcome contributions! Please:
- Follow the existing hybrid architecture patterns
- Add tests for new functionality
- Update documentation for any changes
- Ensure backward compatibility
- Test both GraphQL and API v2 code paths
Built with π§‘ for the Eliza AI ecosystem
Providing reliable, feature-rich Twitter integration through intelligent hybrid architecture.