RuntimeError: Task got Future <Future pending> attached to a different loop

一世执手 提交于 2019-12-02 13:11:05

When you do:

TelegramClient(sn, api_id, api_hash)

Telethon needs to asyncio.get_event_loop(). This method returns the event loop for the current thread, which in your code, is the main thread. Telethon then remembers and uses the loop from the main thread.

When you do:

Thread(target=tele.client2.run_until_disconnected).start()

You are creating a new thread, and you get the corresponding error "Task got Future attached to a different loop" for the reasons I have explained.

When using asyncio, you generally shouldn't use threading unless you really know what you're doing.

In fact, the code can be rewritten as (removing all the unnecessary imports which probably were added without much thought):

Tele.py

from telethon import TelegramClient, functions, types

client = TelegramClient(sn, api_id, api_hash).start()

async def create_contact():
    return await client2(functions.contacts.ImportContactsRequest([
        types.InputPhoneContact(0, phone_number, first_name, last_name)
    ]))

app.py

from quart import Quart, websocket

app = Quart(__name__)

@app.websocket('/wa2tg2')
async def wa2tg2():
    while True:
        data = await websocket.receive()
        await tele.create_contact()

Some things to note:

  • client.start() can work without await.
  • client.run_until_disconnected() only needs to be called if you need to.
  • async def are called by using await on them, not by creating a separate thread.
  • The 0 you use in input contact will only work once (or not at all), since it needs to be a random number.
  • Never copy paste blindly. Understand what it does first.

Solved after passing loop to app.run

loop = asyncio.get_event_loop()
app.run(debug=1,loop=loop)        

Thread for client.run_until_disconnected() not needed since we pass the loop to the run method

More on Telethon and Quart

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!