]> git.localhorst.tv Git - alttp.git/blob - app/Console/Commands/TwitchAuth.php
fix some twitch bot stuff
[alttp.git] / app / Console / Commands / TwitchAuth.php
1 <?php
2
3 namespace App\Console\Commands;
4
5 use App\Models\TwitchToken;
6 use Illuminate\Console\Command;
7 use Illuminate\Support\Facades\Http;
8
9 class TwitchAuth extends Command {
10
11         /**
12          * The name and signature of the console command.
13          *
14          * @var string
15          */
16         protected $signature = 'twitch:auth {nick}';
17
18         /**
19          * The console command description.
20          *
21          * @var string
22          */
23         protected $description = 'Acquire a twitch oauth token';
24
25         /**
26          * Execute the console command.
27          *
28          * @return int
29          */
30         public function handle()
31         {
32                 $token = TwitchToken::firstWhere('nick', $this->argument('nick'));
33                 if (!$token) {
34                         $token = new TwitchToken();
35                         $token->nick = $this->argument('nick');
36                         $token->scope = ['chat:read', 'chat:edit'];
37                 }
38                 $url = $token->getAuthUrl();
39                 $this->line('Please visit '.$url);
40                 $code = $this->ask('and enter the authorization code here');
41                 $rsp = $this->fetchToken($code);
42                 $token->type = $rsp['token_type'];
43                 $token->access = $rsp['access_token'];
44                 $token->refresh = $rsp['refresh_token'];
45                 $token->save();
46                 return Command::SUCCESS;
47         }
48
49         protected function fetchToken($code) {
50                 $rsp = Http::post('https://id.twitch.tv/oauth2/token', [
51                         'client_id' => config('twitch.client_id'),
52                         'client_secret' => config('twitch.client_secret'),
53                         'code' => $code,
54                         'grant_type' => 'authorization_code',
55                         'redirect_uri' => config('twitch.redirect_uri'),
56                 ]);
57                 if (!$rsp->successful()) {
58                         throw new \Exception($rsp['message']);
59                 }
60                 return $rsp->json();
61         }
62
63 }