How to insert a link to user profile or chat in message using telethon?

Viewed 1493

Composing new message in telethon I'm trying to make something like 'User (link) in chat (link) posted something', but failed.

According to https://github.com/LonamiWebs/Telethon/wiki/Special-links, I've tried links like tg://user?id=123 and tg://openmessage?chat_id=123, but that gives links in text that are not working.

Here's the example:

@client.on(events.NewMessage)
async def handler(event):
    sender = await event.get_sender()
    sender_id = event.sender_id
    sender_link = 'tg://user?id=' + str(sender_id)
    payload = '[%s] (%s) said something' % (sender.first_name, sender_link)

I'm expecting a message with hyperlinked username, but getting [Alex] (tg://user?id=123), and that link leads to nowhere.

2 Answers

You need to remove the space between [...] and (...). You should have [%s](%s).

Twit is right, but there are several alternatives. You can manually insert a MessageEntityMention to the parser, or you can use HTML parse_mode and the format. Note that both of these are better, consider for example a user named hello](tg://user?id=321)[. This user would not get a link, so you should avoid markdown as it's not possible to escape this.

Related