Skip to content

Escape all special characters for parse_mode MARKDOWN_V2 #42721

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 0 commits into from
Aug 25, 2021

Conversation

thomas2411
Copy link
Contributor

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.

@@ -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('/([\[_\*\[\]\(\)~`>#\+-=\|{}\.!])/m', '\\\\$1', $message->getSubject());
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

\[ is referenced twice.
IIRC you don't have to escape everything
the m could be removed

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, indeed, I will remove it.

@fabpot fabpot changed the base branch from 5.4 to 5.3 August 25, 2021 10:34
@fabpot
Copy link
Member

fabpot commented Aug 25, 2021

Thank you @thomas2411.

@fabpot fabpot closed this Aug 25, 2021
@fabpot fabpot force-pushed the notifier_telegram_escape branch from bd4a9ba to 709981b Compare August 25, 2021 10:34
@fabpot fabpot merged commit 7d4882c into symfony:5.3 Aug 25, 2021
@thomas2411 thomas2411 deleted the notifier_telegram_escape branch August 25, 2021 11:08
@fabpot fabpot mentioned this pull request Aug 30, 2021
@belmeopmenieuwesim
Copy link

belmeopmenieuwesim commented Dec 7, 2022

this PR broke the Telegram formatting entirely for markdown V2. Literally everything stays escaped. If I comment this preg_match the formatting is exactly as it should be. The current code gives this::

image

@nicolas-grekas
Copy link
Member

Fixed in #58636

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[Notifier] [Telegram] Escaping special characters with MarkdownV2
6 participants