3 namespace App\Console\Commands;
5 use App\Models\Channel;
6 use App\Models\TwitchToken;
7 use GuzzleHttp\Psr7\Query;
8 use Illuminate\Console\Command;
9 use Illuminate\Http\Client\RequestException;
10 use Illuminate\Support\Facades\Http;
12 class TwitchChannelInfo extends Command {
15 * The name and signature of the console command.
19 protected $signature = 'twitch:channel-info';
22 * The console command description.
26 protected $description = 'Refresh twitch channel info';
29 * Execute the console command.
33 public function handle()
35 $this->token = TwitchToken::firstWhere('nick', 'localhorsttv');
37 $this->line('please acquire a token for localhorsttv first');
40 if ($this->token->hasExpired()) {
41 $this->line('access token has expired, refreshing');
42 $this->token->refresh();
44 $channels = Channel::where('twitch_chat', '!=', '')->where('twitch_id', '=', '')->get();
45 foreach ($channels as $channel) {
47 $this->updateChannelId($channel);
48 } catch (RequestException $e) {
49 if ($e->response->status() == 401) {
50 $this->token->refresh();
51 $this->updateChannel($channel);
55 Channel::where('twitch_id', '!=', '')
56 ->where(function($query) {
57 $query->where('join', true);
58 $query->orWhere('chat', true);
60 ->chunk(100, function ($channels) {
61 $this->updateChannelInfos($channels);
63 return Command::SUCCESS;
66 private function updateChannelId(Channel $channel) {
67 $this->line($channel->twitch_chat);
68 $login = substr($channel->twitch_chat, 1);
69 $rsp = $this->token->request()
70 ->get('/users', Query::build([
74 foreach ($rsp['data'] as $user) {
75 if ($user['login'] != $login) continue;
76 $channel->twitch_id = $user['id'];
81 private function updateChannelInfos($channels) {
82 $ids = $channels->pluck('twitch_id')->toArray();
83 $rsp = $this->token->request()
84 ->get('/streams', Query::build([
88 foreach ($channels as $channel) {
90 foreach ($rsp['data'] as $info) {
91 if ($info['user_id'] == $channel->twitch_id) {
97 $channel->twitch_live = false;
98 $channel->twitch_viewers = 0;
100 $channel->twitch_live = true;
101 $channel->twitch_category = $data['game_id'];
102 $channel->twitch_viewers = $data['viewer_count'];