I'm creating a discord bot command that gives a question and two emojis on the question's message for user to react. If you select the wrong emoji, the bot will tell you "Wrong", react again on the message, and wait for the user to react. I want to put this into an infinite loop that only stops when the user chooses the correct emoji. This is what I have worked so far:
message.channel.send(`Question?`).then(sentMessage => {
sentMessage.react('✅');
sentMessage.react('❌');
const filter = (reaction, user) => {
return ['✅', '❌'].includes(reaction.emoji.name) && user.id != `${bid}`; // bid = bot's id
};
sentMessage.awaitReactions({ filter, max: 1, time: 60000, errors: ['time'] }).then(collected => {
var reaction = collected.first();
if (reaction.emoji.name === '❌') {
var check = true;
while (check) {
console.log('?');
message.channel.send('Wrong').then(sentMessage => {
sentMessage.react('✅');
sentMessage.react('❌');
const filter = (reaction, user) => {
return ['✅', '❌'].includes(reaction.emoji.name) && user.id != `${bid}`;
};
sentMessage.awaitReactions({ filter, max: 1, time: 60000, errors: ['time'] }).then(collected => {
var reaction = collected.first();
if (reaction.emoji.name == '✅') check = false;
});
});
}
}
});
});
The idea is when the user finally reacts ✅ after first reacting some ❌, check will become false and the loop will stop. However, after first choosing ❌, the while loop is not running any code inside it other than looping console.log('?'). Can someone point out where I did wrong?
In your code, you send Wrong and put the reaction check logic inside then and wrap with while.
However, since Channel.send returns a Promise, it will end almost instantly, continue the loop while doing Channel.send and reaction logic simultaneously.
You can use an async function and call it recursively.
So the code would be this:
message.channel.send(`Question?`).then(sentMessage => {
sentMessage.react('✅');
sentMessage.react('❌');
const filter = (reaction, user) => {
return ['✅', '❌'].includes(reaction.emoji.name) && user.id != `${bid}`; // bid = bot's id
};
sentMessage.awaitReactions({ filter, max: 1, time: 60000, errors: ['time'] }).then(collected => {
var reaction = collected.first();
if (reaction.emoji.name === '❌') {
async function reactionLoop() {
console.log('?');
let sentMessage = await message.channel.send('Wrong');
await sentMessage.react('✅');
await sentMessage.react('❌');
const filter = (reaction, user) => ['✅', '❌'].includes(reaction.emoji.name) && user.id != `${bid}`;
let collected = await sentMessage.awaitReactions({ filter, max: 1, time: 60000, errors: ['time'] })
var reaction = collected.first();
if (reaction.emoji.name == '✅') await reactionLoop();
}
reactionLoop();
}
});
});