コード例 #1
0
ファイル: ApiClientTest.php プロジェクト: wogsland/slack
 /**
  * @test
  *
  * @expectedException \CL\Slack\Exception\SlackException
  * @expectedExceptionMessage You must supply a token to send a payload, since you did not provide one during construction
  */
 public function it_can_not_send_a_payload_without_a_token()
 {
     /** @var PayloadInterface|\PHPUnit_Framework_MockObject_MockObject $mockPayload */
     $mockPayload = $this->getMock('CL\\Slack\\Payload\\PayloadInterface');
     $apiClient = new ApiClient();
     $apiClient->send($mockPayload);
 }
コード例 #2
0
ファイル: ApiClientTest.php プロジェクト: cleentfaar/slack
 /**
  * @test
  *
  * @expectedException \CL\Slack\Exception\SlackException
  * @expectedExceptionMessage You must supply a token to send a payload, since you did not provide one during construction
  */
 public function it_can_not_send_a_payload_without_a_token()
 {
     /* @var PayloadInterface|Mock\MockInterface $mockPayload */
     $mockPayload = Mock::mock(PayloadInterface::class);
     $apiClient = new ApiClient();
     $apiClient->send($mockPayload);
 }
コード例 #3
0
 /**
  * @param PayloadInterface $payload
  *
  * @return \CL\Slack\Payload\PayloadResponseInterface
  */
 private function sendPayload(PayloadInterface $payload)
 {
     $response = $this->apiClient->send($payload);
     if (!$response->isOk()) {
         throw new \RuntimeException(sprintf('%s (%s)', $response->getErrorExplanation(), $response->getError()));
     }
     return $response;
 }
コード例 #4
0
 private function getRandomUser()
 {
     $payload = new UsersListPayload();
     $response = $this->apiClient->send($payload);
     $users = $response->getUsers();
     $user = $users[array_rand($users)];
     return User::fromSlack($user);
 }
コード例 #5
0
 private function getUsers()
 {
     if (empty($this->users)) {
         $users = $this->apiClient->send(new UsersListPayload())->getUsers();
         $this->users = array_combine(array_map(function (User $user) {
             return $user->getId();
         }, $users), $users);
     }
     return $this->users;
 }
コード例 #6
0
ファイル: Provider.php プロジェクト: humweb/slackpipe
 public function post()
 {
     $content = $this->readInput();
     $client = new ApiClient($this->token);
     $payload = new ChatPostMessagePayload();
     $payload->setChannel($this->options->get('channel', '#general'));
     $payload->setUsername($this->options->get('user', 'SlackPipe Bot'));
     if (!Asserts::isEmbedUrl($content) && !Asserts::isImage($content)) {
         $payload->setText("```" . PHP_EOL . $content . '```');
     } else {
         $payload->setUnfurlLinks(true);
         $payload->setText($content);
     }
     return $this->getResponse($client->send($payload));
 }
コード例 #7
0
ファイル: ApiClientTest.php プロジェクト: billhance/slack
 public function testSendWithoutAnyToken()
 {
     /** @var PayloadInterface|\PHPUnit_Framework_MockObject_MockObject $mockPayload */
     $mockPayload = $this->getMock('CL\\Slack\\Payload\\PayloadInterface');
     $apiClient = new ApiClient();
     try {
         $apiClient->send($mockPayload);
     } catch (SlackException $e) {
         $previous = $e->getPrevious();
         $this->assertInstanceOf('\\InvalidArgumentException', $previous);
         $this->assertEquals('You must supply a token to send a payload, since you did not provide one during construction', $previous->getMessage());
         return;
     }
     $this->markTestIncomplete('This test should have thrown an exception');
 }
コード例 #8
0
 protected function notifySlack($message, $project, $env, $user, $resolverArray, $color = "#FFCC00", $update = false)
 {
     if ($update) {
         $payload = new ChatDeletePayload();
         $payload->setSlackTimestamp($this->ts);
         $payload->setChannelId($this->channel);
         $response = $this->slackApiClient->send($payload);
         if ($response->isOk()) {
             if ($response instanceof ChatPostMessagePayloadResponse) {
                 /** @var ChatPostMessagePayloadResponse $response */
                 $this->ts = $response->getSlackTimestamp();
             }
         } else {
             // something went wrong, but what?
             // simple error (Slack's error message)
             echo $response->getError();
             // explained error (Slack's explanation of the error, according to the documentation)
             echo $response->getErrorExplanation();
             exit(1);
         }
     }
     $payload = new ChatPostMessagePayload();
     $payload->setChannel("#" . getenv("slack_channel"));
     $payload->setIconUrl("https://www.dropbox.com/s/ivrj3wcze7cwh54/masterjenkins.png?dl=1");
     $payload->setUsername("Master Jenkins");
     $attachment = new Attachment();
     $attachment->setColor($color);
     $attachment->setFallback("[" . $project . "#" . getenv("BUILD_NUMBER") . " - branch *" . getenv("GIT_BRANCH") . "* to *" . $env . "* by _" . $user . "_] " . $message);
     $attachment->setText("[" . $project . "#" . getenv("BUILD_NUMBER") . " - branch *" . getenv("GIT_BRANCH") . "* to *" . $env . "* by _" . $user . "_] " . $message . "\n<" . getenv("BUILD_URL") . "console|Jenkins Console> - <" . getenv("BUILD_URL") . "changes|Changes>" . (isset($resolverArray["shared_package_target"]) && file_exists($resolverArray["shared_package_target"]) ? " - <" . $resolverArray["shared_package_url"] . "|Download>" : ""));
     $payload->addAttachment($attachment);
     $response = $this->slackApiClient->send($payload);
     if ($response->isOk()) {
         if ($response instanceof ChatPostMessagePayloadResponse) {
             /** @var ChatPostMessagePayloadResponse $response */
             $this->ts = $response->getSlackTimestamp();
             $this->channel = $response->getChannelId();
         }
     } else {
         // something went wrong, but what?
         // simple error (Slack's error message)
         echo $response->getError();
         // explained error (Slack's explanation of the error, according to the documentation)
         echo $response->getErrorExplanation();
         exit(1);
     }
 }
コード例 #9
0
 /**
  * @param string $channel
  * @param string $message
  * @param Attachment[] $attachments
  */
 public function sendToChannel($channel, $message, $attachments = [])
 {
     if ('prod' !== $this->kernel->getEnvironment()) {
         $channel = "#website-nl";
     }
     $payload = new ChatPostMessagePayload();
     $payload->setChannel($channel);
     $payload->setText($message);
     $payload->setUsername('DojoBot');
     $payload->setIconEmoji('coderdojo');
     if (false === empty($attachments)) {
         foreach ($attachments as $attachment) {
             $payload->addAttachment($attachment);
         }
     }
     $this->client->send($payload);
     return;
 }
コード例 #10
0
 /**
  * Send a notification about members who last left the corp.
  * First check if notification has not already been sent.
  * @param array $left Array of RowSetRow objects from Pheal
  * @param array $last Associative array
  */
 private function SendNotifications($left, $last)
 {
     foreach ($left as $member) {
         if ((int) $member->notificationID > (int) $last['notificationID']) {
             $message = $member->senderName . " left corp at " . $member->sentDate;
             $payload = $this->payload;
             $payload->setText($message);
             $response = $this->slack->send($payload);
             if ($response->isOk()) {
                 $this->UpdateLastLeft($member);
             }
         }
     }
 }
コード例 #11
0
 /**
  * @param ApiClient $apiClient
  */
 private function configureListeners(ApiClient $apiClient)
 {
     $output = $this->output;
     if ($output->getVerbosity() > OutputInterface::VERBOSITY_VERBOSE) {
         $self = $this;
         $apiClient->addRequestListener(function (RequestEvent $event) use($output, $self) {
             $rawRequest = $event->getRawPayload();
             $output->writeln('<comment>Debug: sending payload...</comment>');
             $self->renderKeyValueTable($rawRequest);
         });
         $apiClient->addResponseListener(function (ResponseEvent $event) use($output, $self) {
             $rawResponse = $event->getRawPayloadResponse();
             $output->writeln('<comment>Debug: received payload response...</comment>');
             $self->renderKeyValueTable($rawResponse);
         });
     }
 }
コード例 #12
0
 /**
  * Ask for Slack authentication and store the AccessToken in Session.
  *
  * @param Request $request
  *
  * @return RedirectResponse|Response
  */
 public function authenticate(Request $request)
 {
     $provider = new Slack(['clientId' => $this->slackClientId, 'clientSecret' => $this->slackClientSecret, 'redirectUri' => $this->router->generate('authenticate', [], RouterInterface::ABSOLUTE_URL)]);
     if (!$request->query->has('code')) {
         // If we don't have an authorization code then get one
         $options = ['scope' => ['chat:write:bot', 'users:read']];
         $authUrl = $provider->getAuthorizationUrl($options);
         $this->session->set(self::STATE_SESSION_KEY, $provider->getState());
         return new RedirectResponse($authUrl);
     } elseif (empty($request->query->get('state')) || $request->query->get('state') !== $this->session->get(self::STATE_SESSION_KEY)) {
         $this->session->remove(self::STATE_SESSION_KEY);
         return new Response('Invalid states.', 401);
     } else {
         // Try to get an access token (using the authorization code grant)
         $token = $provider->getAccessToken('authorization_code', ['code' => $request->query->get('code')]);
         // Who Am I?
         $test = new AuthTestPayload();
         $apiClient = new ApiClient($token->getToken());
         $response = $apiClient->send($test);
         if ($response->isOk()) {
             $this->session->set(self::TOKEN_SESSION_KEY, $token);
             $this->session->set(self::USER_ID_SESSION_KEY, $response->getUserId());
             return new RedirectResponse($this->router->generate('run'));
         } else {
             return new RedirectResponse($this->router->generate('homepage'));
         }
     }
 }