Search code examples
telegramtelethon

Using telethon to get text from a new message in telegram


I want a program which will constantly check a telegram channel, and if a new message is sent, it should take that message as input to do something else.

My current problem is getting the program to always run, and to actually do something when a message is sent. The messages are going into a public channel that I am apart of, and I'm using part of https://github.com/amiryousefi/telegram-analysis/blob/master/ChannelMessages.py to login. The login works fine, but it doesn't seem to pick up on new messages at all.

The current code I'm using is:

     while True:
        @client.on(events.NewMessage(chats = [123123]))
        async def handler(event):
            print("Event Occured")
            print(event.message.message)
        sleep(2)

I tried using the while true loop as a way to get the program to constantly check, and I tried to make it specific to the chat to see if that would help, but currently nothing happens when a new message is sent to that channel.

The while loop is entered just fine, but never goes into the event. The current print statements are there for testing, but have not worked.

The message that is sent is sent by a bot that is connected to a webhook and I am logging in under my own account, both of which are in the channel.


Solution

  • You do not need to put the handler inside a while loop. When your script calls client.on(...) method this automatically adds the function as a handler of the client. This means that internally telethon is going to check the events that match NewMessage(chats = [123123] and trigger the function if necessary. This is going to be happening while the client is connected and receiving updates.

    Your code should look like this:

    from telethon import TelegramClient, events
    
    client = TelegramClient('anon', api_id, api_hash)
    
    @client.on(events.NewMessage(chats = [123123]))
    async def handler(event):
        print("Event Occured")
        print(event.raw_text)
    
    client.start()
    client.run_until_disconnected()