我目前正在编写一个不和谐的机器人,它需要能够运行一个任务,这个任务可能需要几秒钟到一分钟的时间,同时还能响应其他命令。如果这是一个相当简单的问题,请原谅我,但我还没有找到一个有效的解决方案。
下面是代码的简略版本
class StableCog(commands.Cog, name='Stable Diffusion', description='Create images from natural language.'):
def __init__(self, bot):
self.text2image_model = Text2Image()
self.bot = bot
@commands.slash_command(description='Create an image.')
async def dream(self, -- a ton of arguments -- ):
print(f'Request -- {ctx.author.name}#{ctx.author.discriminator} -- Prompt: {query}')
asyncio.get_event_loop().create_task(src.bot.queue_system.dream_async( -- a ton of arguments -- ))内部queue_system.py
async def dream_async(-- a ton of arguments --):
await ctx.interaction.response.send_message('Added to queue! You are # in queue')
embed = discord.Embed()
try:
#lots of code, I've removed it since it doesn't have anything to do with the async
await ctx.channel.send(embed=embed, file=discord.File(fp=buffer, filename=f'{seed}.png'))
except Exception as e:
embed = discord.Embed(title='txt2img failed', description=f'{e}\n{traceback.print_exc()}', color=embed_color)
await ctx.channel.send(embed=embed)但是,在queue_system.py中的代码完成运行之前,不和谐的bot会变得没有响应性。到目前为止,我尝试过的每个解决方案都没有正确工作,因为我试图创建一个线程来运行异步方法。这样做最好的方法是什么?忽略名称queue_system.py,它还不是一个完全的队列系统,我只是在研究如何在计算出这个方法之前异步运行这个梦想的方法。
发布于 2022-09-30 02:40:54
是什么阻塞了dream_async协同线中的事件循环?在该协同机制中,如果您调用一些可能阻塞循环的(非异步)函数,这是一个问题,但真正的罪魁祸首必须在“大量代码”部分:)
一个很好的选择是使用遗嘱执行人()在线程池中运行非异步代码,从而防止该代码阻塞dream_async。
def blocking_stuff(arg):
# this will run in a thread
...
return 'something'
async def dream_async(-- a ton of arguments --):
loop = asyncio.get_event_loop()
await ctx.interaction.response.send_message('Added to queue! You are # in queue')
embed = discord.Embed()
try:
# Run the blocking part in a threadpool
result = await loop.run_in_executor(None, blocking_stuff, 'test')
await ctx.channel.send(embed=embed, file=discord.File(fp=buffer, filename=f'{seed}.png'))
except Exception as e:
embed = discord.Embed(title='txt2img failed', description=f'{e}\n{traceback.print_exc()}', color=embed_color)
await ctx.channel.send(embed=embed)希望我没有误解你。
https://stackoverflow.com/questions/73833686
复制相似问题