From a210bdae8ed72bf3f046be278e62a5518418ba57 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Holger=20L=C3=B6sken?= Date: Wed, 23 Oct 2024 01:43:24 +0200 Subject: [PATCH] [Notifier] Improve Telegrams markdown escaping --- .../Bridge/Telegram/TelegramTransport.php | 15 ++++++++++++++- .../Telegram/Tests/TelegramTransportTest.php | 2 +- 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/src/Symfony/Component/Notifier/Bridge/Telegram/TelegramTransport.php b/src/Symfony/Component/Notifier/Bridge/Telegram/TelegramTransport.php index 975a5c1d38ad2..9a3648ed8ec94 100644 --- a/src/Symfony/Component/Notifier/Bridge/Telegram/TelegramTransport.php +++ b/src/Symfony/Component/Notifier/Bridge/Telegram/TelegramTransport.php @@ -89,7 +89,20 @@ protected function doSend(MessageInterface $message): SentMessage if (!isset($options['parse_mode']) || TelegramOptions::PARSE_MODE_MARKDOWN_V2 === $options['parse_mode']) { $options['parse_mode'] = TelegramOptions::PARSE_MODE_MARKDOWN_V2; - $text = preg_replace('/([_*\[\]()~`>#+\-=|{}.!\\\\])/', '\\\\$1', $text); + /* + * Just replace the obvious chars according to Telegram documentation. + * Do not try to find pairs or replace chars, that occur in pairs like + * - *bold text* + * - _italic text_ + * - __underlined text__ + * - various notations of images, f. ex. [title](url) + * - `code samples`. + * + * These formats should be taken care of when the message is constructed. + * + * @see https://core.telegram.org/bots/api#markdownv2-style + */ + $text = preg_replace('/([.!#>+-=|{}~])/', '\\\\$1', $text); } if (isset($options['upload'])) { diff --git a/src/Symfony/Component/Notifier/Bridge/Telegram/Tests/TelegramTransportTest.php b/src/Symfony/Component/Notifier/Bridge/Telegram/Tests/TelegramTransportTest.php index c4e6e24f71a2a..80980b369ba05 100644 --- a/src/Symfony/Component/Notifier/Bridge/Telegram/Tests/TelegramTransportTest.php +++ b/src/Symfony/Component/Notifier/Bridge/Telegram/Tests/TelegramTransportTest.php @@ -265,7 +265,7 @@ public function testSendWithMarkdownShouldEscapeSpecialCharacters() $expectedBody = [ 'chat_id' => 'testChannel', - 'text' => 'I contain special characters \_ \* \[ \] \( \) \~ \` \> \# \+ \- \= \| \{ \} \. \! \\\\ to send\.', + 'text' => 'I contain special characters _ * [ ] ( ) \~ ` \> \# \+ \- \= \| \{ \} \. \! \ to send\.', 'parse_mode' => 'MarkdownV2', ];