Skip to content
This repository was archived by the owner on Jul 14, 2025. It is now read-only.

Enhanced Twitter/X plugin with RICH conversation context, enabling automated posting and context-aware responses

License

Notifications You must be signed in to change notification settings

gnomonprime/plugin-twitter-fork13

Β 
Β 

Repository files navigation

Eliza Twitter/X Client

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.

Features

  • πŸ”„ 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

Architecture Overview

The client implements a smart hybrid approach that maximizes both feature availability and reliability:

🎯 GraphQL-First Strategy

  • 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

πŸ”„ Intelligent API v2 Fallback

  • 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

πŸ”§ Unified Interface & Data Normalization

  • 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

Setup Guide

Prerequisites

  • A Twitter/X account
  • Node.js and bun installed
  • Twitter API credentials (recommended for API v2 fallback)

Step 1: Configure Environment Variables

Create or edit .env file in your project root.

Authentication Methods

The Twitter client supports three authentication methods with intelligent hybrid routing:

πŸ₯‡ Method 1: Manual Cookie Injection (RECOMMENDED)

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 GraphQL

Benefits:

  • βœ… 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

πŸ₯ˆ Method 2: Username/Password (Automatic Cookie-Based Login)

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 GraphQL

Note: May encounter login challenges (2FA, captcha, rate limiting) but automatically obtains session cookies for GraphQL access.

πŸ₯‰ Method 3: Twitter API v2 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

Note: Limited to API v2 endpoints only - no GraphQL features like advanced search or DMs.

πŸ”‘ How to Get Required Tokens

Bearer Token (REQUIRED for GraphQL):

  1. Twitter Developer Portal: Create a Twitter app and use the Bearer Token from your app credentials
  2. Browser Extraction: Use browser developer tools to capture the bearer token from Twitter web requests

Twitter Cookies (For Method 1):

  1. Open Twitter in your browser and log in
  2. Open Developer Tools (F12 or right-click β†’ Inspect)
  3. Go to Application/Storage β†’ Cookies β†’ https://twitter.com
  4. Copy cookie values:
    • auth_token β†’ TWITTER_COOKIES_AUTH_TOKEN
    • ct0 β†’ TWITTER_COOKIES_CT0
    • guest_id β†’ TWITTER_COOKIES_GUEST_ID

Twitter API Credentials (For Method 3 or fallback):

  1. Go to https://developer.twitter.com/en/portal/dashboard
  2. Create a new app or use an existing one
  3. Navigate to "Keys and tokens"
  4. Generate/copy API credentials

βš™οΈ Configuration Options

# === 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)

Step 2: Initialize the Client

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);

Core Features

πŸ€– Autonomous Posting

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

πŸ“Š Timeline Monitoring

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

πŸ’¬ Interaction Handling

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

πŸ” Search and Discovery

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

πŸ›‘οΈ Authentication & Security

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

Configuration Deep Dive

Timeline Algorithms

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

Target User Configuration

# 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=*

Interval Configuration with Variance

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

Development & Testing

Testing

# 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

Monitoring & Debugging

# Enable detailed logging
LOG_LEVEL=debug

# Monitor hybrid API usage
DEBUG=twitter:* bun start

# Check authentication status
DEBUG=twitter:auth bun start

Troubleshooting

Authentication Issues

Cookie 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

Rate Limiting

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_LIMIT if 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

No Interactions

Common causes and solutions:

  • βœ… Verify TWITTER_SEARCH_ENABLE=true
  • βœ… Check TWITTER_TARGET_USERS configuration
  • βœ… Ensure the timeline contains relevant content
  • βœ… Review TWITTER_MAX_INTERACTIONS_PER_RUN setting
  • βœ… Verify at least one authentication method is working
  • βœ… Check logs for authentication and API errors

Timeline Issues

Optimization strategies:

  • βœ… Try switching between "weighted" and "latest" algorithms
  • βœ… Adjust timeline weight parameters for better relevance
  • βœ… Check TWITTER_POLL_INTERVAL for timeline refresh rate
  • βœ… Verify hybrid access (GraphQL provides richer timeline data)
  • βœ… Monitor cache performance and clear if needed

Security Best Practices

  • πŸ”’ Store credentials securely in environment variables, never in code
  • πŸ”’ Use .env.local or 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

Stealth & Anti-Detection Best Practices

πŸ•΅οΈ Authentication Strategy

  • 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)

⏱️ Timing & Rate Limits

  • Enable Variance: Use TWITTER_POST_INTERVAL_VARIANCE=0.3 for 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

🎭 Behavioral Patterns

  • 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

πŸ”§ Technical Measures

  • 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

API Usage & Rate Limits

This plugin intelligently uses both Twitter GraphQL and API v2 endpoints:

GraphQL Endpoints (Primary - when cookie auth available)

  • 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

API v2 Endpoints (Fallback - always available)

  • 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

Rate Limit Strategy

  • 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.

Architecture Benefits

πŸš€ Performance & Reliability

  • 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

πŸ”§ Developer Experience

  • 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

πŸ“ˆ Scalability & Future-Proofing

  • 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

Support & Community

For issues, questions, or contributions:

  1. Check Documentation: Review this README and inline code documentation
  2. Enable Debug Logging: Use LOG_LEVEL=debug for detailed troubleshooting
  3. Verify Configuration: Ensure authentication methods are properly configured
  4. Check API Status: Monitor Twitter API v2 status and GraphQL availability
  5. 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

Contributing

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.

About

Enhanced Twitter/X plugin with RICH conversation context, enabling automated posting and context-aware responses

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • TypeScript 100.0%