PHP code example of danilopolani / twitch-pub-sub

1. Go to this page and download the library: Download danilopolani/twitch-pub-sub library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

danilopolani / twitch-pub-sub example snippets


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

// 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);
});


// 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']);
}

// 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']);

 php

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'],
    ]);
}