Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 533
Federico Avatar asked May 12 '19 22:05

Federico


2 Answers

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!

like image 118
Amir Shabani Avatar answered Nov 19 '22 05:11

Amir Shabani


It works for me! Here's the code I'm using:

>>> from telegram import Bot
>>> tkn = '88888:199939393'; chid = '-31828'
>>> bot = Bot(tkn)
>>> with open('ye.jpeg', 'rb') as fme:
...   bot.send_photo(chid, fme, caption='<b>Hallo</b>', parse_mode='html')
...
<telegram.message.Message object at 0x7f6301b44d10>

Of course, you must use your own telegram token and channel id. Also notice I'm using parse_mode='html' # lowercase

like image 34
slackmart Avatar answered Nov 19 '22 05:11

slackmart