When utilizing Telethon to send Telegram messages with monospace or HTML text in Python, the parse_mode
option (for example parse_mode='markdown'
or parse_mode='html'
) works well during initial message sending. However, when attempting to edit a previously sent message, the parse_mode option does not appear to be available. How can I effectively edit a message and incorporate monospace or HTML-formatted text?
Example: Sending a message containing monospace string
sent_message = client.send_message(To_id, "the authentication code `8632496`", parse_mode='markdown')
Then editing the message and sending new text containing a monospace string
client(EditMessageRequest(
peer=To_id,
id=sent_message.id,
message="the new authentication code `9832798237`"
))
I am aware that using entities is an option. For instance:
entities = [MessageEntityCode(offset=9, length=18)] # specifying a code block entity
client(EditMessageRequest(
peer=To_id,
id=sent_message.id,
message='This is a monospace string.',
no_webpage=True,
entities=entities
))
However, my text is long and contains multiple monospace strings originating from various sources, for example: text = f"something {variable1}, something {variable2}"
Hence, identifying the starting point and length of each monospace string is challenging.
I'd greatly appreciate any guidance on how to approach this issue, including methods or best practices for effectively managing monospace or HTML text when editing Telegram messages using Telethon.
client(EditMessageRequest(
is a old, not preferred way of editing a message.
You should use client.edit_message
method, in your example:
client.edit_message(tst_id, first.id, 'Oeps, the code is `1234789`')
This way, you don't even need to specify parse_mode
it's the same as the message your editing.
Full code to test this:
from telethon import TelegramClient
import asyncio
import time
client = TelegramClient('anon', '1234567', '0123456789abcdef0123456789abcdef')
client.start()
async def main():
tst_id = 1234
first = await client.send_message(tst_id, "the authentication code `8632496`", parse_mode='markdown')
time.sleep(3)
second = await client.edit_message(tst_id, first.id, 'Oeps, the code is `1234789`')
loop = asyncio.get_event_loop()
loop.run_until_complete(main())