-
Notifications
You must be signed in to change notification settings - Fork 19
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #40 from FabienO/wotd
Word of the Day Plugin
- Loading branch information
Showing
3 changed files
with
68 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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]; | ||
} | ||
} |