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 $channels = Channel::where('twitch_chat', '!=', '')->where('twitch_id', '=', '')->get();
41 foreach ($channels as $channel) {
43 $this->updateChannelId($channel);
44 } catch (RequestException $e) {
45 if ($e->response->status() == 401) {
46 $this->token->refresh();
47 $this->updateChannel($channel);
51 Channel::where('twitch_id', '!=', '')
52 ->where(function($query) {
53 $query->where('join', true);
54 $query->orWhere('chat', true);
55 })->chunk(100, function ($channels) {
56 $this->updateChannelInfos($channels);
58 return Command::SUCCESS;
61 private function updateChannelId(Channel $channel) {
62 $this->line($channel->twitch_chat);
63 $login = substr($channel->twitch_chat, 1);
64 $rsp = $this->token->request()
65 ->get('/users', Query::build([
69 foreach ($rsp['data'] as $user) {
70 if ($user['login'] != $login) continue;
71 $channel->twitch_id = $user['id'];
76 private function updateChannelInfos($channels) {
77 $ids = $channels->pluck('twitch_id')->toArray();
78 $rsp = $this->token->request()
79 ->get('/streams', Query::build([
83 foreach ($channels as $channel) {
85 foreach ($rsp['data'] as $info) {
86 if ($info['user_id'] == $channel->twitch_id) {
92 $channel->twitch_live = false;
93 $channel->twitch_viewers = 0;
95 $channel->twitch_live = true;
96 $channel->twitch_category = $data['game_id'];
97 $channel->twitch_viewers = $data['viewer_count'];