Skip to content

[Notifier][Slack] Send messages using Incoming Webhooks App #35828

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Apr 12, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions src/Symfony/Component/Notifier/Bridge/Slack/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
CHANGELOG
=========

5.1.0
-----

* [BC BREAK] Change API endpoit to use the Slack Incoming Webhooks API

5.0.0
-----

Expand Down
20 changes: 15 additions & 5 deletions src/Symfony/Component/Notifier/Bridge/Slack/SlackOptions.php
Original file line number Diff line number Diff line change
Expand Up @@ -50,9 +50,6 @@ public static function fromNotification(Notification $notification): self
public function toArray(): array
{
$options = $this->options;
if (isset($options['blocks'])) {
$options['blocks'] = json_encode($options['blocks']);
}
unset($options['recipient_id']);

return $options;
Expand All @@ -65,11 +62,24 @@ public function getRecipientId(): ?string

/**
* @return $this
*
* @deprecated since Symfony 5.1, use recipient() instead.
*/
public function channel(string $channel): self
{
$this->options['channel'] = $channel;
$this->options['recipient_id'] = $channel;
trigger_deprecation('symfony/slack-notifier', '5.1', 'The "%s()" method is deprecated, use "recipient()" instead.', __METHOD__);

return $this;
}

/**
* @param string $id The hook id (anything after https://hooks.slack.com/services/)
*
* @return $this
*/
public function recipient(string $id): self
{
$this->options['recipient_id'] = $id;

return $this;
}
Expand Down
40 changes: 20 additions & 20 deletions src/Symfony/Component/Notifier/Bridge/Slack/SlackTransport.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,41 +20,44 @@
use Symfony\Contracts\HttpClient\HttpClientInterface;

/**
* Send messages via Slack using Slack Incoming Webhooks.
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Daniel Stancu <birkof@birkof.ro>
*
* @internal
*
* @see https://api.slack.com/messaging/webhooks
*
* @experimental in 5.0
*/
final class SlackTransport extends AbstractTransport
{
protected const HOST = 'slack.com';
protected const HOST = 'hooks.slack.com';

private $accessToken;
private $chatChannel;
private $id;

public function __construct(string $accessToken, string $channel = null, HttpClientInterface $client = null, EventDispatcherInterface $dispatcher = null)
/**
* @param string $id The hook id (anything after https://hooks.slack.com/services/)
*/
public function __construct(string $id, HttpClientInterface $client = null, EventDispatcherInterface $dispatcher = null)
{
$this->accessToken = $accessToken;
$this->chatChannel = $channel;
$this->id = $id;
$this->client = $client;

parent::__construct($client, $dispatcher);
}

public function __toString(): string
{
return sprintf('slack://%s?channel=%s', $this->getEndpoint(), $this->chatChannel);
return sprintf('slack://%s/%s', $this->getEndpoint(), $this->id);
}

public function supports(MessageInterface $message): bool
{
return $message instanceof ChatMessage && (null === $message->getOptions() || $message->getOptions() instanceof SlackOptions);
}

/**
* @see https://api.slack.com/methods/chat.postMessage
*/
protected function doSend(MessageInterface $message): void
{
if (!$message instanceof ChatMessage) {
Expand All @@ -69,22 +72,19 @@ protected function doSend(MessageInterface $message): void
}

$options = $opts ? $opts->toArray() : [];
$options['token'] = $this->accessToken;
if (!isset($options['channel'])) {
$options['channel'] = $message->getRecipientId() ?: $this->chatChannel;
}
$id = $message->getRecipientId() ?: $this->id;
$options['text'] = $message->getSubject();
$response = $this->client->request('POST', 'https://'.$this->getEndpoint().'/api/chat.postMessage', [
'body' => array_filter($options),
$response = $this->client->request('POST', sprintf('https://%s/services/%s', $this->getEndpoint(), $id), [
'json' => array_filter($options),
]);

if (200 !== $response->getStatusCode()) {
throw new TransportException(sprintf('Unable to post the Slack message: %s.', $response->getContent(false)), $response);
throw new TransportException(sprintf('Unable to post the Slack message: '.$response->getContent(false)), $response);
}

$result = $response->toArray(false);
if (!$result['ok']) {
throw new TransportException(sprintf('Unable to post the Slack message: %s.', $result['error']), $response);
$result = $response->getContent(false);
if ('ok' !== $result) {
throw new TransportException(sprintf('Unable to post the Slack message: '.$result), $response);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -29,13 +29,12 @@ final class SlackTransportFactory extends AbstractTransportFactory
public function create(Dsn $dsn): TransportInterface
{
$scheme = $dsn->getScheme();
$accessToken = $this->getUser($dsn);
$channel = $dsn->getOption('channel');
$id = ltrim($dsn->getPath(), '/');
$host = 'default' === $dsn->getHost() ? null : $dsn->getHost();
$port = $dsn->getPort();

if ('slack' === $scheme) {
return (new SlackTransport($accessToken, $channel, $this->client, $this->dispatcher))->setHost($host)->setPort($port);
return (new SlackTransport($id, $this->client, $this->dispatcher))->setHost($host)->setPort($port);
}

throw new UnsupportedSchemeException($dsn, 'slack', $this->getSupportedSchemes());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@

use PHPUnit\Framework\TestCase;
use Symfony\Component\Notifier\Bridge\Slack\SlackTransportFactory;
use Symfony\Component\Notifier\Exception\IncompleteDsnException;
use Symfony\Component\Notifier\Exception\UnsupportedSchemeException;
use Symfony\Component\Notifier\Transport\Dsn;

Expand All @@ -24,26 +23,18 @@ public function testCreateWithDsn(): void
$factory = new SlackTransportFactory();

$host = 'testHost';
$channel = 'testChannel';
$transport = $factory->create(Dsn::fromString(sprintf('slack://testUser@%s/?channel=%s', $host, $channel)));
$path = 'testPath';
$transport = $factory->create(Dsn::fromString(sprintf('slack://%s/%s', $host, $path)));

$this->assertSame(sprintf('slack://%s?channel=%s', $host, $channel), (string) $transport);
}

public function testCreateWithNoTokenThrowsMalformed(): void
{
$factory = new SlackTransportFactory();

$this->expectException(IncompleteDsnException::class);
$factory->create(Dsn::fromString(sprintf('slack://%s/?channel=%s', 'testHost', 'testChannel')));
$this->assertSame(sprintf('slack://%s/%s', $host, $path), (string) $transport);
}

public function testSupportsSlackScheme(): void
{
$factory = new SlackTransportFactory();

$this->assertTrue($factory->supports(Dsn::fromString('slack://host/?channel=testChannel')));
$this->assertFalse($factory->supports(Dsn::fromString('somethingElse://host/?channel=testChannel')));
$this->assertTrue($factory->supports(Dsn::fromString('slack://host/path')));
$this->assertFalse($factory->supports(Dsn::fromString('somethingElse://host/path')));
}

public function testNonSlackSchemeThrows(): void
Expand All @@ -52,6 +43,6 @@ public function testNonSlackSchemeThrows(): void

$this->expectException(UnsupportedSchemeException::class);

$factory->create(Dsn::fromString('somethingElse://user:pwd@host/?channel=testChannel'));
$factory->create(Dsn::fromString('somethingElse://host/path'));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -29,17 +29,17 @@ final class SlackTransportTest extends TestCase
public function testToStringContainsProperties(): void
{
$host = 'testHost';
$channel = 'testChannel';
$path = 'testPath';

$transport = new SlackTransport('testToken', $channel, $this->createMock(HttpClientInterface::class));
$transport = new SlackTransport($path, $this->createMock(HttpClientInterface::class));
$transport->setHost('testHost');

$this->assertSame(sprintf('slack://%s?channel=%s', $host, $channel), (string) $transport);
$this->assertSame(sprintf('slack://%s/%s', $host, $path), (string) $transport);
}

public function testSupportsChatMessage(): void
{
$transport = new SlackTransport('testToken', 'testChannel', $this->createMock(HttpClientInterface::class));
$transport = new SlackTransport('testPath', $this->createMock(HttpClientInterface::class));

$this->assertTrue($transport->supports(new ChatMessage('testChatMessage')));
$this->assertFalse($transport->supports($this->createMock(MessageInterface::class)));
Expand All @@ -49,7 +49,7 @@ public function testSendNonChatMessageThrows(): void
{
$this->expectException(LogicException::class);

$transport = new SlackTransport('testToken', 'testChannel', $this->createMock(HttpClientInterface::class));
$transport = new SlackTransport('testPath', $this->createMock(HttpClientInterface::class));

$transport->send($this->createMock(MessageInterface::class));
}
Expand All @@ -70,15 +70,15 @@ public function testSendWithEmptyArrayResponseThrows(): void
return $response;
});

$transport = new SlackTransport('testToken', 'testChannel', $client);
$transport = new SlackTransport('testPath', $client);

$transport->send(new ChatMessage('testMessage'));
}

public function testSendWithErrorResponseThrows(): void
{
$this->expectException(TransportException::class);
$this->expectExceptionMessageRegExp('/testErrorCode/');
$this->expectExceptionMessage('testErrorCode');

$response = $this->createMock(ResponseInterface::class);
$response->expects($this->exactly(2))
Expand All @@ -87,21 +87,20 @@ public function testSendWithErrorResponseThrows(): void

$response->expects($this->once())
->method('getContent')
->willReturn(json_encode(['error' => 'testErrorCode']));
->willReturn('testErrorCode');

$client = new MockHttpClient(static function () use ($response): ResponseInterface {
return $response;
});

$transport = new SlackTransport('testToken', 'testChannel', $client);
$transport = new SlackTransport('testPath', $client);

$transport->send(new ChatMessage('testMessage'));
}

public function testSendWithOptions(): void
{
$token = 'testToken';
$channel = 'testChannel';
$path = 'testPath';
$message = 'testMessage';

$response = $this->createMock(ResponseInterface::class);
Expand All @@ -112,25 +111,24 @@ public function testSendWithOptions(): void

$response->expects($this->once())
->method('getContent')
->willReturn(json_encode(['ok' => true]));
->willReturn('ok');

$expectedBody = sprintf('token=%s&channel=%s&text=%s', $token, $channel, $message);
$expectedBody = json_encode(['text' => $message]);

$client = new MockHttpClient(function (string $method, string $url, array $options = []) use ($response, $expectedBody): ResponseInterface {
$this->assertSame($expectedBody, $options['body']);

return $response;
});

$transport = new SlackTransport($token, $channel, $client);
$transport = new SlackTransport($path, $client);

$transport->send(new ChatMessage('testMessage'));
}

public function testSendWithNotification(): void
{
$token = 'testToken';
$channel = 'testChannel';
$host = 'testHost';
$message = 'testMessage';

$response = $this->createMock(ResponseInterface::class);
Expand All @@ -141,16 +139,14 @@ public function testSendWithNotification(): void

$response->expects($this->once())
->method('getContent')
->willReturn(json_encode(['ok' => true]));
->willReturn('ok');

$notification = new Notification($message);
$chatMessage = ChatMessage::fromNotification($notification);
$options = SlackOptions::fromNotification($notification);

$expectedBody = http_build_query([
'blocks' => $options->toArray()['blocks'],
'token' => $token,
'channel' => $channel,
$expectedBody = json_encode([
'blocks' => json_decode($options->toArray()['blocks'], true),
'text' => $message,
]);

Expand All @@ -160,7 +156,7 @@ public function testSendWithNotification(): void
return $response;
});

$transport = new SlackTransport($token, $channel, $client);
$transport = new SlackTransport($host, $client);

$transport->send($chatMessage);
}
Expand All @@ -173,15 +169,14 @@ public function testSendWithInvalidOptions(): void
return $this->createMock(ResponseInterface::class);
});

$transport = new SlackTransport('testToken', 'testChannel', $client);
$transport = new SlackTransport('testHost', $client);

$transport->send(new ChatMessage('testMessage', $this->createMock(MessageOptionsInterface::class)));
}

public function testSendWith200ResponseButNotOk(): void
{
$token = 'testToken';
$channel = 'testChannel';
$host = 'testChannel';
$message = 'testMessage';

$this->expectException(TransportException::class);
Expand All @@ -194,17 +189,17 @@ public function testSendWith200ResponseButNotOk(): void

$response->expects($this->once())
->method('getContent')
->willReturn(json_encode(['ok' => false, 'error' => 'testErrorCode']));
->willReturn('testErrorCode');

$expectedBody = sprintf('token=%s&channel=%s&text=%s', $token, $channel, $message);
$expectedBody = json_encode(['text' => $message]);

$client = new MockHttpClient(function (string $method, string $url, array $options = []) use ($response, $expectedBody): ResponseInterface {
$this->assertSame($expectedBody, $options['body']);

return $response;
});

$transport = new SlackTransport($token, $channel, $client);
$transport = new SlackTransport($host, $client);

$transport->send(new ChatMessage('testMessage'));
}
Expand Down