0

Now I am sending a message to the user, and if the user sends a message with four buttons, the first one is pressed and the code does not stop working (it waits for a message from the user further). How can I make the code stop after clicking on the first button?

import random
from telethon import TelegramClient, events


api_id = 109258102341
api_hash = 'k12iy5k2u43v51ui34'

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

@client.on(events.NewMessage(chats=('@username')))
async def normal_handler(event):
    if event.message.button_count == 4:
        await event.message.click(0)

client.start()

client.send_message('@username', 'Hello')
client.run_until_disconnected()
fgrd4035
  • 51
  • 4

1 Answers1

0

Instead of:

client.run_until_disconnected()

You should use:

await client.disconnect()

And the script will exit after sending the message.

sophros
  • 14,672
  • 11
  • 46
  • 75
  • Compiler says that that I should put this line with await in async method, so I put it in method `normal_handler(event)`. Code starts working it asks phone number, password but then the error apperars `RuntimeWarning: coroutine 'MessageMethods.send_message' was never awaited client.send_message('@username', 'Hello') RuntimeWarning: Enable tracemalloc to get the object allocation traceback` – fgrd4035 Aug 20 '21 at 09:29
  • Actually, it should be fine to just use `client.disconnect()` without `await`. – sophros Aug 20 '21 at 09:33
  • You need to keep `client.run_until_disconnected()`, but use `await client.disconnect()` when you want the first call to exit (as the client will be disconnected). That is, you want to disconnect inside the handler after `click`. – Lonami Aug 20 '21 at 11:09
  • @Lonami thank you but error still appears: `RuntimeWarning: coroutine 'MessageMethods.send_message' was never awaited client.send_message('@username', 'Hello') RuntimeWarning: Enable tracemalloc to get the object allocation traceback` – fgrd4035 Aug 20 '21 at 11:21
  • Maybe you should have a look at answers to this question: https://stackoverflow.com/questions/54441424/learning-asyncio-coroutine-was-never-awaited-warning-error – sophros Sep 10 '21 at 05:02