【发布时间】:2023-04-03 03:25:01
【问题描述】:
我正在使用 discord.py 库并正在开发一个 discord 机器人。
基本上,我需要我的机器人每小时访问一个网站并获取一些有关 selenium 的信息。 我想在一个线程中执行此操作以避免在信息收集期间阻塞机器人。
@tasks.loop(hours=1)
async def getwebsiteinfo(self):
thr = threading.Thread(target=self.getwebsiteinfofunc)
thr.start()
获取网站信息功能:
def getwebsiteinfofunc(self):
...
channel.send(f"```sometext```")
..
问题是:channel.send 需要用 await 调用,但我不能用 await 调用它,因为它不在异步函数中。
但我不能将 getwebsiteinfofunc 定义为异步,因为我不能将异步函数与线程一起使用。
我尝试了 asyncio,但我从未使用过它并且失败了。
有什么想法吗?
【问题讨论】:
-
见here。
-
我不能使用 loop.run_in_executor 因为我应该在哪里调用它?如果我在班级的初始化中调用它,它不是异步的
-
请记住,我需要它在循环中运行它不是等待一段时间的一次性命令
-
您可以在异步函数中使用
result = await loop.run_in_executor(ThreadPoolExecutor(), self.getwebsiteinfofunc)而不是thr = threading.Thread(target=self.getwebsiteinfofunc)。然后您可以在异步函数中调用await channel.send(result)。如果您需要这些特定代码,请使用minimal, reproducible example 更新您的问题(可以按原样运行的代码,而不仅仅是 sn-ps)。
标签: python asynchronous async-await bots discord.py