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
332 views
in Technique[技术] by (71.8m points)

javascript - Discord.js - Is there a method for discord bots to recursively ask questions? Like a form filler bot?

I've written some code down below. My main experience coding is with Python, but I got hooked on a discord.js tutorial and decided to give discord bot coding a try (I know that there's a Python option, but I've already invested a lot of time into this, so unless if it's not feasible, then I will most likely not switch over). I'm still taking a while to get the concept of async/await, hopefully I've applied it correctly in the code. It currently works just asking one question, but I can't seem to continue the operation, even though the counter seems to add fine. I was thinking of a recursive solution, but whenever I do a while loop or a recursion function it still starts on the first question again either way. My main concerns would be whether or not I'm going in a path that can get me to ask multiple questions.


tl;dr: The code I've written down below allows the bot to record one response, but when I try to make it repeat using a continuous recursive function, the code just starts back at question 1.

const Discord = require('discord.js');
const client = new Discord.Client();
const token = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';

client.login(token);

const quiz = require('./q.json');
var num = 0;
var item = quiz[num];
var messg = "";
//var line = []; ignore this, this is for recording the responses onto a different application later

client.on('message', async message => {
    if (message.author.bot) return;

    if (message.content === '!test') {
        collec(message);
    }
})

async function collec(message) {
    message.reply(item.question);
    //checks to see if the author that used commmand is the same + if it's an option
    //isPossibleOption() = just constantly gets rid of one element until it fits w/ criteria
    const filter = m => m.author.id === message.author.id && isPossibleOption(m.content, item.answers);

        var collector = new Discord.MessageCollector(message.channel, filter, { max: 1 });

        collector.on("collect", async msg => {
            messg = msg.content;
            //await recordAnswer(messg, num); record it onto google sheets / check for q
            message.channel.send('Next question!');
            nextQ();
        })

        collector.on("end", collected => {});
}

async function isPossibleOption (message, file) {
    var i;
    for (i = 0; i < file.length; i++) {
        if (message.toLowerCase() == file[i]) {
            return true;
        }
    }
    return false;
}

function nextQ () {
    num++;
    item = quiz[num];
}
question from:https://stackoverflow.com/questions/65877569/discord-js-is-there-a-method-for-discord-bots-to-recursively-ask-questions-li

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

1 Reply

0 votes
by (71.8m points)

Message collectors is more of an umbrella term, there are multiple ways to do this in Discord.js. Check out the docs here for more information. To record multiple answers from a user input, your code should look similar to this:

message.channel.send("Please enter an animal:").then(() => {     

  const filter = (user) => {
    return user.author.id === message.author.id && !user.bot  // do not respond to bots, and only respond to the user that called the command
  };

  message.channel.awaitMessages(filter, { max: 1, time: 15000, errors: ['time'] })
      .then(collected => {
        
      // collected is an object created by the awaitmessages event, I will put some dummy code here

      if (collected.content === 'dinosaur') {
        message.channel.send(':white_check_mark: Dinosaur')
      }

      message.channel.send(':white_check_mark:').then(() => {

            message.channel.send("Please enter an animal:").then(() => {                  

              message.channel.awaitMessages(filter, { max: 1, time: 15000, errors: ['time'] }) //the ['time'] parameter is declaring what the awaitMessages depends upon
                  .then(collected => {                                                         // it can also be ['idle'] and a few more, but we need ['time']
                      
                      if (collected.content === 'puppy') {
                        message.channel.send(':white_check_mark: Puppy :dog:')
                      }
                      message.channel.send(':white_check_mark:')
                  });
            });
        });
    });
});

Please let me know if you have any questions. If you are using a DB, simply put the DB write code in the final .then(collected =>) statement


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

...