-
-
Notifications
You must be signed in to change notification settings - Fork 9.8k
[Notifier][Discord] Add DiscordBotTransport
#60218
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
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,6 +1,11 @@ | ||
| CHANGELOG | ||
| ========= | ||
|
|
||
| 7.4 | ||
| --- | ||
|
|
||
| * Add `DiscordBotTransport` | ||
|
|
||
| 6.2 | ||
| --- | ||
|
|
||
|
|
||
114 changes: 114 additions & 0 deletions
114
src/Symfony/Component/Notifier/Bridge/Discord/DiscordBotTransport.php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,114 @@ | ||
| <?php | ||
|
|
||
| /* | ||
| * This file is part of the Symfony package. | ||
| * | ||
| * (c) Fabien Potencier <fabien@symfony.com> | ||
| * | ||
| * For the full copyright and license information, please view the LICENSE | ||
| * file that was distributed with this source code. | ||
| */ | ||
|
|
||
| namespace Symfony\Component\Notifier\Bridge\Discord; | ||
|
|
||
| use Symfony\Component\Notifier\Exception\LengthException; | ||
| use Symfony\Component\Notifier\Exception\LogicException; | ||
| use Symfony\Component\Notifier\Exception\TransportException; | ||
| use Symfony\Component\Notifier\Exception\UnsupportedMessageTypeException; | ||
| use Symfony\Component\Notifier\Message\ChatMessage; | ||
| use Symfony\Component\Notifier\Message\MessageInterface; | ||
| use Symfony\Component\Notifier\Message\SentMessage; | ||
| use Symfony\Component\Notifier\Transport\AbstractTransport; | ||
| use Symfony\Contracts\EventDispatcher\EventDispatcherInterface; | ||
| use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface; | ||
| use Symfony\Contracts\HttpClient\HttpClientInterface; | ||
|
|
||
| /** | ||
| * @author Mathieu Piot <math.piot@gmail.com> | ||
| * @author Tomas Norkūnas <norkunas.tom@gmail.com> | ||
| */ | ||
| final class DiscordBotTransport extends AbstractTransport | ||
| { | ||
| protected const HOST = 'discord.com'; | ||
|
|
||
| private const SUBJECT_LIMIT = 2000; | ||
|
|
||
| public function __construct( | ||
| #[\SensitiveParameter] private string $token, | ||
| ?HttpClientInterface $client = null, | ||
| ?EventDispatcherInterface $dispatcher = null, | ||
| ) { | ||
| parent::__construct($client, $dispatcher); | ||
| } | ||
|
|
||
| public function __toString(): string | ||
| { | ||
| return \sprintf('discord+bot://%s', $this->getEndpoint()); | ||
| } | ||
|
|
||
| public function supports(MessageInterface $message): bool | ||
| { | ||
| return $message instanceof ChatMessage && $message->getOptions() instanceof DiscordOptions; | ||
| } | ||
|
|
||
| protected function doSend(MessageInterface $message): SentMessage | ||
| { | ||
| if (!$message instanceof ChatMessage) { | ||
| throw new UnsupportedMessageTypeException(__CLASS__, ChatMessage::class, $message); | ||
| } | ||
|
|
||
| $channelId = $message->getOptions()?->getRecipientId(); | ||
| if (null === $channelId) { | ||
| throw new LogicException('Missing configured recipient id on Discord message.'); | ||
| } | ||
|
|
||
| $options = $message->getOptions()?->toArray() ?? []; | ||
| $options['content'] = $message->getSubject(); | ||
|
|
||
| if (mb_strlen($options['content'], 'UTF-8') > self::SUBJECT_LIMIT) { | ||
| throw new LengthException(\sprintf('The subject length of a Discord message must not exceed %d characters.', self::SUBJECT_LIMIT)); | ||
| } | ||
|
|
||
| $endpoint = \sprintf('https://%s/api/channels/%s/messages', $this->getEndpoint(), $channelId); | ||
| $response = $this->client->request('POST', $endpoint, [ | ||
| 'headers' => [ | ||
| 'Authorization' => 'Bot '.$this->token, | ||
| ], | ||
| 'json' => array_filter($options), | ||
| ]); | ||
|
|
||
| try { | ||
| $statusCode = $response->getStatusCode(); | ||
| } catch (TransportExceptionInterface $e) { | ||
| throw new TransportException('Could not reach the remote Discord server.', $response, 0, $e); | ||
| } | ||
|
|
||
| if (200 !== $statusCode) { | ||
| $result = $response->toArray(false); | ||
|
|
||
| if (401 === $statusCode) { | ||
| $originalContent = $message->getSubject(); | ||
| $errorMessage = $result['message']; | ||
| $errorCode = $result['code']; | ||
| throw new TransportException(\sprintf('Unable to post the Discord message: "%s" (%d: "%s").', $originalContent, $errorCode, $errorMessage), $response); | ||
| } | ||
|
|
||
| if (400 === $statusCode) { | ||
| $originalContent = $message->getSubject(); | ||
|
|
||
| $errorMessage = ''; | ||
| foreach ($result as $fieldName => $message) { | ||
| $message = \is_array($message) ? implode(' ', $message) : $message; | ||
| $errorMessage .= $fieldName.': '.$message.' '; | ||
| } | ||
|
|
||
| $errorMessage = trim($errorMessage); | ||
| throw new TransportException(\sprintf('Unable to post the Discord message: "%s" (%s).', $originalContent, $errorMessage), $response); | ||
| } | ||
|
|
||
| throw new TransportException(\sprintf('Unable to post the Discord message: "%s" (Status Code: %d).', $message->getSubject(), $statusCode), $response); | ||
| } | ||
|
|
||
| return new SentMessage($message, (string) $this); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
86 changes: 86 additions & 0 deletions
86
src/Symfony/Component/Notifier/Bridge/Discord/Tests/DiscordBotTransportTest.php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,86 @@ | ||
| <?php | ||
|
|
||
| /* | ||
| * This file is part of the Symfony package. | ||
| * | ||
| * (c) Fabien Potencier <fabien@symfony.com> | ||
| * | ||
| * For the full copyright and license information, please view the LICENSE | ||
| * file that was distributed with this source code. | ||
| */ | ||
|
|
||
| namespace Symfony\Component\Notifier\Bridge\Discord\Tests; | ||
|
|
||
| use Symfony\Component\HttpClient\MockHttpClient; | ||
| use Symfony\Component\HttpClient\Response\JsonMockResponse; | ||
| use Symfony\Component\Notifier\Bridge\Discord\DiscordBotTransport; | ||
| use Symfony\Component\Notifier\Bridge\Discord\DiscordOptions; | ||
| use Symfony\Component\Notifier\Exception\LengthException; | ||
| use Symfony\Component\Notifier\Exception\LogicException; | ||
| use Symfony\Component\Notifier\Exception\TransportException; | ||
| use Symfony\Component\Notifier\Message\ChatMessage; | ||
| use Symfony\Component\Notifier\Message\SmsMessage; | ||
| use Symfony\Component\Notifier\Test\TransportTestCase; | ||
| use Symfony\Component\Notifier\Tests\Transport\DummyMessage; | ||
| use Symfony\Contracts\HttpClient\HttpClientInterface; | ||
|
|
||
| final class DiscordBotTransportTest extends TransportTestCase | ||
| { | ||
| public static function createTransport(?HttpClientInterface $client = null): DiscordBotTransport | ||
| { | ||
| return (new DiscordBotTransport('testToken', $client ?? new MockHttpClient()))->setHost('host.test'); | ||
| } | ||
|
|
||
| public static function toStringProvider(): iterable | ||
| { | ||
| yield ['discord+bot://host.test', self::createTransport()]; | ||
| } | ||
|
|
||
| public static function supportedMessagesProvider(): iterable | ||
| { | ||
| yield [new ChatMessage('Hello!', new DiscordOptions(['recipient_id' => 'channel_id']))]; | ||
| } | ||
|
|
||
| public static function unsupportedMessagesProvider(): iterable | ||
| { | ||
| yield [new SmsMessage('0611223344', 'Hello!')]; | ||
| yield [new DummyMessage()]; | ||
| } | ||
|
|
||
| public function testSendThrowsWithoutRecipientId() | ||
| { | ||
| $transport = self::createTransport(); | ||
|
|
||
| $this->expectException(LogicException::class); | ||
| $this->expectExceptionMessage('Missing configured recipient id on Discord message.'); | ||
|
|
||
| $transport->send(new ChatMessage('testMessage')); | ||
| } | ||
|
|
||
| public function testSendChatMessageWithMoreThan2000CharsThrowsLogicException() | ||
| { | ||
| $transport = self::createTransport(); | ||
|
|
||
| $this->expectException(LengthException::class); | ||
| $this->expectExceptionMessage('The subject length of a Discord message must not exceed 2000 characters.'); | ||
|
|
||
| $transport->send(new ChatMessage(str_repeat('囍', 2001), (new DiscordOptions())->recipient('channel_id'))); | ||
| } | ||
|
|
||
| public function testSendWithErrorResponseThrows() | ||
| { | ||
| $response = new JsonMockResponse( | ||
| ['message' => 'testDescription', 'code' => 'testErrorCode'], | ||
| ['http_code' => 400], | ||
| ); | ||
|
|
||
| $client = new MockHttpClient($response); | ||
|
|
||
| $transport = self::createTransport($client); | ||
|
|
||
| $this->expectException(TransportException::class); | ||
| $this->expectExceptionMessageMatches('/testDescription.+testErrorCode/'); | ||
|
|
||
| $transport->send(new ChatMessage('testMessage', (new DiscordOptions())->recipient('channel_id'))); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Let's remove this username check, if the api responds with an actionable error message. Is this the case?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Then it should be removed from both transports. Can it be done in a follow-up pr?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yes