3 namespace App\TwitchBot;
4 use Illuminate\Support\Facades\Http;
5 use Monolog\Handler\StreamHandler;
7 use Ratchet\Client\Connector;
8 use Ratchet\Client\WebSocket;
9 use Ratchet\RFC6455\Messaging\Message;
10 use React\EventLoop\Loop;
14 public function __construct() {
15 $this->logger = new Logger('TwitchBot');
16 $this->logger->pushHandler(new StreamHandler('php://stdout', Logger::INFO));
20 $this->connector = new Connector();
24 public function getLogger() {
28 public function getLoop() {
32 public function run() {
33 $this->getLoop()->run();
36 public function stop() {
38 $this->getLoop()->stop();
42 public function fetchToken() {
43 $this->logger->info('acquiring token');
44 $rsp = Http::post('https://id.twitch.tv/oauth2/token', [
45 'client_id' => config('twitch.client_id'),
46 'client_secret' => config('twitch.client_secret'),
47 'code' => config('twitch.code'),
48 'grant_type' => 'authorization_code',
49 'redirect_uri' => config('twitch.redirect_uri'),
52 var_dump($rsp->body());
53 $this->token = $rsp->json();
57 public function connect() {
58 ($this->connector)('wss://irc-ws.chat.twitch.tv:443')->done(
59 [$this, 'handleWsConnect'],
60 [$this, 'handleWsConnectError'],
64 public function disconnect() {
68 public function handleWsConnect(WebSocket $ws) {
69 $this->logger->info('websocket connection estblished');
71 $ws->on('message', [$this, 'handleWsMessage']);
72 $ws->on('close', [$this, 'handleWsClose']);
73 $ws->on('error', [$this, 'handleWsError']);
74 $ws->send('CAP REQ :twitch.tv/tags twitch.tv/commands');
75 $ws->send('PASS oauth:'.$this->token->access_token);
76 $ws->send('NICK localhorsttv');
79 public function handleWsConnectError(WebSocket $ws) {
80 $this->logger->error('failed to establish websocket connection');
83 public function handleWsMessage(Message $message, WebSocket $ws) {
84 $this->logger->info('websocket message received');
85 var_dump($message->getPayload());
88 public function handleWsClose(int $op, string $reason) {
89 $this->logger->info('websocket connection closed: '.$reason.' ['.$op.']');
92 public function handleWsError(\Exception $e, WebSocket $ws) {
93 $this->logger->error('websocket error '.$e->getMessage());