9

I am working on a Telegram Bot in Python but I struggle to use markdown correctly and I can not find any proper resources about the telegram markdown implementation. It gets even more complicated because of two different markdown "versions" (Markdown and Markdown_V2). And none of them is matching the behavior of the normal chat field (typing by hand).

Test String:

*Bold*, _italic_, *_bold and italic_*, **double bold**, __double italic__, __**double bold and double italic**__

parse_mode="Markdown":

Bold, italic, _bold and italic_, double bold, double italic, double bold and double italic

parse_mode="Markdown V2":

Bold, italic, bold and italic, double bold, double italic, double bold and double italic

in Chat:

*Bold*, _italic_, *bold and italic*, double bold, double italic, **double bold and double italic**

-

How do I add bold and italic, and are there any other commands like underline and more? I need some explanation. Thanks.

Schneyer
  • 1,197
  • 1
  • 9
  • 27

2 Answers2

14

Bots need a different markdown syntax.

To send bold and italic text use:

update.message.reply_text('*_bold and italic_*', parse_mode='MarkdownV2')

from the official telegram website https://core.telegram.org/bots/api#markdownv2-style

*bold \*text*
_italic \*text_
__underline__
~strikethrough~
*bold _italic bold ~italic bold strikethrough~ __underline italic bold___ bold*
[inline URL](http://www.example.com/)
[inline mention of a user](tg://user?id=123456789)
`inline fixed-width code`
```
pre-formatted fixed-width code block
```
```python
pre-formatted fixed-width code block written in the Python programming language
```

I recommend to use only MarkdownV2 syntax, since Markdown is less powerful

Hoxha Alban
  • 1,042
  • 1
  • 8
  • 12
  • "a different markdown syntax"—the markup shown in this question isn't Markdown. If you change something fundamental like what `*this*` means, you have a different language. – ChrisGPT was on strike Jun 06 '20 at 14:03
  • Actually telegram web does not show the combination, while the app does. Confused me even more ..., but now I got it. Thanks! – Schneyer Jun 06 '20 at 14:34
3

Just a note, with Markdownv2 you have to escape special characters. "Special" here means those that Telegram defined as special (doc).

Personally I find it easier to work with parse_mode='HTML' where you can use a common function to escape HTML chars (e.g. html.escape in Python, _.escape in JS). With HTML you have way more options for text decoration.

Aleksandr
  • 489
  • 1
  • 4
  • 12
  • Thanks for the suggestion and the docs link. Read the docs. Got confused even more. Decided to use HTML parsing after all, as having to escape characters like '.' and '-' in V2 is just crazy. – MickeyDickey Sep 02 '23 at 23:28