我想知道同时处理多个同步交互的最佳方法是什么?
例如,我为我们的 Discord 机器人构建了一个斜线命令库。其中一些需要一段时间来处理数据,其他人响应速度非常快。
我不太关心快速响应的交互,因为在给出响应之前有人同时运行斜杠命令的可能性相当小,但是..
但是我注意到,当我运行一个需要一段时间才能获取响应的斜杠命令时,然后在通过
interaction.reply
、interaction.editReply
或 interaction.followUp
给出响应之前运行相同的斜杠命令, Discord.js 似乎忘记了它应该回复哪个交互,并在尝试回复第一个交互的响应时抛出异常。
问题是,如果同时运行多个斜杠命令并处理多个交互,你们会如何处理它?
我尝试编写一个全局标志来检查交互何时挂起,例如:
let interactionProcessing // Within a global scope
...
// Further down, within the slash command functionality
if(interactionProcessing) {
return;
}
interactionProcessing = true;
// Logic here that processes the output
interaction.reply({content: theLogicsOutput}); // The issue here is, that it seems to have lost the definition for the initial interaction and throws an exception
interactionProcessing = false;
return;
我只是想看看其他人是否遇到过这个问题,以及他们是否有诚实的建议。
deferReply
向 API 确认您的机器人已收到交互,然后在完成后编辑延迟回复:
await interaction.deferReply();
// Your long running task here...
await interaction.editReply({ content: "Done!" });
如果您的机器人在几秒钟内没有响应用户的交互,API网关将超时。
(因为它假设您这边发生了错误)
延迟回复允许您先以思考状态回复用户,然后再编辑。