Consume the Twitter Stream API v2 in real-time.
This package is the spiritual successor of fennb/phirehose
.
Requires PHP 8.1+
You can install the package via composer:
composer require redwebcreation/twitter-stream-api
use RWC\TwitterStream\Connection;
use RWC\TwitterStream\FilteredStream;
use RWC\TwitterStream\VolumeStream;
$twitterStream = new FilteredStream();
// or
$twitterStream = new VolumeStream();
$connection = new Connection(
bearerToken: '...'
);
$rule = new RuleManager($connection);
$rule->new(tag: 'cat_filter_1')
->query('cats')
->hasImages()
->andHasGeo()
->save()
$twitterStream
->backfill(2) // for "academic research" accounts only
->expansions('author_id')
->fields('media.duration_ms', 'media.height')
->fields('place.full_name', 'place.geo', 'place.id')
->listen($connection, function (array $tweet) {
echo $tweet['data']['text'];
if ($this->received >= 100) {
$this->stopListening();
}
});
Rules are made of one or many operators that are combined using boolean logic and parentheses to help define which Tweets your stream receives. Rules are saved by Twitter and are persistent.
use RWC\TwitterStream\RuleManager;
$rules = new RuleManager($connection);
$rules->all();
use RWC\TwitterStream\Rule;
$rules->save(
'cat has:image',
'tweet with an image of a cat'
)
// Using saveMany to create many rules is more efficient than using save
// as it only sends one request to Twitter as opposed to sending one request per rule.
$rules->saveMany([
new Rule('cat has:image', 'cat with an image'),
new Rule('cat has:video', 'cat with a video'),
new Rule ('dog -has:image', 'dog without an image'),
])
If no tag is provided, it fallbacks to the rule itself.
use RWC\TwitterStream\Rule;
$rules->delete('THE_RULE_ID_HERE');
// Using deleteMany to delete many rules is more efficient than using delete
// as it only sends one request to Twitter as opposed to sending one request per rule.
$rules->deleteMany([
'RULE_IDS_HERE'
'RULE_IDS_HERE'
'RULE_IDS_HERE'
])
use RWC\TwitterStream\RuleBuilder;
$rules->new()
->query('php')
->group(fn (RuleBuilder $builder) => $builder->raw('tip')->or->raw('🔥'))
->isRetweets()
->hasImages()
->hasNotLinks()
->save();
// Produces #php (tip OR 🔥) is:retweet has:images -has:links
You can negate an operator using the magic property not
.
use RWC\TwitterStream\RuleBuilder;
$rules->new()
->query('#php')
->exceptRetweets()
->hasLinks()
->save()
// Produces: #php -is:retweet has:links
You can also group operators together :
use RWC\TwitterStream\RuleBuilder;
$rules->query('#laravel')
->group(function (RuleBuilder $builder) {
$builder->raw('tip')->or->raw('tips')->or->raw('🔥');
});
// Produces: #laravel (tip OR tips OR 🔥)
composer test
Twitter Stream API was created by Félix Dorn under the MIT License.