Search code examples
pythontelethon

telethon: How to block a spammer user


Im using telethon to recieve messages. When a user sends more messages than he/she was allowed, he/she will get blocked. im having trouble with the blocking part. Here is my code:

with TelegramClient('session', api_id, api_hash) as client:
    @client.on(events.NewMessage())
    async def handler(event):
        if event.message:
            sender = str((await event.get_sender()).username)
            if sender not in spam_list:
                await event.reply('Message received.')
            else:
                # block the sender
                result = client(functions.contacts.BlockRequest(
                    id=sender
                ))
                print(result)

    client.run_until_disconnected()

However, block the sender part generates the following error:

<coroutine object UserMethods.__call__ at 0x000001E8E8276040>
C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\telethon\client\updates.py:454: RuntimeWarning: coroutine 'UserMethods.__call__' was never awaited
  await callback(event)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

I would appreciate any suggestions on how i implement the block spammer user part.


Solution

  • Telethon is an async library, and as such, its methods must be await-ed. As the warning explains:

    RuntimeWarning: coroutine 'UserMethods.call' was never awaited

    Therefore, the solution is to use await:

                    #        vvvvv note the await
                    result = await client(functions.contacts.BlockRequest(
                        id=sender
                    ))