vinod
vinod

Reputation: 1202

Listener in python - telegram

Hi I am working telegram api telethon. Here I wanted to continuously listen the group messages in python code.

I am able to read the messages from group but every time i need to run the code. is there any way to implement it that my code should listen the message synchronically.

below is the code snippets which gives me the messages in group. need to add listener code in it.

client = TelegramClient('session_read', api_id, api_hash)
client.start()

dialog_count = 50
dialogs = client.get_dialogs(dialog_count)
for i, entity in enumerate(dialogs):

    if entity.name == 'GroupName':
     print('{}'.format(entity.message.message))

Upvotes: 3

Views: 7954

Answers (1)

Tulir
Tulir

Reputation: 928

Telethon has event handlers as documented here. For a basic new message handler, the first example should do:

from telethon import TelegramClient, events

client = TelegramClient('session_read', api_id, api_hash)

@client.on(events.NewMessage)
async def my_event_handler(event):
    print('{}'.format(event))

client.start()
client.run_until_disconnected()

If you want to check that it's in a specific group, you can use the chats parameter on events.NewMessage:

@client.on(events.NewMessage(chats=("GroupName", "Group2")))
async def my_event_handler(event):
    print(event)

There are a lot of other filtering options too, so I recommend checking out the documentation linked earlier.

Upvotes: 9

Related Questions