@tree.command(name = "example_command", description = "Example")
async def example_command(interaction):
await interaction.response.defer()
try:
file = test_function() # Takes a couple of seconds to run
d_file = discord.File('nba_ev.png')
await interaction.followup.send(file=d_file)
except Exception as e:
print(f"An error occurred: {e}")
error_message = "An error occurred while processing your request. Please try again."
await interaction.followup.send(content=error_message, ephemeral=True)
我在 python 中有一个不和谐的斜杠命令
example_command
它调用一个函数test_function()
,需要几秒钟才能运行。
问题是当另一个用户尝试使用
example_command
或不同的斜杠命令但 test_function
仍在运行时,我收到错误“应用程序没有响应”,我认为这是因为 await interaction.response.defer()
没有在内部调用3 秒,因为上次调用的 test_function
仍在运行
如何阻止这种情况发生?我目前在 GCP 计算引擎上托管它
出现此问题是因为您的
test_function()
函数是完全同步的。这样,你的机器的处理器进入这个函数后,只有完全完成后才会退出,从而无法并行执行其他命令。
要解决此问题,您可以尝试实现线程或将同步
test_function
函数转换为异步函数。
当尝试使其成为异步函数时,您可以首先消除不良做法,例如将
time.sleep()
替换为 await asyncio.sleep()
以及使用 aiohttp
代替 requests
。不要忘记使用 async def
将函数定义为异步。