Skip to content

Commit

Permalink
bug #42721 Escape all special characters for parse_mode MARKDOWN_V2 (…
Browse files Browse the repository at this point in the history
…thomas2411)

This PR was submitted for the 5.4 branch but it was squashed and merged into the 5.3 branch instead.

Discussion
----------

Escape all special characters for parse_mode MARKDOWN_V2

| Q             | A
| ------------- | ---
| Branch?       | 5.3
| Bug fix?      | yes
| New feature?  | no
| Deprecations? | no
| Tickets       | Fix #42697
| License       | MIT

In the documentation of Telegram Bot API https://core.telegram.org/bots/api#markdownv2-style we can see that we need to escape more characters _ * [ ] ( ) ~ ` > # + - = | { } . !.
I have prepared a Regex for this and replaced https://github.com/symfony/telegram-notifier/blob/5.3/TelegramTransport.php#L85
I have also changed test used for escaping dot to a test that checks escaping all those characters.

Commits
-------

709981b Escape all special characters for parse_mode MARKDOWN_V2
  • Loading branch information
fabpot committed Aug 25, 2021
2 parents 951ac85 + 709981b commit 7d4882c
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 4 deletions.
Expand Up @@ -82,7 +82,7 @@ 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;
$options['text'] = str_replace('.', '\.', $message->getSubject());
$options['text'] = preg_replace('/([_*\[\]()~`>#+\-=|{}.!])/', '\\\\$1', $message->getSubject());
}

$response = $this->client->request('POST', $endpoint, [
Expand Down
Expand Up @@ -186,7 +186,7 @@ public function testSendWithChannelOverride()
$this->assertEquals('telegram://api.telegram.org?channel=defaultChannel', $sentMessage->getTransport());
}

public function testSendWithMarkdownShouldEscapeDots()
public function testSendWithMarkdownShouldEscapeSpecialCharacters()
{
$response = $this->createMock(ResponseInterface::class);
$response->expects($this->exactly(2))
Expand Down Expand Up @@ -223,7 +223,7 @@ public function testSendWithMarkdownShouldEscapeDots()

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

Expand All @@ -235,6 +235,6 @@ public function testSendWithMarkdownShouldEscapeDots()

$transport = $this->createTransport($client, 'testChannel');

$transport->send(new ChatMessage('I contain a .'));
$transport->send(new ChatMessage('I contain special characters _ * [ ] ( ) ~ ` > # + - = | { } . ! to send.'));
}
}

0 comments on commit 7d4882c

Please sign in to comment.