+ public function handleIRCMessage(IRCMessage $msg) {
+ $this->last_contact = time();
+ if ($msg->isPrivMsg()) {
+ $this->handlePrivMsg($msg);
+ return;
+ }
+ if ($msg->isPing()) {
+ $this->sendIRCMessage($msg->makePong());
+ return;
+ }
+ if ($msg->isPong()) {
+ return;
+ }
+ if ($msg->isNotice() && $msg->getText() == 'Login authentication failed') {
+ $this->logger->notice('login failed, refreshing access token');
+ $this->token->refresh();
+ $this->login();
+ return;
+ }
+ if ($msg->command == '001') {
+ // successful login
+ $this->joinChannels();
+ $this->ready = true;
+ return;
+ }
+ }
+
+ public function handlePrivMsg(IRCMessage $msg) {
+ $target = $msg->getPrivMsgTarget();
+ if ($target[0] != '#') return;
+ $text = $msg->getText();
+ if ($text[0] != '!') return;
+ $channel = Channel::firstWhere('twitch_chat', '=', $target);
+ if (!$channel) return;
+ $this->handleChatCommand($channel, $msg);
+ }
+
+ public function handleChatCommand(Channel $channel, IRCMessage $msg) {
+ $cmd = explode(' ', ltrim($msg->getText(), '!'), 2);
+ if (!isset($channel->chat_commands[$cmd[0]])) return;
+ $config = $channel->chat_commands[$cmd[0]];
+ $this->logger->info('got command '.$cmd[0].' on channel '.$channel->title);
+ try {
+ $command = ChatCommand::create($this, $channel, $config);
+ $command->execute($cmd[1] ?? '');
+ } catch (\Exception $e) {
+ $this->logger->warning('error executing command '.$cmd[0].' on channel '.$channel->title.': '.$e->getMessage());
+ }
+ }
+
+ public function login() {
+ $this->ws->send('PASS oauth:'.$this->token->access);
+ $this->ws->send('NICK localhorsttv');
+ }
+
+ public function joinChannels() {
+ $this->logger->info('joining channels');
+ $channels = Channel::where('twitch_chat', '!=', '')->where('join', '=', true)->get();
+ $names = [];
+ foreach ($channels as $channel) {
+ $names[] = $channel->twitch_chat;
+ }
+ $chunks = array_chunk($names, 10);
+ foreach ($chunks as $chunk) {
+ $this->sendIRCMessage(IRCMessage::join($chunk));
+ }
+ }
+
+ private function listenCommands() {
+ $this->getLoop()->addPeriodicTimer(1, function () {
+ if (!$this->ready) return;
+ $command = TwitchBotCommand::where('status', '=', 'pending')->oldest()->first();
+ if ($command) {
+ try {
+ $command->execute($this);
+ } catch (\Exception $e) {
+ }
+ }
+ });
+ }
+
+ private function startPinger() {
+ $this->getLoop()->addPeriodicTimer(15, function () {
+ if (!$this->ready) return;
+ if (time() - $this->last_contact < 60) return;
+ try {
+ $this->sendIRCMessage(IRCMessage::ping());
+ } catch (\Exception $e) {
+ }
+ });
+ }
+
+ public function sendIRCMessage(IRCMessage $msg) {
+ $irc_message = $msg->encode();
+ $this->logger->info('sending IRC message '.$irc_message);
+ $this->ws->send($irc_message);
+ $this->last_contact = time();
+ }
+
+