]> git.localhorst.tv Git - alttp.git/blob - app/TwitchBot/TwitchAppBot.php
add chat bot
[alttp.git] / app / TwitchBot / TwitchAppBot.php
1 <?php
2
3 namespace App\TwitchBot;
4
5 use App\Models\Channel;
6 use App\Models\TwitchBotCommand;
7
8 class TwitchAppBot extends TwitchBot {
9
10         public function __construct() {
11                 parent::__construct('localhorsttv');
12                 $this->listenCommands();
13         }
14
15         public function logMessage(IRCMessage $msg) {
16                 $msg->log();
17         }
18
19         public function handlePrivMsg(IRCMessage $msg) {
20                 $target = $msg->getPrivMsgTarget();
21                 if ($target[0] != '#') return; // direct message
22                 $text = $msg->getText();
23                 if ($text[0] != '!') return;
24                 $channel = $this->getMessageChannel($msg);
25                 if (!$channel) return;
26                 $this->handleChatCommand($channel, $msg);
27         }
28
29         public function handleChatCommand(Channel $channel, IRCMessage $msg) {
30                 $cmd = explode(' ', ltrim($msg->getText(), '!'), 2);
31                 if (!isset($channel->chat_commands[$cmd[0]])) return;
32                 $config = $channel->chat_commands[$cmd[0]];
33                 $this->getLogger()->info('got command '.$cmd[0].' on channel '.$channel->title);
34                 try {
35                         $command = ChatCommand::create($this, $channel, $config);
36                         $command->execute($cmd[1] ?? '');
37                 } catch (\Exception $e) {
38                         $this->getLogger()->warning('error executing command '.$cmd[0].' on channel '.$channel->title.': '.$e->getMessage());
39                 }
40         }
41
42         public function joinChannels() {
43                 $this->getLogger()->info('joining channels');
44                 $channels = Channel::where('twitch_chat', '!=', '')->where('join', '=', true)->get();
45                 $names = [];
46                 foreach ($channels as $channel) {
47                         $names[] = $channel->twitch_chat;
48                 }
49                 $chunks = array_chunk($names, 10);
50                 foreach ($chunks as $chunk) {
51                         $this->sendIRCMessage(IRCMessage::join($chunk));
52                 }
53         }
54
55
56         private function listenCommands() {
57                 $this->getLoop()->addPeriodicTimer(1, function () {
58                         if (!$this->isReady()) return;
59                         $command = TwitchBotCommand::where('status', '=', 'pending')->oldest()->first();
60                         if ($command) {
61                                 try {
62                                         $command->execute($this);
63                                 } catch (\Exception $e) {
64                                 }
65                         }
66                 });
67         }
68
69 }