Skip to content

Commit

Permalink
Merge pull request #40 from FabienO/wotd
Browse files Browse the repository at this point in the history
Word of the Day Plugin
  • Loading branch information
PeeHaa committed Apr 23, 2016
2 parents d8080e5 + 1a2eacc commit 7d5d843
Show file tree
Hide file tree
Showing 3 changed files with 68 additions and 1 deletion.
2 changes: 2 additions & 0 deletions cli/run.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
use Room11\Jeeves\Chat\Plugin\Mdn as MdnPlugin;
use Room11\Jeeves\Chat\Plugin\Chuck as ChuckPlugin;
use Room11\Jeeves\Chat\Plugin\Rebecca as RebeccaPlugin;
use Room11\Jeeves\Chat\Plugin\Wotd as WotdPlugin;
use Room11\Jeeves\Chat\Room\Host;
use Room11\Jeeves\Chat\Room\Room;
use Room11\Jeeves\Fkey\FKey;
Expand Down Expand Up @@ -123,6 +124,7 @@
MdnPlugin::class,
ChuckPlugin::class,
RebeccaPlugin::class,
WotdPlugin::class,
];

foreach ($plugins as $plugin) {
Expand Down
2 changes: 1 addition & 1 deletion composer.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

65 changes: 65 additions & 0 deletions src/Chat/Plugin/Wotd.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
<?php declare(strict_types=1);

namespace Room11\Jeeves\Chat\Plugin;

use Room11\Jeeves\Chat\Client\ChatClient;
use Room11\Jeeves\Chat\Command\Command;
use Room11\Jeeves\Chat\Command\Message;
use Amp\Artax\Response;

class Wotd implements Plugin
{
const COMMAND = 'wotd';

private $chatClient;

public function __construct(ChatClient $chatClient)
{
$this->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 $message instanceof Command
&& $message->getCommand() === self::COMMAND;
}

private function getResult(Message $message): \Generator
{
$response = yield from $this->chatClient->request(
'http://www.dictionary.com/wordoftheday/wotd.rss'
);

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('description')->length === 0) {
return 'I dun goofed';
}

preg_match("/([^:]+)/", $dom->getElementsByTagName('description')->item(2)->textContent, $before);
preg_match("/\:(.*)/", $dom->getElementsByTagName('description')->item(2)->textContent, $after);

return '**['.$before[0].'](http://www.dictionary.com/browse/'.str_replace(" ", "-", $before[0]).')**' . $after[0];
}
}

0 comments on commit 7d5d843

Please sign in to comment.