skip to Main Content
import random
from telethon import TelegramClient, events


def main():
    api_id = 9123640
    api_hash = '8as6fgvs8t9ar76fse89rgearz'
    chat = '@username'
    message = 'hi'

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

    @client.on(events.NewMessage(chats=chat))
    async def normal_handler(event):
        if event.message.button_count == 4:
            await event.message.click(random.randint(0, 3))
            await client.disconnect()

    client.start()
    client.send_message(chat, message)
    client.run_until_disconnected()


if __name__ == '__main__':
    main()

I want to send message to user then get back from user message with 4 buttons, click random button and stop script. Problem with sending message. If I comment line client.send_message(chat, message) and send message by myself, code will continue working fine but but line client.send_message(chat, message) an error appears:

RuntimeWarning: coroutine 'MessageMethods.send_message' was never awaited
  client.send_message('@username', 'hi')
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

How to solve this problem?

3

Answers


  1. Chosen as BEST ANSWER
    import random
    from telethon import TelegramClient, events
    from asyncio import run
    
    
    async def main():
        api_id = 9123640
        api_hash = '8as6fgvs8t9ar76fse89rgearz'
        chat = '@username'
        message = 'hi'
    
        client = TelegramClient('afewfe', api_id, api_hash)
    
        @client.on(events.NewMessage(chats=chat))
        async def normal_handler(event):
            if event.message.button_count == 4:
                await event.message.click(random.randint(0, 3))
                await client.disconnect()
    
        client.start()
        await client.send_message(chat, message)
        client.run_until_disconnected()
    
    if __name__ == "__main__":
        run(main())
    
    

    Full error:

    C:UsersaesokDesktopairdroper2telegram_hi.py:20: RuntimeWarning: coroutine 'AuthMethods._start' was never awaited
      client.start()
    RuntimeWarning: Enable tracemalloc to get the object allocation traceback
    Traceback (most recent call last):
      File "C:UsersaesokDesktopairdroper2telegram_hi.py", line 25, in <module>
        run(main())
      File "C:UsersaesokAppDataLocalProgramsPythonPython39libasynciorunners.py", line 44, in run
        return loop.run_until_complete(main)
      File "C:UsersaesokAppDataLocalProgramsPythonPython39libasynciobase_events.py", line 642, in run_until_complete
        return future.result()
      File "C:UsersaesokDesktopairdroper2telegram_hi.py", line 21, in main
        await client.send_message(chat, message)
      File "C:UsersaesokDesktopairdroper2venvlibsite-packagestelethonclientmessages.py", line 853, in send_message
        result = await self(request)
      File "C:UsersaesokDesktopairdroper2venvlibsite-packagestelethonclientusers.py", line 30, in __call__
        return await self._call(self._sender, request, ordered=ordered)
      File "C:UsersaesokDesktopairdroper2venvlibsite-packagestelethonclientusers.py", line 58, in _call
        future = sender.send(request, ordered=ordered)
      File "C:UsersaesokDesktopairdroper2venvlibsite-packagestelethonnetworkmtprotosender.py", line 172, in send
        raise ConnectionError('Cannot send requests while disconnected')
    ConnectionError: Cannot send requests while disconnected
    
    Process finished with exit code 1
    
    

  2. It looks like you are running asynchronous code in a normal function. The error is complaining that the client.send_message(chat, message) code doesn’t have the await keyword before it. In order to be able to run any async function the way you want to (as just a normal function call), you must have the await keyword before the function call’s code. To be able to use the await keyword without throwing an error, the outer function holding the code (main) needs to be asynchronous and can be run with asyncio.run.

    from asyncio import run
    
    async def main():
        # your code
    
        client.start()
        client.run_until_disconnected()
        await client.send_message(chat, message)
    
    if __name__ == "__main__":
        run(main())
    
    Login or Signup to reply.
  3. Just import:

    from telethon.sync import TelegramClient
    from telethon import TelegramClient, events
    

    That should work.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search