How should I use parse_mode='HTML' in telegram python bot?

Federico picture Federico · May 13, 2019 · Viewed 19.6k times · Source

I'm trying to send a message in a channel with a bot, using Telegram API's send_photo() method. It takes a caption parameter (type String) but I can't format it through parse_mode='HTML' parameter...

If I use something like this:

send_photo(chat_id, photo, caption="<b>Some text</b>", parse_mode='HTML') 

it sends the message but without any kind of formatting. Does anybody know why? Thanks

Answer

Amir A. Shabani picture Amir A. Shabani · May 13, 2019

First, you need to import ParseMode from telegram like this:

from telegram import ParseMode

Then, all you need is to specify parse_mode=ParseMode.HTML. Here's a working example:

def jordan(bot, update):
    chat_id = update.message.chat.id
    with open('JordanPeterson.jpg', 'rb') as jordan_picture:
        caption = "<a href='https://twitter.com/jordanbpeterson'>Jordan B. Peterson</a>"
        bot.send_photo(
            chat_id, 
            photo=jordan_picture, 
            caption=caption,
            parse_mode=ParseMode.HTML
        )

And we can see that it works:

works

Update: Actually, both parse_mode='html' (as suggested by @slackmart) and parse_mode='HTML' that you used yourself work for me!

Another Update (as per your comment): You can use multiple tags. Here's an example of one, with hyperlink, bold, and italic:

multiple tags

Yet Another Update: Regarding your comment:

...do I have any limitations on HTML tags? I can't use something like <img> or <br> to draw a line

Honestly,

try and find out

That's what I did!

Now you're trying to format the caption of an image, using HTML, meaning you're formatting a text, so obviously, you can't use "something like <img>." It has to be a "text formatting tag" (plus <a>). And not even all of them! I believe you can only use these: <a>, <b>, <strong>, <i> and <em>.

If you try to use a text-formatting tag like <del>, it will give you this error:

Can't parse entities: unsupported start tag "del" at byte offset 148

Which is a shame! I'd love to be able to do something like this in captions of images.or something like this!