'Telegram does not escape some markdown characters
Telegram does not escape some markdown characters, for example:
This works fine
_test\_test_
But this return parse error
*test\*test*
What I do wrong?
Solution 1:[1]
String escapedMsg = toEscapeMsg
.replace("_", "\\_")
.replace("*", "\\*")
.replace("[", "\\[")
.replace("`", "\\`");
Do not escape ] character. If [ is escaped, ] is treated like a normal character.
Solution 2:[2]
Actually both are getting error.
{
"ok": false,
"error_code": 400,
"description": "Bad Request: Can't parse message text: Can't find end of the entity starting at byte offset 11"
}
sounds like Telegram doesn't support escape characters for markdown, so i suggest you to use HTML instead:
<b>test*test</b>
Solution 3:[3]
The only workaround is to use HTML in the parse_mode
Solution 4:[4]
You should use '\\' to escape markup tokens *_[`, i.e. send this instead:
*test\\*test*
Solution 5:[5]
Use MarkdownV2.
{
"chat_id": telegram_chat_id,
"parse_mode": "MarkdownV2",
"text": "*test\*test*"
}
Just escape these characters:
'_', '*', '[', ']', '(', ')', '~', '`', '>', '#', '+', '-', '=', '|', '{', '}', '.', '!'
and telegram will handle the rest.
Solution 6:[6]
Ironically if the prase_mode argument is set to markdown instead of using the ParseMode.MARKDOWN_V2 constant in the python without escaping any character send_message function works fine.
Solution 7:[7]
according to telegram API
In all other places characters '_', '*', '[', ']', '(', ')', '~', '`', '>', '#', '+', '-', '=', '|', '{', '}', '.', '!' must be escaped with the preceding character '\'.
so here is function I've used
text
.replace(/\_/g, '\\_')
.replace(/\*/g, '\\*')
.replace(/\[/g, '\\[')
.replace(/\]/g, '\\]')
.replace(/\(/g, '\\(')
.replace(/\)/g, '\\)')
.replace(/\~/g, '\\~')
.replace(/\`/g, '\\`')
.replace(/\>/g, '\\>')
.replace(/\#/g, '\\#')
.replace(/\+/g, '\\+')
.replace(/\-/g, '\\-')
.replace(/\=/g, '\\=')
.replace(/\|/g, '\\|')
.replace(/\{/g, '\\{')
.replace(/\}/g, '\\}')
.replace(/\./g, '\\.')
.replace(/\!/g, '\\!')
But keep in mind, this means if you mean to use *some text* as bold text this script will render *some text* instead without applying the bold effect
Solution 8:[8]
pdenti's answer only replaces the first character found in the message. Use regular expressions with the global tag to replace all of them.
String escapedMsg = toEscapeMsg
.replace(/_/g, "\\_")
.replace(/\*/g, "\\*")
.replace(/\[/g, "\\[")
.replace(/`/g, "\\`");
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | pdenti |
| Solution 2 | Andrii Abramov |
| Solution 3 | Oleg |
| Solution 4 | Karb0f0s |
| Solution 5 | Zhi Long Jared Liw |
| Solution 6 | Abbas |
| Solution 7 | Stanislau Buzunko |
| Solution 8 | Yonic |
