Search code examples
pythonentityoffsettelethon

Telethon, change offset and length of a text entity given a word to change


I'm making a bot that replies to a user with the same message but with some words replaced by others.

Input example:

Hi, this is a keyboard example.

Excepted output:

Hi, testing is a mouse example. (the word this and keyboard have been replaced.)

My output:

Hi, testing is a mouse example.

I've tried solving this problem changing the offset and length values of event.message.entities but i couldn't.

I also tried using event.get_entities_text() but couldn't.

So, what's the simplest/best solution for this problem?


Solution

  • In Telethon v1, you can do this:

    text = message.text
    replaced = text.replace('this', 'testing')
    message.text = replaced
    

    This is because message.text contains the formatting entities as whatever the client.parse_mode says (by default, "markdown" as used by Telegram Desktop), so text would be __Hi__, **this** is a..., and replacing 'this' will keep the formatting intact.

    When setting the message.text, the library automatically separates it again into raw text plus the entities.