首页 > 解决方案 > 将异步函数传递给线程python

问题描述

我正在构建一个 Discord 机器人,其中大部分是基于事件的。机器人准备好后,我想要一个线程,当机器人还活着时,有时会在聊天中写“嗨”,然后休眠 2 分钟。代码:

async def on_ready(self):
    t = threading.Thread(target=self.say_hi)
    t.start()

async def say_hi(self):
    while True:
        chance = random.randint(0, 101)

        if chance <= 25:
            await self.channel.send('hi')
        time.sleep(60 * 2)

问题是我得到不同的错误。RuntimeWarning: Enable tracemalloc to get the object allocation traceback在这种情况下。我尝试按照这个有点相关的答案以这种方式编辑代码:

def say_hi(self):
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)

    loop.run_until_complete(self.say_hi_aux())
    loop.close()

async def say_hi_aux(self):
    while True:
        chance = random.randint(0, 101)

        if chance <= 25:
            await self.channel.send('hi')
        await asyncio.sleep(60 * 2)

但由此产生的错误RuntimeError: Timeout context manager should be used inside a taskloop.run_until_complete()方法上。

我不知道这两种解决方案有什么问题

标签: pythonmultithreadingdiscord.py

解决方案


推荐阅读