skip to Main Content

Upon trying following code on Telethon 1.11.3 , python 3.7.3

from telethon import TelegramClient

api_id = xxx #i give my id
api_hash = xxx##i give my 
client = TelegramClient(name, api_id, api_hash)

async def main():

    # Now you can use all client methods listed below, like for example...
    await client.send_message('me', 'Hello to myself!')

with client:
    client.loop.run_until_complete(main())

I get error as RuntimeError: You must use “async with” if the event loop is running (i.e. you are inside an “async def”)

2

Answers


  1. The problem is not the code itself but the shell you used. IPython and similar run the asyncio event loop which break Telethon’s sync magic.

    To work around this, you can use a normal python shell or write async and await in the right places:

    from telethon import TelegramClient
    
    api_id = ...
    api_hash = ...
    client = TelegramClient(name, api_id, api_hash)
    
    async def main():
        # Now you can use all client methods listed below, like for example...
        await client.send_message('me', 'Hello to myself!')
    
    # Note the async and await keywords
    async with client:
        await main()
    

    Of course, in this scenario, main() is not really necessary either:

    async with client:
        await client.send_message('me', 'Hello to myself!')
    
    Login or Signup to reply.
  2. # Create an object for TelegramClient()
    client = TelegramClient(phone, api_id, api_hash)
    
    async with client :
        await client.send_message('me', 'Hello!!!!!')
    client.connect()
    
    if not client.is_user_authorized() :
        client.send_code_request(phone)
        client.sign_in(phone, input('Enter verification code : '))
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search