diff --git a/cli/run.php b/cli/run.php index 156c2c4..88242a6 100644 --- a/cli/run.php +++ b/cli/run.php @@ -15,6 +15,7 @@ use Room11\Jeeves\Chat\Plugin\Wikipedia as WikipediaPlugin; use Room11\Jeeves\Chat\Plugin\SwordFight as SwordFightPlugin; use Room11\Jeeves\Chat\Plugin\Docs as DocsPlugin; +use Room11\Jeeves\Chat\Plugin\Imdb as ImdbPlugin; use Room11\Jeeves\Chat\Client\Xhr as ChatClient; @@ -41,6 +42,7 @@ ->register(new WikipediaPlugin($chatClient)) ->register(new SwordFightPlugin($chatClient)) ->register(new DocsPlugin($chatClient)) + ->register(new ImdbPlugin($chatClient)) ; $webSocketUrl = $openIdClient->getWebSocketUri($roomId); diff --git a/src/Chat/Plugin/Imdb.php b/src/Chat/Plugin/Imdb.php new file mode 100644 index 0000000..f0bfc96 --- /dev/null +++ b/src/Chat/Plugin/Imdb.php @@ -0,0 +1,69 @@ +chatClient = $chatClient; + } + + public function handle(Message $message): \Generator + { + if (!$this->validMessage($message)) { + return; + } + + yield from $this->getResult($message); + } + + private function validMessage(Message $message): bool + { + return get_class($message) === 'Room11\Jeeves\Chat\Command\Command' + && $message->getCommand() === self::COMMAND + && $message->getParameters(); + } + + private function getResult(Message $message): \Generator + { + $response = yield from $this->chatClient->request( + 'http://www.imdb.com/xml/find?xml=1&nr=1&tt=on&q=' . rawurlencode(implode(' ', $message->getParameters())) + ); + + yield from $this->chatClient->postMessage( + $this->getMessage($response) + ); + } + + private function getMessage(Response $response): string + { + $internalErrors = libxml_use_internal_errors(true); + + $dom = new \DOMDocument(); + $dom->loadHTML($response->getBody()); + + libxml_use_internal_errors($internalErrors); + + if ($dom->getElementsByTagName('resultset')->length === 0) { + return 'I cannot find that title.'; + } + + $result = $dom->getElementsByTagName('imdbentity')->item(0); + + return sprintf( + '[ [%s](%s) ] %s', + $result->firstChild->wholeText, + 'http://www.imdb.com/title/' . $result->getAttribute('id'), + $result->getElementsByTagName('description')->item(0)->textContent + ); + } +}