python 不协调斜线命令在3秒内没有响应

qxgroojn  于 2024-01-05  发布在  Python
关注(0)|答案(1)|浏览(137)
  1. @tree.command(name = "example_command", description = "Example")
  2. async def example_command(interaction):
  3. await interaction.response.defer()
  4. try:
  5. file = test_function() # Takes a couple of seconds to run
  6. d_file = discord.File('nba_ev.png')
  7. await interaction.followup.send(file=d_file)
  8. except Exception as e:
  9. print(f"An error occurred: {e}")
  10. error_message = "An error occurred while processing your request. Please try again."
  11. await interaction.followup.send(content=error_message, ephemeral=True)

字符串
我在python example_command中有一个discord斜杠命令,它调用了一个需要几秒钟运行的函数test_function()
问题是,当另一个用户尝试使用example_command或不同的斜杠命令,但test_function仍在运行时,我得到一个错误“应用程序没有响应”,我认为这是因为await interaction.response.defer()没有在3秒内被调用,因为上一次调用的test_function仍在运行
我如何才能阻止这种情况发生?我目前正在托管此GCP计算引擎

hec6srdp

hec6srdp1#

出现这个问题是因为你的test_function()函数是完全同步的。这样,你机器的处理器进入这个函数后,只有在完全完成的时候才会离开,导致无法并行执行其他命令。
要解决这个问题,可以尝试实现线程或将同步test_function函数转换为异步函数。
在尝试使其成为异步函数时,您可以首先消除不好的做法,例如将await asyncio.sleep()替换为time.sleep(),并使用aiohttp代替requests。不要忘记使用async def将函数定义为异步。

相关问题