PHP code example of vzgcoders / twitchphp

1. Go to this page and download the library: Download vzgcoders/twitchphp 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/ */

    

vzgcoders / twitchphp example snippets


use Twitch\Twitch;

$twitch = new Twitch([
    'client_id'     => getenv('TWITCH_CLIENT_ID'),
    'client_secret' => getenv('TWITCH_CLIENT_SECRET'), // app token, or:
    'token'         => getenv('TWITCH_ACCESS_TOKEN'),  // a user token
    'refresh_token' => getenv('TWITCH_REFRESH_TOKEN'), // refreshed automatically on 401
]);

$twitch->on('ready', function (Twitch $twitch) {
    $twitch->users->fetchByLogin('twitchdev')->then(function ($user) {
        echo "twitchdev is user {$user->id}, created {$user->created_at->diffForHumans()}\n";
    });
});

$twitch->run();

$twitch = new Twitch([
    'client_id'     => getenv('TWITCH_CLIENT_ID'),
    'client_secret' => getenv('TWITCH_CLIENT_SECRET'),
    'token_store'   => new Twitch\Auth\EnvFileTokenStore(__DIR__ . '/.env'),
    'reauthorize'   => new Twitch\Auth\DeviceCodeReauthorizer($oauth, $scopes, $prompt),
]);

$twitch->users;         $twitch->channels;      $twitch->streams;
$twitch->games;         $twitch->chat;          $twitch->moderation;
$twitch->clips;         $twitch->videos;        $twitch->polls;
$twitch->predictions;   $twitch->channelPoints; $twitch->subscriptions;
$twitch->eventSubscriptions;  $twitch->teams;   $twitch->schedule;
$twitch->charity;       $twitch->goals;         $twitch->raids;
$twitch->bits;          $twitch->hypeTrain;     $twitch->search;
$twitch->whispers;      $twitch->ads;           $twitch->contentLabels;
$twitch->conduits;      $twitch->entitlements;  $twitch->analytics;
$twitch->guestStar;     $twitch->extensions;

// Look users up by login and cache them
$twitch->users->byLogins(['twitchdev', 'twitch'])->then(function ($users) {
    foreach ($users as $user) {
        echo "{$user->display_name} ({$user->id})\n";
    }
});

// Who is live among a set of channels
$twitch->streams->live(['userLogins' => ['twitchdev']])->then(function ($streams) {
    echo $streams->count() . " live\n";
});

// Update your channel
$twitch->channels->modify($broadcasterId, [
    'title'         => 'Now with 20% more PHP',
    'game_id'       => '509670',
    'tags'          => ['php', 'reactphp'],
]);

// Moderation
$twitch->moderation->ban($broadcasterId, $modId, $userId, 'spam');
$twitch->moderation->timeout($broadcasterId, $modId, $userId, 600, 'chill');

$twitch = new Twitch([
    'client_id'     => getenv('TWITCH_CLIENT_ID'),
    'token'         => getenv('TWITCH_ACCESS_TOKEN'),
    'refresh_token' => getenv('TWITCH_REFRESH_TOKEN'),
    'eventsub'      => true,
]);

use Twitch\EventSub\SubscriptionTypes;

$twitch->on('ready', function (Twitch $twitch) use ($broadcasterId) {
    $es = $twitch->getEventSub();

    // Typed helpers for the common ones — right condition, right version.
    $es->onChatMessage($broadcasterId, $twitch->getUserId());
    $es->onFollow($broadcasterId, $twitch->getUserId());  // channel.follow v2
    $es->onStreamChange($broadcasterId);                   // online + offline

    // Generic form — version is looked up from SubscriptionTypes unless given.
    $es->subscribe(SubscriptionTypes::CHANNEL_CHEER, ['broadcaster_user_id' => $broadcasterId]);
    $es->subscribeMany([
        [SubscriptionTypes::CHANNEL_RAID, ['to_broadcaster_user_id' => $broadcasterId]],
        [SubscriptionTypes::CHANNEL_AD_BREAK_BEGIN, ['broadcaster_user_id' => $broadcasterId]],
    ]);
});

// Every notification fires twice: a generic event and a per-type event.
$twitch->on('eventsub', function (string $type, array $event, array $meta, Twitch $twitch) {
    echo "eventsub {$type}\n";
});
$twitch->on('eventsub.stream.online', function (array $event) {
    echo "{$event['broadcaster_user_name']} went live\n";
});

$twitch = new Twitch([
    'client_id'      => getenv('TWITCH_CLIENT_ID'),
    'token'          => getenv('TWITCH_ACCESS_TOKEN'),   // needs chat:read + chat:edit
    'refresh_token'  => getenv('TWITCH_REFRESH_TOKEN'),
    'nick'           => 'valgorithms',
    'channels'       => ['twitchdev'],
    'command_prefix' => '!',
]);

$twitch->on('ready', function (Twitch $twitch) {
    $irc = $twitch->getIrc();

    $irc->on('chat', function ($message) {
        if (str_contains(strtolower($message->content), 'hello')) {
            $message->reply('hey!');
        }
    });

    $irc->registerCommand('ping', fn ($message) => $message->say('pong'));
});

use Twitch\Chat\Command;
use Twitch\Chat\CommandClient;

$cc = new CommandClient($twitch);

$cc->command('dice', fn ($m) => $m->reply('🎲 ' . random_int(1, 6)), cooldown: 10, description: 'Roll a die');

$cc->command('so', function ($m, $args) use ($twitch) {
    $twitch->chat->shoutout($m->tags['room-id'], $args[0], $twitch->getUserId());
}, aliases: ['shoutout'], permission: Command::MODERATOR, cooldown: 30, description: 'Shout a channel out');