/**
  * {@inheritdoc}
  */
 protected function createPayload()
 {
     $payload = new ChatPostMessagePayload();
     $payload->setChannel('#acme_channel');
     $payload->setUsername('acme_user');
     $payload->setText('Hello World!');
     $payload->setIconEmoji(':truck:');
     $payload->setLinkNames(true);
     $payload->setParse('full');
     $payload->setUnfurlLinks(true);
     $payload->setUnfurlMedia(false);
     $payload->setIconUrl('http://foo.bar/emoji-1.png');
     $fakeAttachmentField = new AttachmentField();
     $fakeAttachmentField->setShort(false);
     $fakeAttachmentField->setTitle('the title');
     $fakeAttachmentField->setValue('the value');
     $fakeAttachment = new Attachment();
     $fakeAttachment->setTitle('the title');
     $fakeAttachment->setTitleLink('http://thetitlelink.com');
     $fakeAttachment->setColor('the color');
     $fakeAttachment->setFallback('the fallback');
     $fakeAttachment->setImageUrl('the image url');
     $fakeAttachment->setPreText('this is...');
     $fakeAttachment->setText('my attachment');
     $fakeAttachment->setAuthorIcon(':skull:');
     $fakeAttachment->setAuthorName('the author');
     $fakeAttachment->setAuthorLink('http://theauthor.com');
     $fakeAttachment->addField($fakeAttachmentField);
     $payload->addAttachment($fakeAttachment);
     return $payload;
 }
 /**
  * @return ChatPostMessagePayload
  */
 protected function createPayload()
 {
     $payload = new ChatPostMessagePayload();
     $channel = $this->input->getArgument('channel');
     // help support un-escaped channel names such as 'general' (the hash-sign requires the channel name to be quoted)
     // also making sure to ignore it if a channel ID was given
     // @todo Reconsider this approach; different channel formats could be allowed that might conflict with this
     if (substr($channel, 0, 1) !== '#' && !(substr($channel, 0, 1) === 'G' && is_numeric(substr($channel, 1)))) {
         $channel = '#' . $channel;
     }
     $payload->setChannel($channel);
     $payload->setText($this->input->getArgument('text'));
     if ($this->input->getOption('username')) {
         $payload->setUsername($this->input->getOption('username'));
     }
     if ($this->input->getOption('icon-url')) {
         $payload->setIconUrl($this->input->getOption('icon-url'));
     }
     if ($this->input->getOption('icon-emoji')) {
         $payload->setIconEmoji($this->input->getOption('icon-emoji'));
     }
     if ($this->input->getOption('parse')) {
         $payload->setParse($this->input->getOption('parse'));
     }
     if ($this->input->getOption('link-names')) {
         $payload->setLinkNames($this->input->getOption('link-names'));
     }
     if ($this->input->getOption('unfurl-links')) {
         $payload->setUnfurlLinks($this->input->getOption('unfurl-links'));
     }
     if ($this->input->getOption('unfurl-media')) {
         $payload->setUnfurlMedia($this->input->getOption('unfurl-media'));
     }
     return $payload;
 }
 /**
  * Send messages for remaining associations.
  *
  * This method is limited to 20 seconds to be able to display nice error message instead of being timed out by Heroku.
  *
  * @param SecretSanta $secretSanta
  *
  * @throws \RuntimeException
  */
 public function dispatchRemainingMessages(SecretSanta $secretSanta)
 {
     $startTime = time();
     try {
         foreach ($secretSanta->getRemainingAssociations() as $giver => $receiver) {
             if (time() - $startTime > 19) {
                 throw new \RuntimeException('It takes too much time to contact Slack! Please press the Retry button.');
             }
             $text = sprintf("Hi! You have been chosen to be part of a Secret Santa!\n\nSomeone has been chosen to get you a gift; and *you* have been chosen to gift <@%s>!", $receiver);
             if (!empty($secretSanta->getAdminMessage())) {
                 $text .= "\n\nHere is a message from the Secret Santa admin:\n\n```" . $secretSanta->getAdminMessage() . '```';
             }
             if ($secretSanta->getAdminUserId()) {
                 $text .= sprintf("\n\nMessage sent via <@%s>.", $secretSanta->getAdminUserId());
             }
             $message = new ChatPostMessagePayload();
             $message->setChannel(sprintf('@%s', $giver));
             $message->setText($text);
             $message->setUsername('Secret Santa Bot');
             $message->setIconUrl('https://slack-secret-santa.herokuapp.com/images/logo.png');
             $this->sendPayload($message);
             $secretSanta->markAssociationAsProceeded($giver);
         }
     } catch (\Exception $e) {
         $secretSanta->addError($e->getMessage());
     }
 }
 /**
  * @param string[]    $userIds
  * @param string|null $adminMessage
  * @param null        $adminUserId
  *
  * @return Result
  */
 public function dispatchTo($userIds, $adminMessage = null, $adminUserId = null)
 {
     $rudolph = new Rudolph();
     $associatedUsers = $rudolph->associateUsers($userIds);
     $hash = md5(serialize($associatedUsers));
     $remainingAssociations = $associatedUsers;
     $error = null;
     try {
         foreach ($associatedUsers as $giver => $receiver) {
             $text = sprintf("Hi! You have been chosen to be part of a Secret Santa!\n\nSomeone has been chosen to get you a gift; and *you* have been chosen to gift <@%s>!", $receiver);
             if (!empty($adminMessage)) {
                 $text .= "\n\nHere is a message from the Secret Santa admin:\n\n```" . strip_tags($adminMessage) . '```';
             }
             if ($adminUserId) {
                 $text .= sprintf("\n\nMessage sent via <@%s>.", $adminUserId);
             }
             $message = new ChatPostMessagePayload();
             $message->setChannel(sprintf('@%s', $giver));
             $message->setText($text);
             $message->setUsername('Secret Santa Bot');
             $message->setIconUrl('https://slack-secret-santa.herokuapp.com/images/logo.png');
             $this->sendPayload($message);
             unset($remainingAssociations[$giver]);
         }
     } catch (\Exception $e) {
         $error = $e->getMessage();
     }
     return new Result($hash, $remainingAssociations, $error);
 }
Esempio n. 5
0
 /**
  * @param array $settings
  * @param boolean $lunchesToSlack
  */
 public function __construct(array $settings = array(), $lunchesToSlack = true)
 {
     $this->httpClient = new GuzzleHttp\Client();
     $this->slackPayload = new CL\Slack\Payload\ChatPostMessagePayload();
     $this->userSettings = array_merge(['restaurantsFolder' => __DIR__ . '/restaurants', 'lunchDb' => __DIR__ . '/lunches.db', 'slackNick' => 'lunch', 'slackIcon' => 'http://i.imgur.com/PWxRcm1.png', 'slackChannel' => '#general', 'slackKey' => '1234-5678-9012-345'], $settings);
     $this->restaurantsFolder = $this->userSettings['restaurantsFolder'];
     $this->dbClient = new SQLite3($this->userSettings['lunchDb']);
     $this->slackClient = new CL\Slack\Transport\ApiClient($this->userSettings['slackKey']);
     $this->slackPayload->setChannel($this->userSettings['slackChannel']);
     $this->slackPayload->setUsername($this->userSettings['slackNick']);
     $this->slackPayload->setIconUrl($this->userSettings['slackIcon']);
     if ($lunchesToSlack) {
         $this->fetchAndParseLunches();
         $this->lunchesToSlack();
     }
 }
 function __construct()
 {
     // Configure Pheal
     Config::getInstance()->cache = new FileCache(WORKING_DIR . '/tmp/cache/');
     Config::getInstance()->access = new StaticCheck();
     Config::getInstance()->log = new FileLog(WORKING_DIR . '/tmp/log/');
     Config::getInstance()->http_ssl_verifypeer = false;
     Config::getInstance()->http_user_agent = USER_AGENT;
     // Load and configure classes
     $this->pheal = new Pheal(API_KEYID, API_VCODE);
     $this->cache = new Cacher();
     $options = $this->GetClientOptions();
     $guzzle = new Client($options);
     $this->slack = new ApiClient(SLACK_TOKEN, $guzzle);
     $this->payload = new ChatPostMessagePayload();
     $this->payload->setChannel(SLACK_CHANNEL);
     $this->payload->setUsername(SLACK_USERNAME);
 }
Esempio n. 7
0
 public function send(Message $message)
 {
     $payload = new ChatPostMessagePayload();
     $payload->setChannel($this->channel);
     $payload->setUsername('Your X');
     $payload->setIconUrl('https://avatars.slack-edge.com/2016-01-07/17979318133_8214b25cb250e363ff1a_48.png');
     $payload->setLinkNames(true);
     $payload->setText($message->getText());
     $this->apiClient->send($payload);
 }
Esempio n. 8
0
 private function post($view, GameAction $action, $char = null)
 {
     $content = $this->twig->render("::" . $view . ".text.twig", array('game' => $action->getGame(), 'action' => $action, 'char' => $char));
     $payload = new ChatPostMessagePayload();
     $payload->setChannel("#" . $action->getChannelName());
     $payload->setText($content);
     $payload->setUsername("Hangbot");
     $response = $this->slack->send($payload);
     return $response;
 }
Esempio n. 9
0
 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));
 }
Esempio n. 10
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;
 }
Esempio n. 11
0
 /**
  * {@inheritdoc}
  */
 public function send($message, array $options)
 {
     $payload = new ChatPostMessagePayload();
     $payload->setChannel($this->channel);
     $payload->setText($message);
     $payload->setUsername($this->user);
     try {
         $response = $this->client->send($payload);
         if ($response->isOk()) {
             return true;
         } else {
             $this->logger->error($response->getErrorExplanation());
             return false;
         }
     } catch (\CL\Slack\Exception\SlackException $e) {
         $this->logger->error($e);
         return false;
     }
 }
Esempio n. 12
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);
     }
 }
 /**
  * {@inheritdoc}
  */
 public function notifySlackUser($from, $to, $message)
 {
     try {
         $payload = new ChatPostMessagePayload();
         $payload->setChannel("@{$to}");
         $payload->setUsername($from);
         $payload->setText($message);
         /** @var ChatPostMessagePayloadResponse $response */
         $response = $this->slack_client->send($payload);
         if (!$response->isOk()) {
             throw new NotifierException(sprintf("Can't send message to slack user: %s (%s)", $response->getError(), $response->getErrorExplanation()));
         }
         return true;
     } catch (SlackException $exception) {
         throw new NotifierException("Can't access to slack api, check credentials.", null, $exception);
     }
 }
 public function testExceptionNotifySlackUser()
 {
     $from = 'test_from';
     $to = 'test_to';
     $message = 'test_message';
     $redmine_stub = $this->getMockBuilder(RedmineClient::class)->disableOriginalConstructor()->getMock();
     $slack_stub = $this->getMockBuilder(SlackClient::class)->disableOriginalConstructor()->getMock();
     $payload = new ChatPostMessagePayload();
     $payload->setChannel("@{$to}");
     $payload->setUsername($from);
     $payload->setText($message);
     $slack_stub->expects($this->once())->method('send')->with($payload)->willThrowException(new SlackException());
     $this->expectException(NotifierException::class);
     $this->expectExceptionMessage("Can't access to slack api, check credentials.");
     (new Notifier($redmine_stub, $slack_stub))->notifySlackUser($from, $to, $message);
 }