Skip to content
This repository has been archived by the owner on Jul 5, 2022. It is now read-only.

Commit

Permalink
Merge pull request #2 from DZunke/dev
Browse files Browse the repository at this point in the history
Release Merge for v1.2.0
  • Loading branch information
DZunke committed Jun 26, 2015
2 parents c8112b6 + db0a3d2 commit 64a6256
Show file tree
Hide file tree
Showing 18 changed files with 617 additions and 33 deletions.
5 changes: 2 additions & 3 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
.idea/
vendor/
composer.lock
log/
composer.phar
vendor
9 changes: 9 additions & 0 deletions CHANGELOG
Original file line number Diff line number Diff line change
@@ -1,3 +1,12 @@
SlackBundle v1.2.0
==================
- Feature: Added FileUploads
- Feature: Added Basic Implementation for Event-Driven Bots

SlackBundle v1.1.1
==================
- Feature: Downgraded requirement for GuzzleClient Version to 3.7.0 (by @toooni)

SlackBundle v1.1.0
==================
- Feature: Added Provider for Silex-Integration
Expand Down
89 changes: 89 additions & 0 deletions Command/BotMessagingCommand.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
<?php

namespace DZunke\SlackBundle\Command;

use DZunke\SlackBundle\Event;
use DZunke\SlackBundle\Events;
use DZunke\SlackBundle\Slack\Client;
use DZunke\SlackBundle\Slack\Entity\Message;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class BotMessagingCommand extends ContainerAwareCommand
{

const PROCESS_ITERATION_SLEEP = 1;

protected function configure()
{
$this
->setName('dzunke:slack:run-bot')
->setDescription('Running the Bot-User to a Channel')
->addArgument(
'channel',
InputArgument::REQUIRED,
'Channel wo Watch over'
);
}

protected function execute(InputInterface $input, OutputInterface $output)
{
$logger = new Logger(new StreamHandler('php://output'));

$channel = $this->getContainer()->get('dz.slack.channels')->getId($input->getArgument('channel'));
if (empty($channel)) {
$logger->error('channel "' . $channel . '" does not exists');
return;
}

$lastTimestamp = time();
while (true) {

try {
$latestMessages = $this->getContainer()->get('dz.slack.channels')->history($channel, $lastTimestamp);

foreach ($latestMessages as $message) {
if ($message->isBot() === true) {
continue;
}

$logger->debug('Handling Message of Type : "' . $message->getType() . '"');

$event = Event::MESSAGE;
switch ($message->getType()) {
case Message::TYPE_MESSAGE :
$event = Event::MESSAGE;
break;
case Message::TYPE_CHANNEL_JOIN:
$event = Event::JOIN;
break;
case Message::TYPE_CHANNEL_LEAVE:
$event = Event::LEAVE;
break;
}

$logger->debug('Dispatching "' . $event . '"');

$this->getContainer()->get('event_dispatcher')->dispatch(
$event,
new Events\MessageEvent($channel, $message)
);

$lastTimestamp = $message->getId();
}

$logger->debug('Handled ' . count($latestMessages) . ' Messages');

} catch (\Exception $e) {
$logger->error($e->getMessage());
$logger->error($e->getTraceAsString());
}

sleep(self::PROCESS_ITERATION_SLEEP);
}
}
}
2 changes: 1 addition & 1 deletion Command/DebugCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ protected function renderSlackChannels()
null
);

if ($channels->getStatus() == false) {
if ($channels->getStatus() === false) {
$this->output->writeln('<error>' . $channels->getError() . '</error>');

return;
Expand Down
27 changes: 27 additions & 0 deletions Event.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?php

namespace DZunke\SlackBundle;

/**
* there are some events that will be triggerd in Bot-Mode to
* react on specific actions in the watched channel
*/
class Event
{

/**
* event for standard messages
*/
const MESSAGE = 'slack.message';

/**
* event for messages that contain a joined user
*/
const JOIN = 'slack.channel.join';

/**
* event for messages that contain a leave
*/
const LEAVE = 'slack.channel.leave';

}
31 changes: 31 additions & 0 deletions Events/MessageEvent.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php

namespace DZunke\SlackBundle\Events;

use DZunke\SlackBundle\Slack\Entity\Message;
use Symfony\Component\EventDispatcher\Event;

class MessageEvent extends Event
{

/**
* @var Message
*/
private $message;

/**
* @param object $message
*/
public function __construct($message)
{
$this->message = $message;
}

/**
* @return Message
*/
public function getMessage()
{
return $this->message;
}
}
20 changes: 19 additions & 1 deletion Resources/doc/actions-list.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,24 @@ protected $parameter = [
'icon_emoji' => null,
'parse' => 'full',
'link_names' => 1,
'unfurl_links' => 1
'unfurl_links' => 1,
'attachments' => []
];
```

## files.upload

[Slack Documentation](https://api.slack.com/methods/files.upload)

Constant: \DZunke\SlackBundle\Slack\Client::ACTION_FILES_UPLOAD

``` php
protected $parameter = [
'content' => null,
'filetype' => null,
'filename' => null,
'title' => null,
'initial_comment' => null,
'channels' => null # If no Channel is given the File will be private to the API-User
];
```
16 changes: 15 additions & 1 deletion Resources/doc/services.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ There is also a way to use the "Attachment"-Feature of Slack. In this Case there
For this you must create deliver an Array of Attachments to the Message-Method.

``` php
$attachment = new Attachment();
$attachment = new DZunke\SlackBundle\Slack\Entity\MessageAttachment();
$attachment->setColor('danger');
$attachment->addField('Test1', 'Test works');

Expand All @@ -28,6 +28,20 @@ $response = $container->get('dz.slack.messaging')->message(
);
```

### File Uploads

The Messaging does include File Uploads. So the Service has an "upload"-Method to publish Reports or other Files to a Channel.
You must note that every uploaded File will be associated with the API-Key-User configured for your Slack-Client.

``` php
$response = $container->get('dz.slack.messaging')->upload(
'#foo-channel',
'Title for this File',
'/Path/to/the/file',
'Optional Comment'
);
```

## Channels

There are some operations you can do for a Channel. It is necessary to get the ChannelId from the Slack-API before you
Expand Down
47 changes: 44 additions & 3 deletions Slack/Channels.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@
namespace DZunke\SlackBundle\Slack;

use DZunke\SlackBundle\Slack\Client\Actions;
use DZunke\SlackBundle\Slack\Entity\Message;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;

class Channels
{
Expand Down Expand Up @@ -33,13 +36,15 @@ public function getClient()
*/
public function getId($channelName)
{
$channels = (array)$this->listAll()->getData();
if ($channelName[0] === 'C') {
return $channelName;
}

if (strpos($channelName, '#') !== false) {
$channelName = str_replace('#', '', $channelName);
}

foreach ($channels as $name => $data) {
foreach ((array)$this->listAll()->getData() as $name => $data) {
if ($name == $channelName) {
return $data['id'];
}
Expand Down Expand Up @@ -86,7 +91,7 @@ public function setTopic($channel, $topic)
Actions::ACTION_CHANNELS_SET_TOPIC,
[
'channel' => (string)$channel,
'topic' => (string)$topic
'topic' => (string)$topic
]
);

Expand All @@ -101,4 +106,40 @@ public function setTopic($channel, $topic)
return $response->setData($data);
}

/**
* @param string $channel
* @param int $from
* @param int $count
* @return Message[]
*/
public function history($channel, $from = null, $count = 10)
{
$messages = $this->client->send(
Client\Actions::ACTION_CHANNELS_HISTORY,
[
'channel' => $this->getId($channel),
'oldest' => is_null($from) ? time() : $from,
'count' => $count
]
);

$repository = [];
if (!empty($messages->getData()['messages'])) {
$messages = $messages->getData()['messages'];
foreach (array_reverse($messages) as $message) {
$objMsg = new Message();
$objMsg->setId($message['ts']);
$objMsg->setChannel($channel);
$objMsg->setType(isset($message['subtype']) ? $message['subtype'] : $message['type']);
$objMsg->setUserId(isset($message['user']) ? $message['user'] : null);
$objMsg->setUsername(isset($message['username']) ? $message['username'] : null);
$objMsg->setContent($message['test']);

$repository[] = $objMsg;
}
}

return $repository;
}

}
2 changes: 1 addition & 1 deletion Slack/Client.php
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ public function send($action, array $parameter)

if (
$response->getStatus() === true ||
($response->getStatus() == false && $response->getError() != Response::ERROR_RATE_LIMITED)
($response->getStatus() === false && $response->getError() != Response::ERROR_RATE_LIMITED)
) {
break;
}
Expand Down
24 changes: 14 additions & 10 deletions Slack/Client/Actions.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,23 +6,27 @@

class Actions
{
const ACTION_POST_MESSAGE = 'chat.postMessage';
const ACTION_CHANNELS_LIST = 'channels.list';
const ACTION_API_TEST = 'api.test';
const ACTION_AUTH_TEST = 'auth.test';
const ACTION_POST_MESSAGE = 'chat.postMessage';
const ACTION_CHANNELS_LIST = 'channels.list';
const ACTION_API_TEST = 'api.test';
const ACTION_AUTH_TEST = 'auth.test';
const ACTION_CHANNELS_SET_TOPIC = 'channels.setTopic';
const ACTION_CHANNELS_INFO = 'channels.info';
const ACTION_CHANNELS_INFO = 'channels.info';
const ACTION_CHANNELS_HISTORY = 'channels.history';
const ACTION_FILES_UPLOAD = 'files.upload';

/**
* @var array
*/
protected static $classes = [
self::ACTION_POST_MESSAGE => 'ChatPostMessage',
self::ACTION_CHANNELS_LIST => 'ChannelsList',
self::ACTION_API_TEST => 'ApiTest',
self::ACTION_AUTH_TEST => 'AuthTest',
self::ACTION_POST_MESSAGE => 'ChatPostMessage',
self::ACTION_CHANNELS_LIST => 'ChannelsList',
self::ACTION_API_TEST => 'ApiTest',
self::ACTION_AUTH_TEST => 'AuthTest',
self::ACTION_CHANNELS_SET_TOPIC => 'ChannelsSetTopic',
self::ACTION_CHANNELS_INFO => 'ChannelsInfo'
self::ACTION_CHANNELS_INFO => 'ChannelsInfo',
self::ACTION_CHANNELS_HISTORY => 'ChannelsHistory',
self::ACTION_FILES_UPLOAD => 'FilesUpload'
];

/**
Expand Down
Loading

0 comments on commit 64a6256

Please sign in to comment.