Parsing entities of text message in telegram bot sent BY the user
I am writing a telegram bot that needs to know how the text has been stylized by the user (bold, italicized, strikethrough, spoiler, etc.). But it is not clear to me how this can be done or if it is even possible. I am using python and the python-telegram-bot
package. I have figured out how to send stylized messages by having the Dispatcher parse the message being sent to the user in markdown. But how can I do the same thing receiving messages?
To make a very simple example, let's take this bot that just has a "start" command.
def start_command(update, context):
update.message.reply_text(context.args) # reply message back to the user
def main():
defaults = Defaults(parse_mode='MarkdownV2')
updater = Updater(API_KEY, use_context=True, defaults=defaults)
dp = updater.dispatcher
dp.add_handler(CommandHandler("start", start_command))
updater.start_polling(0)
updater.idle()
How can I make it such that it knows the argument was bolded, italicized, etc. by the user?
To make it clear, I want to be able to distinguish between:
- /start hello
- /start hello
- /start hello
- ...
Depending on your use case, there several things that you can use one of the following:
-
Message.entities
is a list ofMessageEntity
objects that tell you how the text is formatted. However, since aMessageEntity
only contains info on the offset and length, it's a bit tricky to get the text that's formatted by the entity. - PTB offers the convenience methods
Message.parse_entity
andMessage.parse_entities
. The first accepts one of the elements ofMessage.entities
and returns the text covered by that entity. The second returns a dictionary, where the keys are the elements ofMessage.enities
and the values are the corresponding return values ofMessage.parse_entity
. - Finally
Message.text_html
andMessage.text_markdown_v2
are convenience properties that give you the text with the corresponding markup inserted. E.g.message.reply_html(message.text_html)
will send a message that's formatted exactly likemessage
.
Disclaimer: I'm currently the maintainer of python-telegram-bot
.