Skip to content

Commit a210bda

Browse files
codedgenicolas-grekas
authored andcommitted
[Notifier] Improve Telegrams markdown escaping
1 parent 0dff554 commit a210bda

File tree

2 files changed

+15
-2
lines changed

2 files changed

+15
-2
lines changed

src/Symfony/Component/Notifier/Bridge/Telegram/TelegramTransport.php

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,20 @@ protected function doSend(MessageInterface $message): SentMessage
8989

9090
if (!isset($options['parse_mode']) || TelegramOptions::PARSE_MODE_MARKDOWN_V2 === $options['parse_mode']) {
9191
$options['parse_mode'] = TelegramOptions::PARSE_MODE_MARKDOWN_V2;
92-
$text = preg_replace('/([_*\[\]()~`>#+\-=|{}.!\\\\])/', '\\\\$1', $text);
92+
/*
93+
* Just replace the obvious chars according to Telegram documentation.
94+
* Do not try to find pairs or replace chars, that occur in pairs like
95+
* - *bold text*
96+
* - _italic text_
97+
* - __underlined text__
98+
* - various notations of images, f. ex. [title](url)
99+
* - `code samples`.
100+
*
101+
* These formats should be taken care of when the message is constructed.
102+
*
103+
* @see https://core.telegram.org/bots/api#markdownv2-style
104+
*/
105+
$text = preg_replace('/([.!#>+-=|{}~])/', '\\\\$1', $text);
93106
}
94107

95108
if (isset($options['upload'])) {

src/Symfony/Component/Notifier/Bridge/Telegram/Tests/TelegramTransportTest.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -265,7 +265,7 @@ public function testSendWithMarkdownShouldEscapeSpecialCharacters()
265265

266266
$expectedBody = [
267267
'chat_id' => 'testChannel',
268-
'text' => 'I contain special characters \_ \* \[ \] \( \) \~ \` \> \# \+ \- \= \| \{ \} \. \! \\\\ to send\.',
268+
'text' => 'I contain special characters _ * [ ] ( ) \~ ` \> \# \+ \- \= \| \{ \} \. \! \ to send\.',
269269
'parse_mode' => 'MarkdownV2',
270270
];
271271

0 commit comments

Comments
 (0)