loopsasynchronouspython-asynciotelethon

I can't understand what's wrong with my loop/asyncio when trying to run a telethon script


I can't understand what's wrong with my loop/asyncio when trying to run a telethon script

I've tried multiple approaches, but I constatly get errors when trying to run the client with asyncio - so with all functions running at the same time forever 24/7

from telethon import TelegramClient, events
from telethon.tl.types import PeerUser, PeerChat, PeerChannel
import asyncio

API_ID = 'xyz'
API_HASH = 'xyz'
BOT_TOKEN = 'xyz'

# Create the bot client
bot = TelegramClient('bot_session', api_id=API_ID, api_hash=API_HASH).start(bot_token=BOT_TOKEN)

async def main():
        await bot.send_message('me', 'Using asyncio!')
        # and other functions of my own. i.e 
        # fetch_messages() etc 

asyncio.run(main())
raise RuntimeError('The asyncio event loop must not change after connection (see the FAQ for details)')

I don't want to make the post longer than it has to be so I'll skip all the other stuff I've tried because it failed :/

What I want to achieve is to have async def main() - and under them have all the other functions of mine I want to be runned asynchronously, and run them in a loop forever 24/7.

So far from what I've learned it should be done with asyncio.run(main()), and not client.run_forever or client.loop.something, but eh, none of them work for me anyway, so I have no idea what approach is the correct one

Full traceback:

Traceback (most recent call last):
  File "C:\Users\name123\PycharmProjects\TG_BOT\TG_BOT\main.py", line 55, in <module>
    asyncio.run(main())
  File "C:\Users\name123\AppData\Local\Programs\Python\Python38\lib\asyncio\runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "C:\Users\name123\AppData\Local\Programs\Python\Python38\lib\asyncio\base_events.py", line 616, in run_until_complete
    return future.result()
  File "C:\Users\name123\PycharmProjects\TG_BOT\TG_BOT\main.py", line 52, in main
    await bot.start()
  File "C:\Users\name123\PycharmProjects\TG_BOT\TG_BOT\.venv\lib\site-packages\telethon\client\auth.py", line 141, in _start
    me = await self.get_me()
  File "C:\Users\name123\PycharmProjects\TG_BOT\TG_BOT\.venv\lib\site-packages\telethon\client\users.py", line 165, in get_me
    me = (await self(
  File "C:\Users\name123\PycharmProjects\TG_BOT\TG_BOT\.venv\lib\site-packages\telethon\client\users.py", line 30, in __call__
    return await self._call(self._sender, request, ordered=ordered)
  File "C:\Users\name123\PycharmProjects\TG_BOT\TG_BOT\.venv\lib\site-packages\telethon\client\users.py", line 34, in _call
    raise RuntimeError('The asyncio event loop must not change after connection (see the FAQ for details)')
RuntimeError: The asyncio event loop must not change after connection (see the FAQ for details)
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x0000029B76F2DC0>
Traceback (most recent call last):
  File "C:\Users\name123\AppData\Local\Programs\Python\Python38\lib\asyncio\proactor_events.py", line 116, in __del__
  File "C:\Users\name123\AppData\Local\Programs\Python\Python38\lib\asyncio\proactor_events.py", line 108, in close
  File "C:\Users\name123\AppData\Local\Programs\Python\Python38\lib\asyncio\base_events.py", line 719, in call_soon
  File "C:\Users\name123\AppData\Local\Programs\Python\Python38\lib\asyncio\base_events.py", line 508, in _check_closed
RuntimeError: Event loop is closed
Task was destroyed but it is pending!
task: <Task pending name='Task-3' coro=<Connection._send_loop() running at C:\Users\name123\PycharmProjects\TG_BOT\TG_BOT\.venv\lib\site-packages\telethon\network\connection\connection.py:322> wait_for=<Future pending cb=[<TaskWakeupMethWrapper object at 0x0000029B92CD070>()]>>
Task was destroyed but it is pending!
task: <Task pending name='Task-4' coro=<Connection._recv_loop() running at C:\Users\name123\PycharmProjects\TG_BOT\TG_BOT\.venv\lib\site-packages\telethon\network\connection\connection.py:341> wait_for=<Future pending cb=[<TaskWakeupMethWrapper object at 0x0000029B8AB1FD0>()]>>
Task was destroyed but it is pending!
task: <Task pending name='Task-5' coro=<MTProtoSender._send_loop() running at C:\Users\name123\PycharmProjects\TG_BOT\TG_BOT\.venv\lib\site-packages\telethon\network\mtprotosender.py:464> wait_for=<Future pending cb=[<TaskWakeupMethWrapper object at 0x0000029B92CD790>()]>>
Task was destroyed but it is pending!
task: <Task pending name='Task-6' coro=<MTProtoSender._recv_loop() running at C:\Users\name123\PycharmProjects\TG_BOT\TG_BOT\.venv\lib\site-packages\telethon\network\mtprotosender.py:507> wait_for=<Future pending cb=[<TaskWakeupMethWrapper object at 0x0000029B8AB1E80>()]>>
Unexpected exception in the send loop

RuntimeError: Event loop is closed
Exception ignored in: <coroutine object Connection._send_loop at 0x0000029B84B2040>
RuntimeError: coroutine ignored GeneratorExit
Unhandled error while receiving data
Traceback (most recent call last):
  File "C:\Users\name123\AppData\Local\Programs\Python\Python38\lib\asyncio\queues.py", line 163, in get
    await getter
GeneratorExit

Solution

  • Don't use asyncio.run() instead first get the current event loop by loop = asyncio.get_event_loop() then use, loop.run_until_complete(main()) also start your client first using bot.start() then call run_until_complete

    Corrected Code:

    from telethon import TelegramClient, events
    from telethon.tl.types import PeerUser, PeerChat, PeerChannel
    import asyncio
    
    API_ID = 'xyz'
    API_HASH = 'xyz'
    BOT_TOKEN = 'xyz'
    
    # Create the bot client
    bot = TelegramClient('bot_session', api_id=API_ID, api_hash=API_HASH).start(bot_token=BOT_TOKEN)
    
    async def main():
        await bot.send_message('me', 'Using asyncio!')
        # and other functions of my own. i.e 
        # fetch_messages() etc 
    
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())