首页 > 解决方案 > Discord.js awaitMessages 循环?

问题描述

我正在尝试为 Discord 机器人(discord.js)上的简单游戏编写带有 awaitMessages 循环的循环。

到目前为止,这是我的这个模块的代码:

message.channel.awaitMessages(filter2, { max: 1 })
            .then(collected2 => {
            const response2 = collected2.first();
            if (response1.author.id === Fighter1 && response2.author.id === Fighter2)
                message.channel.send(`Round #1, FIGHT!!`);
                message.channel.send(`${Fighter1.user.username} Punch, Kick, or Block?`);
                message.channel.awaitMessages(filter1, { max: 1 })
                .then(collected => {
                    const response = collected.first();
                    });
                    if (response.author.id === Fighter1)
                        const Move1 = response.content
                    else
                        message.channel.send(`Not your turn!`)

如果满足 else 条件,我想让它恢复为 await.Messages,(并且不要在此过程中发送垃圾邮件“轮到你了!”消息。)有人可以帮忙吗?

标签: javascriptloopsdiscord.jsbots

解决方案


我不熟悉 discord.js,但首先我会删除这个 Promise 链并使用 async/await。您以后可以随时恢复它,但它会更容易阅读:

// wait for first response
const collected2 = await message.channel.awaitMessages(filter2, { max: 1 });
const response2 = collected2.first();

if (response1.author.id === Fighter1 && response2.author.id === Fighter2) {
  await message.channel.send(`Round #1, FIGHT!!`);
}

// prompt for attack input
await message.channel.send(`${Fighter1.user.username} Punch, Kick, or Block?`);

const collected = await message.channel.awaitMessages(filter1, { max: 1 });
const response = collected.first();

// process attack response
if (response.author.id === Fighter1) {
  const Move1 = response.content;
}
else {
  await message.channel.send(`Not your turn!`);
}

然后,通过一点递归,我们可以继续检查对攻击问题的响应:

// fn to process the attack response
async function waitForAttackInput(fighter) {
  // prompt for attack input
  const collected = await message.channel.awaitMessages(filter1, { max: 1 });
  const response = collected.first();

  // process attack response
  if (response.author.id === fighter) {
    //const Move1 = response.content;
    return response.content;
  }
  else {
    await message.channel.send(`Not your turn!`);
    waitForAttackInput(fighter);
  }
}

// wait for first response
const collected2 = await message.channel.awaitMessages(filter2, { max: 1 });
const response2 = collected2.first();

if (response1.author.id === Fighter1 && response2.author.id === Fighter2) {
  await message.channel.send(`Round #1, FIGHT!!`);
}


await message.channel.send(`${Fighter1.user.username} Punch, Kick, or Block?`);
    
const fighter1Response = await waitForAttackInput(Fighter1);


推荐阅读