Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.6k 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...