Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.1k views
in Technique[技术] by (71.8m points)

javascript - Discord.js awaitMessages loop?

I'm trying to write a loop with awaitMessages loop for a simple game on a Discord bot (discord.js).

Here is my code for this module thus far:

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!`)

I want to make it revert to await.Messages if the else condition is met, (and not spam the 'Not your turn!' message in the process.) Can anyone help?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I'm not familiar with discord.js but first I would remove this Promise chain and use async/await. You can always revert this later but it will make it much easier to read:

// 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 {
  const message.channel.send(`Not your turn!`);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

63 comments

56.6k users

...