PHPackages                             danilopolani/twitch-pub-sub - 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. [HTTP &amp; Networking](/categories/http)
4. /
5. danilopolani/twitch-pub-sub

ActiveLibrary[HTTP &amp; Networking](/categories/http)

danilopolani/twitch-pub-sub
===========================

Integrate Twitch PubSub Web Sockets with Laravel

1.0.2(5y ago)3461MITPHPPHP ^7.4|^8.0

Since Jan 13Pushed 3y ago1 watchersCompare

[ Source](https://github.com/danilopolani/twitch-pub-sub)[ Packagist](https://packagist.org/packages/danilopolani/twitch-pub-sub)[ Docs](https://github.com/danilopolani/twitch-pub-sub)[ RSS](/packages/danilopolani-twitch-pub-sub/feed)WikiDiscussions master Synced 2d ago

READMEChangelog (3)Dependencies (6)Versions (4)Used By (0)

(Laravel) Twitch PubSub
=======================

[](#laravel-twitch-pubsub)

[![Latest Version on Packagist](https://camo.githubusercontent.com/f4d32719e822bbca486a36d531636dd380640c966095e76e4eb39f95f4734678/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f64616e696c6f706f6c616e692f7477697463682d7075622d7375622e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/danilopolani/twitch-pub-sub)[![Build Status](https://camo.githubusercontent.com/9e0dd6983489d1a5feb3ac8242d2f658492e42c875471c8f58a7f1ac81e4682a/68747470733a2f2f7472617669732d63692e636f6d2f64616e696c6f706f6c616e692f7477697463682d7075622d7375622e737667)](https://travis-ci.com/danilopolani/twitch-pub-sub)

 [ ![](https://camo.githubusercontent.com/967f55317c4f96038a252b3d3eda3c99ff24efb39df1a03150c0f88c7a0ecea4/68747470733a2f2f62616e6e6572732e6265796f6e64636f2e64652f5477697463682532305075625375622e706e673f7468656d653d6c69676874267061636b6167654d616e616765723d636f6d706f7365722b72657175697265267061636b6167654e616d653d64616e696c6f706f6c616e692532467477697463682d7075622d737562267061747465726e3d666c6f6174696e67436f6773267374796c653d7374796c655f31266465736372697074696f6e3d5477697463682b5075625375622b5765622b536f636b65742b696d706c656d656e746174696f6e2b666f722b4c61726176656c266d643d312673686f7757617465726d61726b3d3126666f6e7453697a653d313030707826696d616765733d7377697463682d766572746963616c) ](https://github.com/danilopolani/twitch-pub-sub)

Laravel Twitch PubSub
=====================

[](#laravel-twitch-pubsub-1)

Connect to Twitch PubSub (Web Sockets) in a Laravel application, dispatching **Events** whenever a message for a topic is received.

Built with [Amphp with Web Socket](https://amphp.org/websocket-client/).

Table of Contents
-----------------

[](#table-of-contents)

1. [Getting Started](#getting-started)
    - [Prerequisites](#prerequisites)
    - [Installation](#installation)
2. [Usage](#usage)
    - [Topics &amp; Events](#topics--events)
    - [Reconnecting](#reconnection)
    - [Callbacks](#callbacks)
3. [Changelog](#changelog)
4. [Contributing](#contributing)
5. [Testing](#testing)
6. [Security](#security)
7. [Credits](#credits)
8. [License](#license)

Getting Started
---------------

[](#getting-started)

The package supports `Laravel 8.x` and `PHP >= 7.4`.

### Prerequisites

[](#prerequisites)

The PHP extension `ext-pcntl` is required.

### Installation

[](#installation)

You can install the package via composer:

```
composer require danilopolani/twitch-pub-sub
```

Usage
-----

[](#usage)

The package relies on one main function:

```
TwitchPubSub::run(string|array $twitchAuthToken, array $topics = [])
```

ArgumentDescription`array|string $twitchAuthToken`if string, it must be a valid Auth Token, otherwise it can be an associative array of authToken =&gt; [topics](https://dev.twitch.tv/docs/pubsub#topics)\[\]`array $topics`an array of valid [topics](https://dev.twitch.tv/docs/pubsub#topics), needed only if `$twitchAuthToken` is a stringUsually you would put the main function of the package inside an [Artisan Command](https://laravel.com/docs/8.x/artisan#writing-commands).

```
use \Danilopolani\TwitchPubSub\Facades\TwitchPubSub;

/**
 * Execute the console command.
 *
 * @return mixed
 */
public function handle()
{
    TwitchPubSub::run('a1b2c3d4e5', ['whispers.44322889']);

    // Or the array syntax that support multiple users too
    TwitchPubSub::run([
        'a1b2c3d4e5' => ['whispers.44322889'],
        'f6g7h8j9k0' => ['channel-bits-events-v1.123456', 'channel-points-channel-v1.123456'],
    ]);
}
```

Now you can run your command from your terminal or a worker.

> You should **definitely** [setup Supervisor](https://laravel.com/docs/8.x/queues#supervisor-configuration) or a similar tool to keep your command alive and restart it if something goes wrong.

Finally, create a [Listener](https://laravel.com/docs/8.x/events#defining-listeners) to handle the incoming events.

```
// App\Providers\EventServiceProvider.php

/**
 * The event listener mappings for the application.
 *
 * @var array
 */
protected $listen = [
    \Danilopolani\TwitchPubSub\Events\WhisperReceived::class => [
        TrackMessages::class,
    ],
];

// Or with a closure
Event::listen(function (\Danilopolani\TwitchPubSub\Events\WhisperReceived $event) {
    dd($event->data);
});
```

### Topics &amp; Events

[](#topics--events)

TopicEvent`channel-bits-events-v1.``\Danilopolani\TwitchPubSub\Events\BitsDonated``channel-bits-events-v2.``\Danilopolani\TwitchPubSub\Events\BitsDonated``channel-bits-badge-unlocks.``\Danilopolani\TwitchPubSub\Events\BitsBadgeUnlocked``channel-points-channel-v1.``\Danilopolani\TwitchPubSub\Events\RewardRedeemed``channel-subscribe-events-v1.``\Danilopolani\TwitchPubSub\Events\SubscriptionReceived``chat_moderator_actions..``\Danilopolani\TwitchPubSub\Events\ModeratorActionSent``whispers.``\Danilopolani\TwitchPubSub\Events\WhisperReceived`### Reconnection

[](#reconnection)

When the connection is closed, the package itself will try to attempt a reconnection, but this would need a **fresh access token**, furthermore we **strongly suggest you** to handle the `onClose` callback and exit your script. This, with a correct configuration of [**Supervisor**](https://laravel.com/docs/8.x/queues#supervisor-configuration), will restart the worker automatically reconnecting with a fresh token, if your code is written in that way. Below a simple example with a correct flow to demonstrate how it should work:

```
// App/Console/Commands/PubSub.php

public function handle()
{
    // A fresh Twitch Access Token
    $token = $user->getFreshAccessToken();

    TwitchPubSub::onClose(function (\Amp\Websocket\ClosedException $e) {
        exit(0);
    });

    TwitchPubSub::run($token, ['my-topic']);
}
```

When `exit(0)` will be executed, the script will stop, Supervisor will restart it - invoking `handle` again - and refreshing the token reconnecting correctly.
Please see below for more information about callbacks.

### Callbacks

[](#callbacks)

The package provides several callbacks fired when something occurs. These callbacks **must be put before** the `::run()` method to let them work correctly.

```
// A message (anything, PING/PONG too for example) is received
TwitchPubSub::onMessage(function (array $payload) {
    dump('received message:', $payload);
});

// A generic error occurs
TwitchPubSub::onError(function (\Exception $e) {
    dump('generic error:', $e->getMessage());
});

// The connection has been closed
// This could triggered from a SIGINT or SIGTERM too (stopping the script, restarting the worker etc.)
TwitchPubSub::onClose(function (\Amp\Websocket\ClosedException $e) {
    dump('connection closed, reason:', $e->getMessage());
});

// An error occurred in a Listener after the event has been dispatched
TwitchPubSub::onDispatchError(function (string $event, array $payload, Throwable $e) {
    dump('error for event', $event, $payload, $e->getMessage());
});

// Runner
TwitchPubSub::run('a1b2c3d4e5', ['whispers.44322889']);
```

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information what has changed recently.

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](CONTRIBUTING.md) for details.

Testing
-------

[](#testing)

Clone the repository and just run

```
composer test
```

With Docker (Windows):

```
docker run --rm -v %cd%:/app composer:2 bash -c "cd /app && composer install --ignore-platform-reqs && ./vendor/bin/phpunit"
```

With Docker (Linux/OSX):

```
docker run --rm -v $(pwd):/app composer:2 bash -c "cd /app && composer install --ignore-platform-reqs && ./vendor/bin/phpunit"
```

Security
--------

[](#security)

If you discover any security related issues, please email  instead of using the issue tracker.

Credits
-------

[](#credits)

- [Danilo Polani](https://github.com/danilopolani)
- [All Contributors](../../contributors)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

Laravel Package Boilerplate
---------------------------

[](#laravel-package-boilerplate)

This package was generated using the [Laravel Package Boilerplate](https://laravelpackageboilerplate.com).

###  Health Score

28

—

LowBetter than 54% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity12

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity60

Established project with proven stability

 Bus Factor1

Top contributor holds 100% 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 ~37 days

Total

3

Last Release

1871d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/8ed568a3c0ca4ca3d3b7d199371b455e3a50347dcffc39ec01c94e04743bdcd6?d=identicon)[Theraloss](/maintainers/Theraloss)

---

Top Contributors

[![danilopolani](https://avatars.githubusercontent.com/u/6277291?v=4)](https://github.com/danilopolani "danilopolani (20 commits)")

---

Tags

laraveltwitchtheralosstwitch-pubsub

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/danilopolani-twitch-pub-sub/health.svg)

```
[![Health](https://phpackages.com/badges/danilopolani-twitch-pub-sub/health.svg)](https://phpackages.com/packages/danilopolani-twitch-pub-sub)
```

###  Alternatives

[laravel/pulse

Laravel Pulse is a real-time application performance monitoring tool and dashboard for your Laravel application.

1.7k12.1M99](/packages/laravel-pulse)[watson/validating

Eloquent model validating trait.

9723.3M47](/packages/watson-validating)[roots/acorn

Framework for Roots WordPress projects built with Laravel components.

9682.1M97](/packages/roots-acorn)[dyrynda/laravel-model-uuid

This package allows you to easily work with UUIDs in your Laravel models.

4802.8M8](/packages/dyrynda-laravel-model-uuid)[psalm/plugin-laravel

Psalm plugin for Laravel

3274.9M308](/packages/psalm-plugin-laravel)[laravel-zero/framework

The Laravel Zero Framework.

3371.4M369](/packages/laravel-zero-framework)

PHPackages © 2026

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