Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

305
Visualizações
Stop an infinite loop when correct reaction is met discord.js

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?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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();
                    }
                });
            });
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda