S
S
Stepan2020-04-27 15:00:01
Python
Stepan, 2020-04-27 15:00:01

How to attach decorators in a loop?

I am making a bot in a telegram that reads messages from several accounts. To receive messages, the following construction is used:

@clien1t.on(events.NewMessage)
async def handler(event):
        word = event.message.to_dict()['message']
        if (word[:18] == "Код подтверждения:"):
            print(word)

For 1 client this works. Then 2 clients:
@client1.on(events.NewMessage)
@client2.on(events.NewMessage)
async def handler(event):
        word = event.message.to_dict()['message']
        if (word[:18] == "Код подтверждения:"):
            print(word)

And so everything works - that is, it receives all messages from 2 accounts. But how can I link, for example, 10 accounts in a cycle? Of course, I can write
@client1.on(events.NewMessage)
@client2.on(events.NewMessage)
@client3.on(events.NewMessage)
@client4.on(events.NewMessage)
...
@client10.on(events.NewMessage)

But it will not be convenient and not extensible. I tried it like this:
for i in range(3):
    client = TelegramClient(session_names[i], api_id, api_hash)
    clients.append(client)
    testclient=clients[i]
    @testclient.on(events.NewMessage)
    async def handler(event):
        word = event.message.to_dict()['message']
        if (word[:18] == "Код подтверждения:"):
            print(word)

But in this way, only the messages of the last account are read (that is, the third one, and the first and second accounts are ignored). How can I attach several decorators to this function in a loop?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
javedimka, 2020-04-27
@Stepashka20

You can just read how decorators work and what is syntactic sugar

async def handler(event):
        word = event.message.to_dict()['message']
        if (word[:18] == "Код подтверждения:"):
            print(word)

for client in clients:
    handler = client.on(events.NewMessage)(handler)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question