RektLeft
RektLeft

Reputation: 93

How to find which part of text message has a nested link/and open it?

Example text message I received on telegram:

Listen to best music: Ava Max - My Head & My Heart

My question is, how can my script check the message and eventually open the site via nested link? I tried:

      for entity in event.message.text:
            if isinstance(entity, MessageEntityTextUrl):
                open_url(entity.url)

but no luck - Script doesn't open the link.

//Edit implemented watzon's solution:

async def my_event_handler(event):
            msg = event.message.message
            for _, inner_text in msg.get_entities_text(MessageEntityTextUrl):
                    open_url(inner_text)

and now the error is:

...in my_event_handler
    for _, inner_text in msg.get_entities_text(MessageEntityTextUrl):
AttributeError: 'str' object has no attribute 'get_entities_text'

I must have missed my mistake here, what should I change in the msg?

//Edit2

msg = event.message

fixed the error but I still don't get the link as output.

Upvotes: 1

Views: 1110

Answers (2)

druskacik
druskacik

Reputation: 2497

Correct implementation of @watzon's answer would look something like this:

from telethon.tl.types import MessageEntityTextUrl

async def my_event_handler(event):
    msg = event.message
    for url_entity, inner_text in msg.get_entities_text(MessageEntityTextUrl):
        url = url_entity.url
        open_url(url)
        ...

Upvotes: 3

watzon
watzon

Reputation: 2549

You should be using message.get_entities_text().

Example:

for _, inner_text in message.get_entities_text(MessageEntityTextUrl):
  open_url(inner_text)

Alternatively you can leave out the filter argument and loop over all of the provided entities, but given your example code this should work in place.

Upvotes: 2

Related Questions