Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Twitter Stream Api Laravel Package

redwebcreation/twitter-stream-api

Laravel-friendly PHP wrapper for Twitter’s Streaming API. Authenticate with OAuth and open filtered streams to receive tweets/events in real time, with simple configuration and callbacks for handling incoming data—ideal for building live feeds, monitors, and bots.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require redwebcreation/twitter-stream-api
    

    Ensure your project has PHP ≥ 8.0 and Laravel ≥ 8.0.

  2. Configuration

    • Publish the config file:
      php artisan vendor:publish --provider="RedWebCreation\TwitterStreamApi\TwitterStreamApiServiceProvider"
      
    • Update config/twitter-stream-api.php with your Twitter API Bearer Token (from Twitter Developer Portal).
  3. First Use Case: Basic Stream

    use RedWebCreation\TwitterStreamApi\Facades\TwitterStream;
    
    $stream = TwitterStream::filter(['track' => 'laravel']);
    $stream->on('tweet', function ($tweet) {
        // Process tweet in real-time
        dd($tweet->text);
    });
    

Implementation Patterns

Common Workflows

  1. Filtering Streams

    • Track keywords, follow users, or filter by location:
      $stream = TwitterStream::filter([
          'track' => 'php,laravel',
          'follow' => '1234567', // User ID
          'locations' => '-122.75,36.8,-121.75,37.8' // Bounding box
      ]);
      
  2. Handling Events

    • Subscribe to multiple event types (e.g., tweet, limit, disconnect):
      $stream->on('tweet', fn($tweet) => logger()->info($tweet->text));
      $stream->on('limit', fn() => logger()->warning('Rate limit exceeded!'));
      
  3. Long-Running Streams

    • Use Laravel Queues to process tweets asynchronously:
      $stream->on('tweet', fn($tweet) => dispatch(new ProcessTweet($tweet)));
      
  4. Reconnecting on Disconnect

    • Automatically retry failed connections:
      $stream->retryOnDisconnect(3); // Retry 3 times
      

Integration Tips

  • Laravel Events: Dispatch custom events for tweets:
    $stream->on('tweet', fn($tweet) => event(new TweetReceived($tweet)));
    
  • Database Storage: Use Eloquent models to store tweets:
    $stream->on('tweet', fn($tweet) => Tweet::create($tweet->toArray()));
    
  • Rate Limiting: Monitor limit events to adjust stream rules dynamically.

Gotchas and Tips

Pitfalls

  1. Bearer Token Expiry

    • Ensure your token hasn’t expired (check Twitter Developer Portal).
    • Fix: Regenerate the token and update config/twitter-stream-api.php.
  2. Rate Limits

    • Twitter enforces strict rate limits. Handle limit events gracefully:
      $stream->on('limit', fn() => sleep(60)); // Wait before reconnecting
      
  3. Connection Drops

    • Network issues or Twitter API downtime may disconnect streams. Use retryOnDisconnect() or implement a watchdog service.
  4. Data Parsing

    • Tweets may contain nested objects (e.g., entities, user). Use json_decode() or Laravel’s collect() for deep inspection:
      $entities = collect($tweet->entities)->toJson();
      

Debugging

  • Enable Logging Set debug to true in config/twitter-stream-api.php to log raw API responses.
  • Check HTTP Headers Verify the Authorization: Bearer {token} header is included in requests (use Laravel’s tap() for debugging):
    $stream->getClient()->tap(fn($client) => logger()->debug($client->getHeaders()));
    

Extension Points

  1. Custom HTTP Client Override the default Guzzle client:

    TwitterStream::setClient(app()->makeWith(\GuzzleHttp\Client::class, [
        'timeout' => 30,
        'headers' => ['User-Agent' => 'MyApp/1.0']
    ]));
    
  2. Event Modifiers Transform tweet data before processing:

    $stream->on('tweet', fn($tweet) => $stream->emit('processed_tweet', $this->sanitizeTweet($tweet)));
    
  3. Rule Management Dynamically update stream rules at runtime:

    $stream->addRules(['track' => 'new_keyword']); // Requires API v2 rules endpoint
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky