PHPackages                             redwebcreation/twitter-stream-api - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. redwebcreation/twitter-stream-api

ActiveLibrary[API Development](/categories/api)

redwebcreation/twitter-stream-api
=================================

Consume the Twitter Stream API in real-time.

2.2.1(2y ago)3220.3k↓40%9[2 issues](https://github.com/felixdorn/twitter-stream-api/issues)1MITPHPPHP ^8.1

Since May 7Pushed 2y ago2 watchersCompare

[ Source](https://github.com/felixdorn/twitter-stream-api)[ Packagist](https://packagist.org/packages/redwebcreation/twitter-stream-api)[ Docs](https://github.com/redwebcreation/phirehose)[ RSS](/packages/redwebcreation-twitter-stream-api/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (10)Dependencies (8)Versions (19)Used By (1)

Twitter Stream API (v2)
=======================

[](#twitter-stream-api-v2)

[![Tests](https://github.com/redwebcreation/twitter-stream-api/actions/workflows/tests.yml/badge.svg?branch=master)](https://github.com/redwebcreation/twitter-stream-api/actions/workflows/tests.yml)[![Formats](https://github.com/redwebcreation/twitter-stream-api/actions/workflows/formats.yml/badge.svg?branch=master)](https://github.com/redwebcreation/twitter-stream-api/actions/workflows/formats.yml)[![Version](https://camo.githubusercontent.com/486b386bbb9634706fffd6d4903a8b22ed1b3398616dbd13775cdfc0e157ed70/68747470733a2f2f706f7365722e707567782e6f72672f7265647765626372656174696f6e2f747769747465722d73747265616d2d6170692f76657273696f6e)](//packagist.org/packages/redwebcreation/twitter-stream-api)[![Total Downloads](https://camo.githubusercontent.com/454f7b96126a3735c5c2d8f7a5250be091819f89ce8694889fbd18a546ac7672/68747470733a2f2f706f7365722e707567782e6f72672f7265647765626372656174696f6e2f747769747465722d73747265616d2d6170692f646f776e6c6f616473)](//packagist.org/packages/redwebcreation/twitter-stream-api)[![codecov](https://camo.githubusercontent.com/5e1a2a235a3e16fb9648c171fec14fac200e89b6dbeb0f75f68bf88fa377158e/68747470733a2f2f636f6465636f762e696f2f67682f66656c6978646f726e2f747769747465722d73747265616d2d6170692f6272616e63682f6d61696e2f67726170682f62616467652e7376673f746f6b656e3d30624238306c33486774)](https://codecov.io/gh/felixdorn/twitter-stream-api)

Consume the Twitter Stream API v2 in real-time.

This package is the spiritual successor of `fennb/phirehose`. It also uses some of `salsify/jsonstreamingparser` and `maxakawizard/json-collection-parser`.

Getting started
---------------

[](#getting-started)

You need an approved developer account. If you don't have one, [apply here](https://developer.twitter.com/en/docs/twitter-api/getting-started/getting-access-to-the-twitter-api). Once you are in, create an "Application" in the Developer Portal and generate a new bearer token.

> Requires [PHP 8.1+](https://www.php.net/releases/)

You can install the package via composer:

```
composer require redwebcreation/twitter-stream-api
```

Then, create a connection:

```
$connection = new \Felix\TwitterStream\TwitterConnection(
    bearerToken: '...' # the one you got from the Developer Portal
);
```

Usage
-----

[](#usage)

### Streams

[](#streams)

- [\\Felix\\TwitterStream\\Streams\\VolumeStream](src/Streams/VolumeStream.php)
- [\\Felix\\TwitterStream\\Streams\\FilteredStream](src/Streams/FilteredStream.php)

### Creating a stream

[](#creating-a-stream)

```
$stream = new \Felix\TwitterStream\Streams\VolumeStream();
// or
$stream = new \Felix\TwitterStream\Streams\FilteredStream();
```

### Configuring a stream

[](#configuring-a-stream)

- `withTweetLimit(int)` - Limit the number of tweets a connection should process ```
    $stream->withTweetLimit(100_000);
    ```
- `fields(string[])` - See [Fields](#fields)
- `expansions(...string)` - See [Expansions](#expansions)

#### For advanced use

[](#for-advanced-use)

- `withBufferSize(int = 85)` - How many bytes should the parser store before trying to parse the JSON, on very high-volume streams, using a larger buffer size is recommended (2500, 10000, depending on the volume). Setting to a big value &gt; 2000 on a low-volume stream would result in 0 tweets being processed until there are enough tweets in the buffer.

### Interacting with a stream

[](#interacting-with-a-stream)

- `stopListening()` - Stops listening to the stream.
- `createdAt(): int` - The UNIX timestamp at which you started listening
- `timeElapsedInSeconds(): int` - How much time passed since you started listening
- `tweetsReceived(): int` - How much the stream sent

#### For advanced use

[](#for-advanced-use-1)

- `response(): Psr\Http\Message\ResponseInterface` - The response sent by Twitter

### Listening to a stream

[](#listening-to-a-stream)

```
$stream->listen($connection, function (object $tweet) {
    echo $tweet->data->text . PHP_EOL;
});
```

Filtering the stream
--------------------

[](#filtering-the-stream)

**This part only applies if you're interested in the *filtered stream*.**

### Building a rule

[](#building-a-rule)

> Note, If you change your rules while connected to the stream, Twitter will use the new rules immediately.

#### Save, read and delete rules

[](#save-read-and-delete-rules)

> You can not update rules.

```
use Felix\TwitterStream\Rule\RuleManager;

$rule = new RuleManager($connection);
```

Let's create a rule:

```
$rule->save(
	# tweets must contain the word cat and have at least one image
	"cat has:images",
	"images of cats"
);
```

You may now retrieve your newly saved rule:

```
$rule->all();
```

Which returns an array of `Felix\TwitterStream\Rule\Rule`:

```
[
	0 => Felix\TwitterStream\Rule\Rule{
		+value: "cat has:images",
		+tag: "images of cats",
		+id: "4567654567654567654"
	}
]
```

> Note, the `Felix\TwitterStream\Rule\Rule` is merely a Data Object, it does not contain any method.

To delete the rule pass its ID to the `delete` method:

```
$rule->delete('4567654567654567654');
```

##### Batch Processing

[](#batch-processing)

To save many rules at once:

```
use Felix\TwitterStream\Rule\Rule;

$rule->saveMany([
   new Rule("cats has:images", "cat pictures"),
   new Rule("dogs has:images", "dog pictures"),
   new Rule("horses has:images", "horse picture"),
]);
```

To delete these new rules,

```
$rule->delete([
	'[RULE ID]',
	'[RULE ID]',
	'[RULE ID]',
]);
```

#### Validating your rules

[](#validating-your-rules)

You can either use the `validate()` method:

```
# returns a list of errors
$errors = $rule->validate('cats ha:images');
```

Or, the `save` and `saveMany` method both have a dryRun parameter:

```
$rule->save('...', '...', dryRun: true);

$rule->saveMany([...], dryRun: true);
```

#### Rule Builder

[](#rule-builder)

Every operator is available, here's an example:

```
$rule->new('listening to music')
    ->raw('#nowplaying')
    ->isNotRetweet()
    ->lang('en')
    ->save();
```

You may also use `and[Operator]`, `or[Operator]`, for example `orNotFrom('ID')` or `andBioLocation('location')`.

Compiling this would produce the following:

```
#nowplaying -is:retweet lang:en sample:10

```

##### Tips

[](#tips)

- To directly add a string to the rule, use `raw(string)`
- You may call `dump()` or `dd()` to quickly debug your rule.
- `and` is the default operator, you may omit it. For example, `andIsNotRetweet()` is the same as `isNotRetweet()`.

Fields
------

[](#fields)

Fields allow for more customization regarding the payload returned per tweet. Let's see that in an example below:

```
$stream
    ->fields([
        'tweet' => 'author_id'
         // or,
         // 'tweet' => ['author_id', '...']
    ])
    ->listen(...);
```

Which could return:

```
{
  "data": {
    "id": "1234321234321234321",
    "text": "Hello world!",
    "author_id": "5678765678765678765"
  }
}
```

Here's the list of all the available field types and their respective object model (last updated: Aug. 2022):

- Tweet
- User
- Media
- Poll
- Place

You can also check out [Twitter’s documentation](https://developer.twitter.com/en/docs/twitter-api/fields) for more details.

Expansions
----------

[](#expansions)

Expansions let you expand ids to their complete object, for example, if you request an extra author\_id field, you may expand it using the author\_id expansion:

```
$stream
    ->fields(['tweet' => 'author_id'])
    ->expansions('author_id')
    ->listen(...);
```

Which could return:

```
{
  "data": {
    "id": "1234321234321234321",
    "text": "Hello world!",
    "author_id": "5678765678765678765"
  },
  "includes": {
    "users": [
      {
        "id": "5678765678765678765",
        "name": "John Doe",
        "username": "johndoe"
      }
    ]
  }
}
```

The list of expansions is quite extensive and not all expansions work the same, please check out [Twitter's documentation](https://developer.twitter.com/en/docs/twitter-api/expansions). on the subject.

Testing
-------

[](#testing)

```
composer test
```

**Twitter Stream API** was created by [Félix Dorn](https://twitter.com/afelixdorn) under the [MIT License](https://opensource.org/licenses/MIT).

###  Health Score

41

—

FairBetter than 89% of packages

Maintenance19

Infrequent updates — may be unmaintained

Popularity38

Limited adoption so far

Community26

Small or concentrated contributor base

Maturity69

Established project with proven stability

 Bus Factor1

Top contributor holds 61.3% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~44 days

Recently: every ~66 days

Total

18

Last Release

1090d ago

Major Versions

0.3.1 → 1.0.02022-07-05

1.0.2 → 2.0.02022-09-01

PHP version history (2 changes)0.1.0PHP ^8

1.0.0PHP ^8.1

### Community

Maintainers

![](https://www.gravatar.com/avatar/eeca3822ab1a1281e77e0c4f7bdb671c840417def9884107629952224ce42eb0?d=identicon)[felixdorn](/maintainers/felixdorn)

---

Top Contributors

[![felixdorn](https://avatars.githubusercontent.com/u/55788595?v=4)](https://github.com/felixdorn "felixdorn (138 commits)")[![DarrenCook](https://avatars.githubusercontent.com/u/880436?v=4)](https://github.com/DarrenCook "DarrenCook (28 commits)")[![fennb](https://avatars.githubusercontent.com/u/127930?v=4)](https://github.com/fennb "fennb (23 commits)")[![sebastianhoitz](https://avatars.githubusercontent.com/u/353768?v=4)](https://github.com/sebastianhoitz "sebastianhoitz (6 commits)")[![sankar4n](https://avatars.githubusercontent.com/u/501259?v=4)](https://github.com/sankar4n "sankar4n (4 commits)")[![compwright](https://avatars.githubusercontent.com/u/138688?v=4)](https://github.com/compwright "compwright (4 commits)")[![adam-riha](https://avatars.githubusercontent.com/u/22528181?v=4)](https://github.com/adam-riha "adam-riha (3 commits)")[![uintaam](https://avatars.githubusercontent.com/u/295346?v=4)](https://github.com/uintaam "uintaam (2 commits)")[![aaronpk](https://avatars.githubusercontent.com/u/113001?v=4)](https://github.com/aaronpk "aaronpk (2 commits)")[![MichelCarroll](https://avatars.githubusercontent.com/u/222127?v=4)](https://github.com/MichelCarroll "MichelCarroll (1 commits)")[![mkraemer](https://avatars.githubusercontent.com/u/1070200?v=4)](https://github.com/mkraemer "mkraemer (1 commits)")[![Parad0X](https://avatars.githubusercontent.com/u/14222?v=4)](https://github.com/Parad0X "Parad0X (1 commits)")[![poldixd](https://avatars.githubusercontent.com/u/695449?v=4)](https://github.com/poldixd "poldixd (1 commits)")[![samedyildirim](https://avatars.githubusercontent.com/u/6238444?v=4)](https://github.com/samedyildirim "samedyildirim (1 commits)")[![thaddeusmt](https://avatars.githubusercontent.com/u/129787?v=4)](https://github.com/thaddeusmt "thaddeusmt (1 commits)")[![vitch](https://avatars.githubusercontent.com/u/9898?v=4)](https://github.com/vitch "vitch (1 commits)")[![aizatto](https://avatars.githubusercontent.com/u/1182?v=4)](https://github.com/aizatto "aizatto (1 commits)")[![bangpound](https://avatars.githubusercontent.com/u/6731?v=4)](https://github.com/bangpound "bangpound (1 commits)")[![calvinnwq](https://avatars.githubusercontent.com/u/580008?v=4)](https://github.com/calvinnwq "calvinnwq (1 commits)")[![Darkflib](https://avatars.githubusercontent.com/u/101405?v=4)](https://github.com/Darkflib "Darkflib (1 commits)")

---

Tags

packagephptwittertwitter-apitwitter-api-streamphpapistreamingtwitterphirehose

###  Code Quality

TestsPest

Static AnalysisPHPStan

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/redwebcreation-twitter-stream-api/health.svg)

```
[![Health](https://phpackages.com/badges/redwebcreation-twitter-stream-api/health.svg)](https://phpackages.com/packages/redwebcreation-twitter-stream-api)
```

###  Alternatives

[fennb/phirehose

A PHP interface to the Twitter Streaming API.

698402.4k3](/packages/fennb-phirehose)[theodo-group/llphant

LLPhant is a library to help you build Generative AI applications.

1.5k311.5k5](/packages/theodo-group-llphant)[noweh/twitter-api-v2-php

This library provides methods for sending messages to Twitter and receiving statuses.

131225.2k1](/packages/noweh-twitter-api-v2-php)[resend/resend-php

Resend PHP library.

574.7M21](/packages/resend-resend-php)[mozex/anthropic-php

Anthropic PHP is a supercharged community-maintained PHP API client that allows you to interact with Anthropic API.

46365.1k13](/packages/mozex-anthropic-php)[owlycode/streaming-bird

A PHP client for the Twitter Streaming APIs inspired from Phirehose.

1024.6k](/packages/owlycode-streaming-bird)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
