Twitter provides a streaming API with which you can do interesting things such as listen for tweets that contain specific strings or actions a user might take (e.g. liking a tweet, following someone,...). In this post you'll learn an easy way to work with that API.

Phirehose

When researching on how to work with the streaming API in PHP it stumbled upon Phirehose. This package can authenticate and set up a connection with the streaming API. Unfortunately the API of Phirehose itself is a bit unwieldy. That's why I created a wrapper around Phirehose that makes setting up a connection to Twitter's streaming API a breeze. I made a framework agnostic version of the package and a Laravel specific one.

Getting started

Let's review how to integrate the package in a Laravel app. First you need to retrieve some credentials from Twitter. Fortunately this is very easy. Head over to the Application management on Twitter to create an application.

Once you've created your application, click on the Keys and access tokens tab to retrieve your consumer_key , consumer_secret , access_token and access_token_secret .

Now you've got the credentials let's install the package in a Laravel app.

Like a gazillion other packages laravel-twitter-streaming-api can be installed via composer.

composer require spatie/laravel-twitter-streaming-api

Next, install the service provider.

'providers' => [ ... Spatie\LaravelTwitterStreamingApi\TwitterStreamingApiServiceProvider::class, ];

If you love working with facades, you'll be happy to know that there's one provider by the package.

'aliases' => [ ... 'TwitterStreamingApi' => Spatie\LaravelTwitterStreamingApi\TwitterStreamingApiFacade::class, ];

The config file must be published with this command:

php artisan vendor:publish --provider= "Spatie\LaravelTwitterStreamingApi\TwitterStreamingApiServiceProvider" --tag= "config"

It'll copy a file with this content in config/laravel-twitter-streaming-api.php

return [ 'access_token' => env( 'TWITTER_ACCESS_TOKEN' ), 'access_token_secret' => env( 'TWITTER_ACCESS_TOKEN_SECRET' ), 'consumer_key' => env( 'TWITTER_CONSUMER_KEY' ), 'consumer_secret' => env( 'TWITTER_CONSUMER_SECRET' ), ];

Create the TWITTER_ACCESS_TOKEN , TWITTER_ACCESS_TOKEN_SECRET , TWITTER_CONSUMER_KEY and TWITTER_CONSUMER_SECRET keys in your .env and set them to the values you retrieved on Twitter.

Now you're ready to use the package.

Your first stream

Let's listen for all tweets that contain the string #laravel . I've created an example Laravel app with the package preinstalled. This artisan command included to listen for incoming tweets:

namespace App \ Console \ Commands ; use Illuminate \ Console \ Command ; use TwitterStreamingApi ; class ListenForHashTags extends Command { protected $signature = 'twitter:listen-for-hash-tags' ; protected $description = 'Listen for hashtags being used on Twitter' ; public function handle () { TwitterStreamingApi::publicStream() ->whenHears( '#laravel' , function (array $tweet) { dump( "{$tweet['user']['screen_name']} tweeted {$tweet['text']}" ); }) ->startListening(); } }

In case you haven't used it before, that dump function does the same as dd but without the dying part. The call to startListening() starts the listening process. The function will run forever so any code after that won't be executed.

Let's go ahead an execute the command. In the output you'll see some logging done by the underlying Phirehose package.

Now tweet something with #laravel in the tweet.

In the console you'll see your own tweet appearing immediately.

Pretty cool! Be aware that this API works in realtime, so they could report a lot of activity. If you need to do some heavy work processing that activity it's best to put that work in a queue to keep your listening process fast.

Another example

In the example above we've used the public stream. You can use that one to listen for tweets with specific strings posted on Twitter. But there also other kinds of streams. With the user stream you can listen for certain events that happen for the authenticated user.

Here's an example that demonstrates how you can listen people favouriting on of your tweets:

TwitterStreamingApi::userStream() ->onEvent( function (array $event) { if ($event[ 'event' ] === 'favorite' ) { echo "Our tweet {$event['target_object']['text']} got favourited by {$event['source']['screen_name']}" ; } }) ->startListening();

In closing

The Twitter Streaming API's are pretty powerful. If you want to know more about them take a look at the official docs. The easiest way to get started with them is by using our laravel specific or framework agnostic package. If you don't like wrappers and want to use Phirehose directly, then read this tutorial on Scotch.io.

In any case check out the other PHP and Laravel packages our team has made before.

Have fun building a cool app using Twitter's streaming APIs!