coroutine'AuthMethods._start' was never awaited

Viewed 386

I'm just trying to get into making a bot that can read messages and reply... But I can't even execute the first example code in the documentation:

import asyncio
from telethon import TelegramClient

# Use your own values from my.telegram.org
api_id = 12345
api_hash = '0123456789abcdef0123456789abcdef'

async def main():
    # The first parameter is the .session file name (absolute paths allowed)
    async with TelegramClient('anon', api_id, api_hash).start() as client:
        await client.send_message('me', 'Hello, myself!')

asyncio.run(main())

This is the error I keep getting:


d:\Telegram bot\telegram bot\hello.py:10: RuntimeWarning: coroutine 'AuthMethods._start' was never awaited
  async with TelegramClient('anon', api_id, api_hash).start() as client:
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Traceback (most recent call last):
  File "d:\Telegram bot\telegram bot\hello.py", line 13, in <module>
    asyncio.run(main())
  File "C:\Users\Bruh\AppData\Local\Programs\Python\Python39\lib\asyncio\runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "C:\Users\Bruh\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 642, in run_until_complete  
    return future.result()
  File "d:\Telegram bot\telegram bot\hello.py", line 10, in main
    async with TelegramClient('anon', api_id, api_hash).start() as client:
AttributeError: __aenter__

I'm not sure what's my problem exactly as I don't seem many people having the same problem, I've trible checked the dependencies and I have everything up to date (except the optional dependencies which I haven't installed)

1 Answers

async with requires an object that has the method __aenter__ defined. TelegramClient has one but start() incorrectly documents that it returns an instance of itself -- looks like there are conditions that it will return other values.

Source: https://github.com/LonamiWebs/Telethon/blob/a00f74285cf98e2672897ea914163a5067f1caf8/telethon/_client/auth.py#L46

I can't fully reproduce for you because I don't know what Telethon is / don't have the tokens to get a client. Try examining the return-value of TelegramClient(...).start().

def main():
  started = TelegramClient('anon', api_id, api_hash).start()

  if not isinstance(started, TelegramClient):
    raise ValueError(f"Unexpected client: {started}")

  async with started as client:
    ...
  

asyncio.run(main())
Related