コード例 #1
0
ファイル: RoomPresence.php プロジェクト: Room-11/Jeeves
 private function invite(CommandMessage $command)
 {
     if (!$command->hasParameters()) {
         (yield $this->chatClient->postReply($command, "If you want to invite me somewhere, you have to tell me where..."));
         return;
     }
     try {
         $identifier = $this->getRoomIdentifierFromArg($command->getParameter(0), $command->getRoom()->getIdentifier()->getHost());
     } catch (InvalidRoomIdentifierException $e) {
         (yield $this->chatClient->postReply($command, "Sorry, I can't work out where you are asking me to go"));
         return;
     }
     if ($identifier->equals($command->getRoom()->getIdentifier())) {
         (yield $this->chatClient->postReply($command, "Ummm... that's this room?"));
         return;
     }
     $userId = $command->getUserId();
     $userName = $command->getUserName();
     $this->logger->log(Level::DEBUG, "Invited to {$identifier} by {$userName} (#{$userId})");
     try {
         (yield $this->presenceManager->addRoom($identifier, $userId));
         (yield $this->chatClient->postReply($command, "See you there shortly! :-)"));
     } catch (RoomAlreadyExistsException $e) {
         (yield $this->chatClient->postReply($command, "I'm already there, I don't need to be invited again"));
     } catch (\Throwable $e) {
         (yield $this->chatClient->postReply($command, "Something went pretty badly wrong there, please report this issue to my maintainers."));
     }
 }
コード例 #2
0
ファイル: Scrabble.php プロジェクト: Room-11/Jeeves
 public function scrabble(Command $command) : Promise
 {
     if ($command->hasParameters() === false) {
         return $this->chatClient->postMessage($command->getRoom(), self::USAGE);
     }
     return $this->chatClient->postReply($command, $this->formatScores($this->calculateScores($this->getScorableWords($command->getParameters()))));
 }
コード例 #3
0
ファイル: Xkcd.php プロジェクト: Room-11/Jeeves
 public function search(Command $command) : \Generator
 {
     if (!$command->hasParameters()) {
         return new Success();
     }
     $uri = "https://www.google.com/search?q=site:xkcd.com+intitle%3a%22xkcd%3a+%22+" . urlencode(implode(' ', $command->getParameters()));
     /** @var HttpResponse $response */
     $response = (yield $this->httpClient->request($uri));
     if ($response->getStatus() !== 200) {
         return $this->chatClient->postMessage($command->getRoom(), "Useless error message here so debugging this is harder than needed.");
     }
     $dom = domdocument_load_html($response->getBody());
     $nodes = (new \DOMXPath($dom))->query("//*[contains(concat(' ', normalize-space(@class), ' '), ' g ')]/h3/a");
     /** @var \DOMElement $node */
     foreach ($nodes as $node) {
         if (preg_match('~^/url\\?q=(https://xkcd\\.com/\\d+/)~', $node->getAttribute('href'), $matches)) {
             return $this->chatClient->postMessage($command->getRoom(), $matches[1]);
         }
     }
     if (preg_match('/^(\\d+)$/', trim(implode(' ', $command->getParameters())), $matches) !== 1) {
         return $this->chatClient->postMessage($command->getRoom(), self::NOT_FOUND_COMIC);
     }
     /** @var HttpResponse $response */
     $response = (yield $this->httpClient->request('https://xkcd.com/' . $matches[1]));
     if ($response->getStatus() !== 200) {
         return $this->chatClient->postMessage($command->getRoom(), self::NOT_FOUND_COMIC);
     }
     return $this->chatClient->postMessage($command->getRoom(), 'https://xkcd.com/' . $matches[1]);
 }
コード例 #4
0
ファイル: RFC.php プロジェクト: Room-11/Jeeves
 public function search(Command $command)
 {
     if ($command->hasParameters(1)) {
         // !!rfcs some-rfc-name
         return yield from $this->getRFC($command);
     }
     /** @var HttpResponse $response */
     $response = (yield $this->httpClient->request(self::BASE_URI));
     if ($response->getStatus() !== 200) {
         return $this->chatClient->postMessage($command->getRoom(), "Nope, we can't have nice things.");
     }
     $dom = domdocument_load_html($response->getBody());
     $list = $dom->getElementById("in_voting_phase")->nextSibling->nextSibling->getElementsByTagName("ul")->item(0);
     $rfcsInVoting = [];
     foreach ($list->childNodes as $node) {
         if ($node instanceof \DOMText) {
             continue;
         }
         /** @var \DOMElement $node */
         /** @var \DOMElement $href */
         $href = $node->getElementsByTagName("a")->item(0);
         $rfcsInVoting[] = sprintf("[%s](%s)", trim($href->textContent), \Sabre\Uri\resolve(self::BASE_URI, $href->getAttribute("href")));
     }
     yield from $this->unpinPreviousMessage($command->getRoom());
     if (empty($rfcsInVoting)) {
         if ((yield $this->pluginData->exists('lastpinid', $command->getRoom()))) {
             (yield $this->pluginData->unset('lastpinid', $command->getRoom()));
         }
         return $this->chatClient->postMessage($command->getRoom(), "Sorry, but we can't have nice things.");
     }
     /** @var PostedMessage $postedMessage */
     $postedMessage = (yield $this->chatClient->postMessage($command->getRoom(), sprintf("[tag:rfc-vote] %s", implode(" | ", $rfcsInVoting))));
     (yield $this->pluginData->set('lastpinid', $postedMessage->getId(), $command->getRoom()));
     return $this->chatClient->pinOrUnpinMessage($postedMessage, $command->getRoom());
 }
コード例 #5
0
ファイル: Imdb.php プロジェクト: DaveRandom/Jeeves
 public function search(Command $command) : \Generator
 {
     if (!$command->hasParameters()) {
         return new Success();
     }
     $response = (yield $this->httpClient->request('http://www.imdb.com/xml/find?xml=1&nr=1&tt=on&q=' . rawurlencode(implode(' ', $command->getParameters()))));
     return $this->chatClient->postMessage($command->getRoom(), $this->getMessage($response));
 }
コード例 #6
0
ファイル: Giphy.php プロジェクト: Room-11/Jeeves
 public function random(Command $command) : \Generator
 {
     if (!$command->hasParameters()) {
         return new Success();
     }
     /** @var HttpResponse $response */
     $response = (yield $this->httpClient->request(self::API_BASE_URL . 'v1/gifs/random?' . http_build_query(['api_key' => $this->apiKey, 'rating' => $this->rating, 'tag' => implode(' ', $command->getParameters())])));
     $result = json_decode($response->getBody(), true);
     return $this->chatClient->postMessage($command->getRoom(), $this->getMessage($result));
 }
コード例 #7
0
ファイル: Haskell.php プロジェクト: Room-11/Jeeves
 public function run(Command $command) : Generator
 {
     if (!$command->hasParameters()) {
         return $this->chatClient->postMessage($command->getRoom(), self::USAGE);
     }
     $form = (new FormBody())->addField("exp", implode(" ", $command->getParameters()));
     $request = (new Request())->setMethod("POST")->setUri("https://tryhaskell.org/eval")->setBody($form);
     $response = (yield $this->httpClient->request($request));
     return $this->chatClient->postMessage($command->getRoom(), $this->getMessage($response));
 }
コード例 #8
0
ファイル: Urban.php プロジェクト: Room-11/Jeeves
 public function search(Command $command) : \Generator
 {
     if (!$command->hasParameters()) {
         return new Success();
     }
     /** @var HttpResponse $response */
     $response = (yield $this->httpClient->request('http://api.urbandictionary.com/v0/define?term=' . rawurlencode(implode(' ', $command->getParameters()))));
     $result = json_decode($response->getBody(), true);
     return $this->chatClient->postMessage($command->getRoom(), $this->getMessage($result), PostFlags::TRUNCATE);
 }
コード例 #9
0
ファイル: Mdn.php プロジェクト: Room-11/Jeeves
 public function search(Command $command) : \Generator
 {
     if (!$command->hasParameters()) {
         return new Success();
     }
     /** @var HttpResponse $response */
     $response = (yield $this->httpClient->request('https://developer.mozilla.org/en-US/search.json?highlight=false&q=' . rawurlencode(implode('%20', $command->getParameters()))));
     $result = json_decode($response->getBody(), true);
     if (!isset($result["documents"][0]["id"], $result["documents"][0]["url"])) {
         return $this->postNoResult($command);
     }
     return $this->postResult($command, $result["documents"][0]);
 }
コード例 #10
0
ファイル: Man.php プロジェクト: Room-11/Jeeves
 public function search(Command $command) : \Generator
 {
     if (!$command->hasParameters()) {
         return new Success();
     }
     /** @var HttpResponse $response */
     $response = (yield $this->httpClient->request("https://man.freebsd.org/" . rawurlencode(implode("%20", $command->getParameters()))));
     $dom = domdocument_load_html($response->getBody());
     $xpath = new \DOMXPath($dom);
     if (!$this->isFound($xpath)) {
         return $this->postNoResult($command);
     }
     return $this->postResult($command, $xpath, $response->getRequest()->getUri());
 }
コード例 #11
0
ファイル: Canon.php プロジェクト: Room-11/Jeeves
 private function remove(Command $command, string $canonTitle) : Promise
 {
     // !!canon remove mysql
     return resolve(function () use($command, $canonTitle) {
         if (!$command->hasParameters(2)) {
             return $this->chatClient->postMessage($command->getRoom(), self::USAGE);
         }
         $canonicals = (yield $this->storage->getAll($command->getRoom()));
         if (!in_array($canonTitle, array_keys($canonicals))) {
             return $this->chatClient->postMessage($command->getRoom(), "Canonical is not on the list.");
         }
         (yield $this->storage->unset($canonTitle, $command->getRoom()));
         return $this->chatClient->postMessage($command->getRoom(), "Canonical removed from the list.");
     });
 }
コード例 #12
0
ファイル: Wikipedia.php プロジェクト: Room-11/Jeeves
 public function search(Command $command) : \Generator
 {
     if (!$command->hasParameters()) {
         return new Success();
     }
     /** @var HttpResponse $response */
     $response = (yield $this->makeAPIRequest(['titles' => implode(' ', $command->getParameters())]));
     $result = json_try_decode($response->getBody(), true);
     $firstHit = reset($result['query']['pages']);
     if (!isset($firstHit['pageid'])) {
         return $this->chatClient->postReply($command, 'Sorry I couldn\'t find that page.');
     }
     $response = (yield $this->makeAPIRequest(['prop' => 'info', 'inprop' => 'url', 'pageids' => $firstHit['pageid']]));
     $page = json_try_decode($response->getBody(), true);
     return $this->chatClient->postMessage($command->getRoom(), $page['query']['pages'][$firstHit['pageid']]['canonicalurl']);
 }
コード例 #13
0
ファイル: Imdb.php プロジェクト: Room-11/Jeeves
 public function search(Command $command) : \Generator
 {
     if (!$command->hasParameters()) {
         return $this->chatClient->postReply($command, 'Mhm, I need a film title you want me to look for.');
     }
     $search = $command->getText();
     $message = (yield $this->chatClient->postMessage($command->getRoom(), sprintf('_Looking for \'%s\' for you…_', $search)));
     $params = $this->buildTitleSearchParams($search);
     // Send it out.
     /** @var HttpResponse $response */
     $response = (yield $this->httpClient->request(sprintf('%s?%s', self::OMDB_API_ENDPOINT, http_build_query($params))));
     /** @var \stdClass $data */
     $data = @json_decode($response->getBody());
     if (!$data || $data->Response === 'False') {
         return $this->chatClient->postMessage($command->getRoom(), 'I couldn\'t find anything for that title.');
     }
     $searchResults = [];
     foreach ($data->Search as $searchResult) {
         $searchResults[$searchResult->imdbID] = $searchResult;
     }
     // Only pick the top 3 results if needed.
     $searchResults = array_slice($searchResults, 0, 3, true);
     /** @var PostedMessage $chatMessage */
     (yield $this->chatClient->editMessage($message, $this->formatSearchResults($searchResults)));
     $requests = [];
     // Send out multiple http requests to get film descriptions and ratings.
     foreach ($searchResults as $id => $searchResult) {
         $requests[$id] = sprintf('%s?%s', self::OMDB_API_ENDPOINT, http_build_query($this->buildTitleDescParams($id)));
     }
     // Wait until all requests are done, allow failures.
     $allRequests = \Amp\some($this->httpClient->requestMulti($requests));
     list($errors, $responses) = (yield $allRequests);
     $descriptionResults = [];
     foreach ($responses as $key => $response) {
         $responseBody = @json_decode($response->getBody());
         if (!$responseBody || $responseBody->Response === 'False') {
             continue;
         }
         $descriptionResults[$key] = $responseBody;
     }
     return $this->chatClient->editMessage($message, $this->formatSearchResults($searchResults, $descriptionResults));
 }
コード例 #14
0
ファイル: Reminder.php プロジェクト: Room-11/Jeeves
 /**
  * Handle a command message
  *
  * According to http://www.strawpoll.me/11212318/r this plugin will support the following commands
  * !!<reminder|remind> remind this <in|at> <time>
  * !!at <time> remind this
  * !!in <time> remind this
  *
  * @param Command $command
  * @return Promise
  */
 public function handleCommand(Command $command) : Promise
 {
     return resolve(function () use($command) {
         if ($command->hasParameters() === false) {
             return $this->chatClient->postMessage($command->getRoom(), self::USAGE);
         }
         /* $command->getParameter(0) can be: list | examples | flush | unset | <text> | <time> */
         $textOrCommand = $command->getParameter(0);
         $commandName = $command->getCommandName();
         // <reminder|in|at>
         switch ($commandName) {
             case 'in':
                 return (yield $this->setReminder($command, 'in'));
             case 'at':
                 return (yield $this->setReminder($command, 'at'));
             case 'reminder':
                 break;
         }
         if (count(array_diff($command->getParameters(), array($textOrCommand))) < 1) {
             switch ($textOrCommand) {
                 case 'list':
                     return (yield $this->getAllReminders($command));
                 case 'examples':
                     return (yield $this->getExamples($command));
                 case 'nuke':
                     // nukes all reminders
                     return (yield $this->nuke($command));
             }
         }
         if ($command->getParameter(0) === 'unset' && $command->getParameter(1) !== null && count($command->getParameters()) <= 2) {
             return (yield $this->unset($command));
         }
         return (yield $this->setReminder($command, 'reminder'));
     });
 }
コード例 #15
0
ファイル: Ban.php プロジェクト: Room-11/Jeeves
 /**
  * Handle a command message
  *
  * @param CommandMessage $command
  * @return Promise
  */
 public function handleCommand(CommandMessage $command) : Promise
 {
     return $command->hasParameters() ? resolve($this->execute($command)) : new Success();
 }
コード例 #16
0
ファイル: Google.php プロジェクト: Room-11/Jeeves
 public function search(Command $command) : \Generator
 {
     if (!$command->hasParameters()) {
         return new Success();
     }
     $text = implode(' ', $command->getParameters());
     $searchTerm = (yield $this->messageResolver->resolveMessageText($command->getRoom(), $text));
     $uri = $this->getSearchURL($searchTerm);
     $request = (new HttpRequest())->setMethod('GET')->setUri($uri)->setHeader('User-Agent', self::USER_AGENT);
     /** @var HttpResponse $response */
     $response = (yield $this->httpClient->request($request));
     if ($response->getStatus() !== 200) {
         return $this->chatClient->postMessage($command->getRoom(), "Google responded with {$response->getStatus()}");
     }
     if (preg_match('#charset\\s*=\\s*([^;]+)#i', trim(implode(', ', $response->getHeader('Content-Type'))), $match) && !preg_match('/' . preg_quote(self::ENCODING, '/') . '/i', $match[1])) {
         $body = iconv($match[1], self::ENCODING, $response->getBody());
     }
     if (empty($body)) {
         $body = $response->getBody();
     }
     $dom = domdocument_load_html($body);
     $xpath = new \DOMXPath($dom);
     $nodes = $this->getResultNodes($xpath);
     if ($nodes->length === 0) {
         return $this->postNoResultsMessage($command);
     }
     $searchResults = $this->getSearchResults($nodes, $xpath);
     $postMessage = $this->getPostMessage($searchResults, $uri, $searchTerm);
     return $this->chatClient->postMessage($command->getRoom(), $postMessage);
 }
コード例 #17
0
ファイル: PHPSrcGrok.php プロジェクト: Room-11/Jeeves
 public function getDefinition(Command $command) : \Generator
 {
     if (!$command->hasParameters()) {
         return;
     }
     list($branch, $searchTerm) = $this->getBranchAndSearchTerm($command);
     try {
         $results = (yield from $this->getOpenGrokSearchResults($branch, ['defs' => $searchTerm]));
     } catch (OpenGrokSearchFailureException $e) {
         if ($e->getCode()) {
             yield from $this->chatClient->postReply($command, $e->getMessage());
             return;
         }
         $results = [];
     }
     if ($result = $this->findCSymbolDefinition($results, $searchTerm)) {
         yield from $this->chatClient->postMessage($command->getRoom(), $this->formatResultMessage($result));
         return;
     }
     try {
         $results = (yield from $this->getOpenGrokSearchResults($branch, ['refs' => $searchTerm]));
     } catch (OpenGrokSearchFailureException $e) {
         yield from $this->chatClient->postReply($command, $e->getMessage());
         return;
     }
     if ($result = $this->findPHPSymbolDefinition($results, $searchTerm)) {
         yield from $this->chatClient->postMessage($command->getRoom(), $this->formatResultMessage($result));
         return;
     }
     yield from $this->chatClient->postReply($command, 'Nothing went wrong but I couldn\'t find a suitable definition. Ping DaveRandom if you think I should have done.');
 }
コード例 #18
0
ファイル: EvalCode.php プロジェクト: Room-11/Jeeves
 public function eval(Command $command) : Promise
 {
     if (!$command->hasParameters()) {
         return new Success();
     }
     $code = $this->normalizeCode($command->getText());
     $body = (new FormBody())->addField("title", "")->addField("code", $code);
     $request = (new HttpRequest())->setUri("https://3v4l.org/new")->setMethod("POST")->setHeader("Accept", "application/json")->setBody($body);
     $deferred = new Deferred();
     $this->queue->push([$request, $command->getRoom(), $deferred]);
     if (!$this->haveLoop) {
         resolve($this->executeActionsFromQueue());
     }
     return $deferred->promise();
 }