Distinguish between NewMessage and MessageEdited in Telethon?

30 Views Asked by At

I have a Python (3.9) class which is monitoring message edits and new messageas in channels. Is there any way to know in the code whether the message was edited or if it's a new message? According to the documentation, edited messages should be treated like new messages.

I tried the following code without success:

class TelegramBot:

    # --------------------------------
    # Initialization
    # --------------------------------
    def __init__(self):
        client.add_event_handler(
            self.message_listener,
            events.NewMessage(
                chats=get_chat_ids(
                    "X",
                    "Y",
                    "Z",
                )
            ),
        )
    # Register the event handler for edited messages
    client.add_event_handler(
        self.message_listener,
        events.MessageEdited(chats=get_chat_ids("X", "Y")),
    )


    async def message_listener(self, event):
        message = event.message.message
        message_id = event.message.id  # Get the ID of the triggering message

        if event.chat_id in get_chat_ids("X", "Y"):
            if isinstance(event, events.NewMessage):
                ...
            elif isinstance(event, events.MessageEdited):
                ...

It also seems an edited message triggers both event types, meaning one message executes my code twice.

Using print for the event type shows the same:

{type(event).__name__}

yields Event

1

There are 1 best solutions below

6
Jonny Henly On

Since the base class for events.MessageEdited is events.NewMessage, check if it's an instance of events.MessageEdited, if it's not then it's an instance of events.NewMessage.

if isinstance(event, events.MessageEdited):
    # it's an edited message
else:
    # it's a new message