Search code examples
pythonpython-asynciotelethon

can't get to work an async function. telethon python asyncio


im trying to understand asyncio and integrating it into my program.

i tried with this method:

def my_test():
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    loop.run_until_complete(my_function(group_id))

#//// code
    
async def my_function(group_id):
    group_id = (int(group_id))
    user = await client.get_entity(PeerUser(group_id)) # a telethon method the get an entity 
    print (user)

i tried with different methods.. but the code stops at user = without any error so i don't have anything to search about


Solution

  • yeah, as I thought that was a stupid thing. can't find anything related to it so i guess this can help someone:

    when you call client.start() you are creating a loop, and with client.run_until_disconnected() you basically telling asyncio to not stop the code until you disconnect client. so what was the solution? (reading and understanding the docs lmao)

        if to_search == "id" or to_search == "ID" or to_search == "Id":
            clr(); group_id = (input(f"{info}{r}Insert group id:{rs}\n>>> "))
    

    -------> client.add_event_handler(func_name)<---- the async one

    then i noted that the func is executed like 6 times(can't understand why tho) so make sure to start the async function like this:

            async def search_by_id(event):
               client.remove_event_handler(func_name)