0

I am working on a trivia game in a discord bot which at the moment works like this:

  1. User clicks "Begin" button
  2. Code adds user id to a set, and a while(set.has(user.id)) is executed
  3. In this loop: New question is sent to channel

Now, the way discord.js handles it is that buttons fire events when clicked, but I at the moment send the question in the while() loop to check for an ongoing game, so in order to not send random questions over and over again, I need the bot to wait before a button is pressed. Is that possible? Or would a different approach be better?

Code for this part is down here:

            const button_row_trivia_game_start_buttons = new Discord.MessageActionRow()
            .addComponents(
                new Discord.MessageButton()
                    .setCustomId("trivia_begin")
                    .setLabel("Start")
                    .setStyle("PRIMARY")
            )
            .addComponents(
                new Discord.MessageButton()
                    .setCustomId("trivia_cancel")
                    .setLabel("Cacnel")
                    .setStyle("DANGER")
            )

            const button_row_trivia_game_answer_buttons = new Discord.MessageActionRow()
                .addComponents(
                    new Discord.MessageButton()
                        .setCustomId("trivia_true")
                        .setLabel("Yes")
                        .setStyle("SUCCESS")
                )
                .addComponents(
                    new Discord.MessageButton()
                        .setCustomId("trivia_false")
                        .setLabel("No")
                        .setStyle("DANGER")
                )

            await interaction.reply({ embeds: [trivia_begin_embed], components: [button_row_trivia_game_start_buttons] }).then(() => {
                const button_row_trivia_game_begin_buttons_collector = interaction.channel.createMessageComponentCollector({ componentType: 'BUTTON', time: 60000, max: 1 });

                button_row_trivia_game_begin_buttons_collector.on('collect', async (collectedButtonClick) => {
                    if(collectedButtonClick.user.id === interaction.user.id) {
                        if(collectedButtonClick.customId === "trivia_begin") {
                            set_trivia_ongoing_trivia_games.add(uniqueUserKey)

                            while(set_trivia_ongoing_trivia_games.has(uniqueUserKey)) {
                                let trivia_question_counter = 0
                                let trivia_droplet_earnings = 0
                                let trivia_question_randomness_decider = Math.floor(Math.random() * 100)

                                let trivia_question = await getQuestions({ 
                                    amount: 1,
                                    difficulty: "easy",
                                    type: "boolean",
                                    category: Category.allNames.GENERAL_KNOWLEDGE
                                });

                                let trivia_question_embed = new Discord.MessageEmbed()
                                .setColor(0x009dff)
                                .setTitle(`\u{1F5F3} Fact Check!`)
                                .addFields(
                                    {
                                        name: `${trivia_question[0].value} **Is this true?**`,
                                        value: `Question **${trivia_question_counter}** | Droplets earned: **${trivia_droplet_earnings}**`,
                                        inline: true,
                                    },
                                )

                                console.log("NOW SENDING QUESTION")

                                await collectedButtonClick.update({ embeds: [trivia_question_embed], components: [button_row_trivia_game_answer_buttons] }).then(() => {
                                    const button_row_trivia_game_answers_collector = collectedButtonClick.channel.createMessageComponentCollector({ componentType: 'BUTTON', time: 10000, max: 1 });

                                    button_row_trivia_game_answers_collector.on('collect', async (answer) => {
                                        trivia_question_counter = trivia_question_counter + 1

                                        if(answer.customId === "trivia_true" || trivia_question.correctAnswer === "True") {    // correct yes
                                            collectedButtonClick.update(`CORRECT ANSWER (NO. ${trivia_question_counter})`)
                                            console.log("a")
                                        }
                                        else if(answer.customId === "trivia_true" || trivia_question.correctAnswer === "False") {      // wrong yes
                                            collectedButtonClick.update(`WRONG ANSWER (NO. ${trivia_question_counter})`)
                                            set_trivia_ongoing_trivia_games.delete(uniqueUserKey);
                                            console.log("b")
                                        }
                                        else if(answer.customId === "trivia_false" || trivia_question.correctAnswer === "True") {      // wrong no
                                            collectedButtonClick.update(`WRONG ANSWER (NO. ${trivia_question_counter})`)
                                            set_trivia_ongoing_trivia_games.delete(uniqueUserKey);
                                            console.log("c")
                                        }
                                        else if(answer.customId === "trivia_false" || trivia_question.correctAnswer === "False") {     // correct no
                                            collectedButtonClick.update(`CORRECT ANSWER (NO. ${trivia_question_counter})`)
                                            console.log("d")
                                        }
                                    })
                                })


                            }

                        } else {
                            collectedButtonClick.update({ content: "Game cancelled.", embeds: [], components: [] })
                        }
                    }

                    button_row_trivia_game_begin_buttons_collector.on('end', async (collectedObjects, reason) => {
                    if(reason != "limit") {
                        await interaction.editReply({ embeds: [trivia_question_timeout_embed], components: [] });
                    }
                });

                return;

For context: The collector is the discord.js object that collects the buttons pressed, and fires the event once a button is pressed. Some of the embeds are defined earlier in the code. Any help is appreciated!

  • Please fix your code's tabbing so that it can be read. – Lee Taylor Apr 29 '22 at 23:29
  • 1
    This might help: https://stackoverflow.com/questions/10058753/how-to-create-pause-or-delay-in-for-loop (Spoiler: no can do.) – bloodyKnuckles Apr 30 '22 at 00:34
  • Well, technically you can do this if you use asynchronous code. The question is, is that really the best way to go about this? The answer is no. Instead of trying to pause a while loop, it would probably be a lot better and more efficient to use recursive code here in my opinion. – Cannicide May 01 '22 at 22:58

0 Answers0