ghostzero/twitch-toolkit

此包已废弃,不再维护。未建议替代包。

此包提供了一套 Twitch 工具包,用于使用 Laravel 框架简化某些流程。

4.0.1 2021-03-24 11:30 UTC

This package is auto-updated.

Last update: 2022-07-24 15:02:00 UTC


README

此 Laravel 包的主要思想是使其性能出色,并易于解决 Twitch 某些 API 问题。此外,此包提供了一套工具包,用于简化某些流程(这些流程由我的 StreamKit 平台提供)

  • Twitch 用户名/ID 解析器 & 缓存
  • Twitch 扩展保护中间件
  • Twitch Webhook/Polling 管理
  • Twitch Webhook 作为 Laravel 事件

TwitchUserResolver

use GhostZero\TwitchToolkit\Utils\TwitchUserResolver;
use romanzipp\Twitch\Twitch;

// Fetch the user information from twitch based on the login or id.
// This response will be cached for 12h (because of rate limits).
if ($user = TwitchUserResolver::fetchUser('name or id', app(Twitch::class))) {
	$this->info("Fetched user {$user->login} successfully!");
}

WIP: TwitchExtGuard

1. 注册 TwitchExtGuard (app/Providers/AuthServiceProvider.php)

public function boot()  
{  
	...
	
	TwitchExtGuard::register(config('twitch-api.ext_secret'), new TwitchUserProvider);  
}

2. 配置 TwitchUserProvider

namespace App\Utils;

use App\User;
use GhostZero\TwitchToolkit\Auth\UserProvider;
use Illuminate\Contracts\Auth\Authenticatable;
  
class TwitchUserProvider extends UserProvider  
{  
	public function retrieveById($identifier): ?Authenticatable  
	{
		/** @var User $user */  
		$user = User::query()->whereKey($identifier)->first();  

		return $user;  
	}  

	public function createFromTwitchToken($decoded): ?Authenticatable  
	{
		return User::createFromTwitchToken($decoded);  
	}  
}

3. 守护者

<?php

return [
    ...
    'guards' => [
        ...
        'twitch' => [
            'driver' => 'twitch',
            'provider' => 'users', // this is wrong, will be fixed soon
        ],
    ],
    ...
];

4. 中间件

$this->middleware('auth:twitch')->only(['update']);

轮询安装(如果您未安装 Webhook)

1. 设置计划(app/Console/Kernel.php)

$schedule->command('twitch-toolkit:poll')->everyFiveMinutes();

2. 设置事件(app/Providers/EventServiceProvider.php)

use GhostZero\TwitchToolkit\Events\WebhookWasCalled;

protected $listen = [  
	StreamUp::class => [  
		StreamUpListener::class,  
	],
	StreamDown::class => [  
		StreamDownListener::class,  
	],
	...
];

3. 创建您的监听器(StreamUpListener/StreamDownListener)

4. 为用户注册事件(例如,已注册事件)

Webhook 安装

1. 设置计划(app/Console/Kernel.php)

$schedule->command('twitch-toolkit:subscribe-webhooks')->everyMinute();

2. 设置事件(app/Providers/EventServiceProvider.php)

use GhostZero\TwitchToolkit\Events\WebhookWasCalled;

protected $listen = [  
	WebhookWasCalled::class => [  
		StoreWebhookActivity::class,  
	],
	...
];

3. 创建您自己的事件监听器

namespace App\Listeners;

use GhostZero\TwitchToolkit\Events\WebhookWasCalled;  
  
class StoreWebhookActivity  
{  
	public function handle(WebhookWasCalled $event): void  
	{
		// business logic  
    }  
}

4. 设置访问令牌处理器(app/Providers/AppServiceProvider.php)

use GhostZero\TwitchToolkit\Models\Channel as WebhookChannel;

public function boot(): void
{
	// sometimes twitch-toolkit requires fresh access tokens
	// they will be handled in the requiresFreshOauthCredentials closure
    WebhookChannel::requiresFreshOauthCredentials(function (WebhookChannel $channel) {
        // fetch your user access tokens and fill them in the channel object        
        $channel->forceFill([
            'broadcaster_type' => '...',
            'oauth_access_token' => '...',
            'oauth_refresh_token' => '...',
            'oauth_expires_at' => new CarbonImmutable('...'),
        ])->save();
    });
}

5. 扩展您自己的频道模型

namespace App\Models;

use GhostZero\TwitchToolkit\Models\Channel as WebhookChannel;  
use GhostZero\TwitchToolkit\Models\WebSub;

/**
 * @property string id  
 * @property WebhookChannel webhook_channel  
 * @property WebSub[] web_subs  
 */
class Channel extends Model  
{
	public function webhook_channel(): BelongsTo  
	{  
		return $this->belongsTo(WebhookChannel::class, 'id');  
	}  
	  
	public function web_subs(): HasMany  
	{  
		return $this->hasMany(WebSub::class, 'channel_id');  
	}
}

6. 为用户注册事件(例如:已注册事件)

use GhostZero\TwitchToolkit\Jobs\SubscribeTwitchWebhooks;  
use GhostZero\TwitchToolkit\Models\Channel as WebhookChannel;

// creates a twitch webhook subscription  
$webhookChannel = WebhookChannel::subscribe($channel->getKey(), [  
	WebhookChannel::OPTION_CAPABILITIES => $attributes['capabilities'],  
	WebhookChannel::OPTION_BROADCASTER_TYPE => $attributes['broadcaster_type'],  
]);  
  
if (in_array(WebhookChannel::TYPE_WEBHOOK, $attributes['capabilities'], true)) {  
	dispatch_now(new SubscribeTwitchWebhooks($webhookChannel));  
}  

// check webhook setup
if ($channel->web_subs()->count() < 2) {  
	return response()->json([  
		'message' => 'We need at least 2 WebSubs from Twitch.'  
	], 409);  
}  

// check token generation
if (!$webhookChannel->oauth_access_token) {  
	return response()->json([  
		'message' => 'We couldn\'t get a Twitch access token from our SSO.'  
	], 409);  
}  
  
return response('', 204);