Ikram
Ikram

Reputation: 13

How to call a the python code when a new message is delivered from telethon API

How can I call some Python code when a new message is delivered from the Telethon API? I need to run the code all the day so that I can do my processing from Python code.

  1. How to use this? @client.on(events.NewMessage(chats=channel, incoming=True))
  2. Do I need run the scheduler to check this?

I am using history = client(GetHistoryRequest) method.

Upvotes: 0

Views: 492

Answers (1)

Lonami
Lonami

Reputation: 7086

First Steps - Updates in the documentation greets you with the following code:

import logging
logging.basicConfig(format='[%(levelname) 5s/%(asctime)s] %(name)s: %(message)s',
                    level=logging.WARNING)

from telethon import TelegramClient, events

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

@client.on(events.NewMessage)
async def my_event_handler(event):
    if 'hello' in event.raw_text:
        await event.reply('hi!')

client.start()
client.run_until_disconnected()

Note you can "call" any Python code inside my_event_handler. It also shows how @client.on() is meant to be used. Note there is no need for a scheduler.


I am using history = client(GetHistoryRequest) method.

As a side note this is raw API which is discouraged if a friendly alternative, like client.get_messages, exists.

Upvotes: 1

Related Questions