Ejemplo n.º 1
0
 public function testWildcardCallToMessage()
 {
     $client = new Client('http://fake.endpoint');
     $message = $client->to('@regan');
     $this->assertInstanceOf('Maknz\\Slack\\Message', $message);
     $this->assertSame('@regan', $message->getChannel());
 }
 /**
  * Send a message to the configured slack channel
  * @param $message
  * @return null
  */
 protected function send($message)
 {
     $chan = is_null($this->channel) ? $this->config['slack']['channel'] : '#' . $this->channel;
     $settings = ['username' => $this->config['slack']['username'], 'channel' => $chan];
     $client = new Maknz\Slack\Client($this->config['slack']['endpoint'], $settings);
     $client->send($message);
 }
Ejemplo n.º 3
0
 /**
  * Sends the log message to slack.
  */
 public function export()
 {
     $error = ArrayHelper::getValue($this->messages[0], 0, 'Unknown Error');
     $message = $this->client->createMessage();
     $text = is_object($error) ? $error->__toString() : $error;
     $message->attach(['title' => ArrayHelper::getValue($this->messages[0], 2, 'Site Error'), 'text' => $text, 'fallback' => $text, 'color' => $this->color, 'fields' => $this->getContextAttachment()]);
     $message->send();
 }
Ejemplo n.º 4
0
 /**
  * Report or log an exception.
  *
  * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
  *
  * @param  \Exception  $e
  * @return void
  */
 public function report(Exception $e)
 {
     if (true === env('SLACK_NOTIFY') && $e) {
         $settings = ['username' => env('SLACK_USERNAME'), 'channel' => env('SLACK_CHANNEL'), 'link_names' => true];
         $client = new Client(env('SLACK_WEBHOOKS'), $settings);
         $msgArr = ['From' => env('APP_ENV'), 'url' => Request::url(), 'Type' => get_class($e), 'ip' => Request::ip(), 'Username' => urlencode(Auth::check() ? Auth::user()->username : '******'), 'Message' => $e->getMessage(), 'File' => $e->getFile(), 'Line' => $e->getLine()];
         $client->send(urldecode(json_encode($msgArr, JSON_PRETTY_PRINT)));
     }
     return parent::report($e);
 }
Ejemplo n.º 5
0
 /**
  * Check if slack is enabled, if so send the snapshot to the relevant
  * channel.
  *
  * @param EventInterface $event
  * @throws EndPointNotSetException
  */
 public function handle(EventInterface $event)
 {
     if ($this->config['slack']['enabled']) {
         if (empty($this->config['slack']['endpoint'])) {
             throw new EndPointNotSetException("You must set the endpoint for your slack channel.");
         }
         $client = new Client($this->config['slack']['endpoint'], $this->config['slack']['settings']);
         $client->send($this->getMessage($event->getSnapshot()));
     }
 }
Ejemplo n.º 6
0
 /**
  * Send report to Slack.
  *
  * $param array $to
  *   Comma separated list of Slack channels ("#") and/or users ("@") to send message to.
  * @param string $message
  *   List of message attachment options. https://github.com/maknz/slack#send-an-attachment-with-fields
  * @param array $channelNames
  *   The name of the channel to send the message to.
  */
 public function alert($channelNames, $message, $tos = ['@dee'])
 {
     $to = implode(',', $tos);
     foreach ($channelNames as $channelName) {
         $channelKey = $this->lookupChannelKey($channelName);
         $slack = new Client($channelKey);
         $slack->to($to)->attach($message)->send();
         $this->statHat->ezCount('MB_Toolbox: MB_Slack: alert', 1);
     }
 }
Ejemplo n.º 7
0
 public function testMessageWithAttachmentsAndFields()
 {
     $attachmentArray = ['fallback' => 'Some fallback text', 'text' => 'Some text to appear in the attachment', 'pretext' => null, 'color' => 'bad', 'mrkdwn_in' => [], 'image_url' => 'http://fake.host/image.png', 'thumb_url' => 'http://fake.host/image.png', 'title' => 'A title', 'title_link' => 'http://fake.host/', 'author_name' => 'Joe Bloggs', 'author_link' => 'http://fake.host/', 'author_icon' => 'http://fake.host/image.png', 'fields' => [['title' => 'Field 1', 'value' => 'Value 1', 'short' => false], ['title' => 'Field 2', 'value' => 'Value 2', 'short' => false]]];
     $expectedHttpData = ['username' => 'Test', 'channel' => '#general', 'text' => 'Message', 'link_names' => false, 'unfurl_links' => false, 'unfurl_media' => true, 'mrkdwn' => true, 'attachments' => [$attachmentArray]];
     $client = new Client('http://fake.endpoint', ['username' => 'Test', 'channel' => '#general']);
     $message = $client->createMessage()->setText('Message');
     $attachment = new Attachment($attachmentArray);
     $message->attach($attachment);
     $payload = $client->preparePayload($message);
     $this->assertEquals($expectedHttpData, $payload);
 }
 /**
  * @param string $message
  * @param string $type
  * @param array $attachment
  */
 public function post($message, $type, $attachment = [])
 {
     $type = \Config::get('slack.types.' . strtolower($type), \Config::get('slack.default', []));
     $webHookUrl = \Config::get('slack.webHookUrl');
     $client = new Client($webHookUrl, ['username' => array_get($type, 'username', 'FamarryBot'), 'channel' => array_get($type, 'channel', '#random'), 'link_names' => true, 'icon' => array_get($type, 'icon', ':smile:')]);
     $messageObj = $client->createMessage();
     if (!empty($attachment)) {
         $attachment = new Attachment(['fallback' => array_get($attachment, 'fallback', ''), 'text' => array_get($attachment, 'text', ''), 'pretext' => array_get($attachment, 'pretext', ''), 'color' => array_get($attachment, 'color', 'good'), 'fields' => array_get($attachment, 'fields', [])]);
         $messageObj->attach($attachment);
     }
     $messageObj->setText($message)->send();
 }
Ejemplo n.º 9
0
 public function testMessageWithAttachmentsAndActions()
 {
     $now = new DateTime();
     $attachmentInput = ['fallback' => 'Some fallback text', 'text' => 'Some text to appear in the attachment', 'pretext' => null, 'color' => 'bad', 'footer' => 'Footer', 'footer_icon' => 'https://platform.slack-edge.com/img/default_application_icon.png', 'timestamp' => $now, 'mrkdwn_in' => [], 'image_url' => 'http://fake.host/image.png', 'thumb_url' => 'http://fake.host/image.png', 'title' => 'A title', 'title_link' => 'http://fake.host/', 'author_name' => 'Joe Bloggs', 'author_link' => 'http://fake.host/', 'author_icon' => 'http://fake.host/image.png', 'fields' => [], 'actions' => [['name' => 'Name 1', 'text' => 'Text 1', 'style' => 'default', 'type' => 'button', 'value' => 'Value 1', 'confirm' => ['title' => 'Title 1', 'text' => 'Text 1', 'ok_text' => 'OK Text 1', 'dismiss_text' => 'Dismiss Text 1']], ['name' => 'Name 2', 'text' => 'Text 2', 'style' => 'default', 'type' => 'button', 'value' => 'Value 2', 'confirm' => ['title' => 'Title 2', 'text' => 'Text 2', 'ok_text' => 'OK Text 2', 'dismiss_text' => 'Dismiss Text 2']]]];
     $attachmentOutput = ['fallback' => 'Some fallback text', 'text' => 'Some text to appear in the attachment', 'pretext' => null, 'color' => 'bad', 'footer' => 'Footer', 'footer_icon' => 'https://platform.slack-edge.com/img/default_application_icon.png', 'ts' => $now->getTimestamp(), 'mrkdwn_in' => [], 'image_url' => 'http://fake.host/image.png', 'thumb_url' => 'http://fake.host/image.png', 'title' => 'A title', 'title_link' => 'http://fake.host/', 'author_name' => 'Joe Bloggs', 'author_link' => 'http://fake.host/', 'author_icon' => 'http://fake.host/image.png', 'fields' => [], 'actions' => [['name' => 'Name 1', 'text' => 'Text 1', 'style' => 'default', 'type' => 'button', 'value' => 'Value 1', 'confirm' => ['title' => 'Title 1', 'text' => 'Text 1', 'ok_text' => 'OK Text 1', 'dismiss_text' => 'Dismiss Text 1']], ['name' => 'Name 2', 'text' => 'Text 2', 'style' => 'default', 'type' => 'button', 'value' => 'Value 2', 'confirm' => ['title' => 'Title 2', 'text' => 'Text 2', 'ok_text' => 'OK Text 2', 'dismiss_text' => 'Dismiss Text 2']]]];
     $client = new Client('http://fake.endpoint', ['username' => 'Test', 'channel' => '#general']);
     $message = $client->createMessage()->setText('Message');
     $attachment = new Attachment($attachmentInput);
     $message->attach($attachment);
     $payload = $client->preparePayload($message);
     $expectedHttpData = ['username' => 'Test', 'channel' => '#general', 'text' => 'Message', 'link_names' => 0, 'unfurl_links' => false, 'unfurl_media' => true, 'mrkdwn' => true, 'attachments' => [$attachmentOutput]];
     $this->assertEquals($expectedHttpData, $payload);
 }
Ejemplo n.º 10
0
 /**
  * Send a Slack message.
  *
  * @param string $payload
  */
 public function send($payload)
 {
     $message = $this->client->createMessage();
     if (!is_string($payload)) {
         $text = null;
         if (is_array($payload)) {
             $text = $payload['message'];
         } elseif ($payload instanceof \Exception) {
             $text = $payload->getMessage();
         }
         return $message->attach($this->buildAttachment($payload))->setText($text)->send();
     }
     return $message->setText($payload)->send();
 }
Ejemplo n.º 11
0
 /**
  * Send the message
  *
  * @param string $text The text to send
  * @return void
  */
 public function send($text = null)
 {
     if ($text) {
         $this->setText($text);
     }
     $this->client->sendMessage($this);
 }
Ejemplo n.º 12
0
            }
            $hours = $row[4]->diff($row[5])->format('%hh%I');
            $hourDirection = strtolower($row[7]);
            $team[$member] = ['title' => $member, 'value' => '_' . $hours . '_ ' . $hourDirection];
            $teamFallback .= $member . ': ' . $hours . ' ' . $hourDirection . String::newLine();
            $teamCli[$member] = ['name' => $member, 'hours' => $hours, 'hourDirection' => $hourDirection];
        }
    }
}
$reader->close();
if (!empty($configuration['slackEndpoint']) && !empty($configuration['channel'])) {
    Cli::writeOutput('Notifying Slack team', Cli::COLOR_GREEN_DIM);
    // Instantiate with defaults, so all messages created
    // will be sent from 'Cyril' and to the #accounting channel
    // by default. Any names like @regan or #channel will also be linked.
    $client = new Client($configuration['slackEndpoint'], ['username' => 'HourBank', 'channel' => $configuration['channel'], 'icon' => ':clock4:', 'markdown_in_attachments' => ['fields']]);
    /** @var $client Message */
    !$dryRun && $client->attach(['fallback' => $teamFallback, 'color' => 'bad', 'fields' => $team])->send($headLine);
}
if ($configuration['markAsDone']) {
    $modify = new Google_Service_Gmail_ModifyMessageRequest();
    $modify->setRemoveLabelIds(['INBOX']);
    !$dryRun && $service->users_messages->modify($user, $message->getId(), $modify);
    Cli::writeOutput('Message marked as *done*', Cli::COLOR_YELLOW_DIM);
}
if ($configuration['removeMessage'] && !$dryRun) {
    !$dryRun && $service->users_messages->trash($user, $message->getId());
    Cli::writeOutput('Message moved to trash!', Cli::COLOR_YELLOW_DIM);
}
if ($headLine) {
    Cli::writeOutput(String::newLine() . $headLine . String::newLine(), Cli::COLOR_WHITE_BOLD);
Ejemplo n.º 13
0
 /**
  * Send reviews to Slack
  *
  * @param  array   $reviews   list of reviews to send
  * @return boolean successful sending
  */
 public function sendReviews($reviews)
 {
     if (!is_array($reviews) || !count($reviews)) {
         return false;
     }
     if (!isset($this->slackSettings['endpoint'])) {
         if ($this->logger) {
             $this->logger->error('Reviewer: you should set endpoint in Slack settings');
         }
         return false;
     }
     $config = ['username' => 'TJ Reviewer', 'icon' => 'https://i.imgur.com/GX1ASZy.png'];
     if (isset($this->slackSettings['channel'])) {
         $config['channel'] = $this->slackSettings['channel'];
     }
     $slack = new Slack($this->slackSettings['endpoint'], $config);
     foreach ($reviews as $review) {
         $ratingText = '';
         for ($i = 1; $i <= 5; $i++) {
             $ratingText .= $i <= $review['rating'] ? "★" : "☆";
         }
         try {
             if ($this->firstTime === false) {
                 $slack->attach(['fallback' => "{$ratingText} {$review['title']} — {$review['content']}", 'author_name' => $review['application']['name'], 'author_icon' => $review['application']['image'], 'author_link' => $review['application']['link'], 'color' => $review['rating'] >= 4 ? 'good' : ($review['rating'] == 3 ? 'warning' : 'danger'), 'fields' => [['title' => $review['title'], 'value' => $review['content']], ['title' => 'Rating', 'value' => $ratingText, 'short' => true], ['title' => 'Author', 'value' => "<{$review['author']['uri']}|{$review['author']['name']}>", 'short' => true], ['title' => 'Version', 'value' => $review['application']['version'], 'short' => true], ['title' => 'Country', 'value' => $review['country'], 'short' => true]]])->send();
             }
             $this->storage->set("r{$review['id']}", 1);
         } catch (Exception $e) {
             if ($this->logger) {
                 $this->logger->error('Reviewer: exception while sending reviews', ['exception' => $e]);
             }
         }
     }
     return true;
 }
Ejemplo n.º 14
0
 /**
  * Send the message
  *
  * @param $message
  */
 protected function send($message)
 {
     $this->client->send($message);
     $this->client = null;
 }
Ejemplo n.º 15
0
 /**
  * Send slack report.
  *
  * @return mixed
  */
 public function send()
 {
     return $this->client->createMessage()->attach($this->buildPayload())->send();
 }
Ejemplo n.º 16
0
 /**
  * Prepares the payload to be sent to the webhook
  *
  * @param \Maknz\Slack\Message $message The message to send
  * @return array 
  * @static 
  */
 public static function preparePayload($message)
 {
     return \Maknz\Slack\Client::preparePayload($message);
 }
Ejemplo n.º 17
0
 /**
  * Send a message to the configured slack channel
  * @param $message
  * @return null
  */
 protected function send($message)
 {
     $settings = ['username' => $this->config['slack']['username'], 'channel' => $this->config['slack']['channel']];
     $client = new Maknz\Slack\Client($this->config['slack']['endpoint'], $settings);
     $client->attach(['text' => (string) $message, 'color' => 'good'])->send('New user connected');
 }
Ejemplo n.º 18
0
 protected function sendToSlack($message)
 {
     $this->client->send($message);
 }
 public function doRun(InputInterface $input, OutputInterface $output)
 {
     $this->input = $input;
     $this->output = $output;
     $archive = null;
     $fatalError = [];
     $errorJS = 0;
     $errorPHP = 0;
     $warningPHP = 0;
     $output->writeln('<fg=white;options=bold;bg=red>Code Quality Tool Note</fg=white;options=bold;bg=red>');
     $output->writeln('<info>Fetching files</info>');
     $files = $this->extractCommitedFiles();
     $output->writeln('<info>Running PHPLint</info>');
     $phpLint = $this->phpLint($files);
     if ($phpLint !== true) {
         $this->output->writeln(sprintf('<error>%s</error>', $phpLint['line']));
         $this->output->writeln(sprintf('<error>%s</error>', $phpLint['error']));
         $fatalError[] = $phpLint['error'];
         $errorPHP += count($phpLint['error']);
     }
     if (!isset($this->config->run->phpcsfix) || $this->config->run->phpcsfix == 'true') {
         $output->writeln('<info>Checking code style</info>');
         $codeStyle = $this->codeStyle($files);
         if ($codeStyle !== true) {
             $this->output->writeln(sprintf('<error>%s</error>', $codeStyle));
         }
     }
     $output->writeln('<info>Checking code style with PHPCS</info>');
     $codeStylePsr = $this->codeStylePsr($files);
     if ($codeStylePsr !== true) {
         $this->output->writeln(sprintf('<error>%s</error>', $codeStylePsr));
         $pos = strpos($codeStylePsr, 'FOUND');
         $rest = substr($codeStylePsr, $pos, 100);
         $explode = explode(' ', $rest);
         $errorPHP += $explode[1];
         $warningPHP += $explode[4];
     }
     $output->writeln('<info>Checking code style with PHPCS JS</info>');
     $codeStyleJS = $this->codeStyleJS($files);
     if ($codeStyleJS !== true) {
         $this->output->writeln(sprintf('<error>%s</error>', $codeStyleJS));
         $pos = strpos($codeStyleJS, 'FOUND');
         $rest = substr($codeStyleJS, $pos, 30);
         $explode = explode(' ', $rest);
         $errorJS = $explode[1];
     }
     $output->writeln('<info>Checking code mess with PHPMD</info>');
     $phpmd = $this->phPmd($files);
     if ($phpmd !== true) {
         $this->output->writeln(sprintf('<error>%s</error>', $phpmd['file']));
         $this->output->writeln(sprintf('<error>%s</error>', $phpmd['errorOutput']));
         $this->output->writeln(sprintf('<error>%s</error>', $phpmd['error']));
         //count line erros
         $explode = array_filter(explode("\n", $phpmd['error']));
         $warningPHP += count($explode);
     }
     if (!isset($this->config->run->phpunit) || $this->config->run->phpunit == 'true') {
         $output->writeln('<info>Running unit tests</info>');
         if (!$this->unitTests()) {
             throw new \Exception('Fix the f*****g unit tests!');
         }
     }
     $author = null;
     exec('git config --get user.name', $author);
     $message = 'Rating *A*. Good work!';
     if ($errorPHP >= 1 || $errorJS >= 1 || $warningPHP >= 1) {
         $message = 'Rating *B*. warnings (`' . $warningPHP . '` in PHP) errors (`' . $errorJS . '` in JS, `' . $errorPHP . '` in PHP)';
     }
     if (count($fatalError) >= 1) {
         $message = 'Rating *C*. warnings (`' . $warningPHP . '` in PHP) errors (`' . $errorJS . '` in JS, `' . $errorPHP . '` in PHP)';
     }
     if (preg_match("/(\\*B\\*)|(\\*C\\*)/", $message)) {
         $output->write('<question>There were some errors in the test, do you still want to commit? (Y/n)</question>: ');
         do {
             set_time_limit(0);
             @ob_end_flush();
             ob_implicit_flush(true);
             $cmdline = new Prompt();
             $return = strtoupper($cmdline->get());
             if ($return !== 'N' || $return !== 'Y') {
                 $output->write('<bg=red>Invalid response! Y for yes, N for no</>: ');
             }
             if ($return === 'N') {
                 throw new \Exception("\n###### Commit Aborted! #######\n");
             }
         } while ($return !== 'Y');
     }
     $msgOut = str_replace('`', '', str_replace('*', '', $message));
     $output->writeln('<info>Commit ' . $author[0] . ':' . $msgOut . '</info>');
     if (isset($this->config->run->slack) && $this->config->run->slack == 'true' && isset($this->config->slackConfig)) {
         $settings = ['username' => strval($this->config->slackConfig->username), 'channel' => strval($this->config->slackConfig->channel), 'icon' => strval($this->config->slackConfig->icon)];
         $client = new Client(strval($this->config->slackConfig->url), $settings);
         $client->send('Commit *' . $author[0] . '*: ' . $message . '');
     }
 }
Ejemplo n.º 20
0
 public function send()
 {
     $this->client->to($this->config['channel'])->attach(['text' => $this->message, 'color' => $this->type === static::TYPE_SUCCESS ? 'good' : 'warning'])->send($this->subject);
 }
Ejemplo n.º 21
0
 /**
  * @param Release $release
  * @param string $channel
  * @param string $title
  * @param array $message
  */
 protected function sendNotification(Release $release, $channel, $title, array $message)
 {
     $message = $this->slack->createMessage()->to($channel)->attach($message + ['fallback' => $title, 'fields' => $this->describeCommitFields($release, $release->commit())]);
     $this->slack->send($message);
 }