Discord.js - Getting information after Prefix and command

Viewed 3429

I'm now working in a new command, a poll command. For that, I need a way of get the arguments after the prefix and the command itself.

Example: +Poll Do you like puppies?

And, it'd ignore the "+Poll", and get only the question itself, for then create a poll.

To get the arguments, I'm using:

var Args = message.content.split(/\s+/g)

1 Answers

You probably want to try creating the poll with a command, store the question in your database, and then use a separate command to display current polls that are open. Then the users would select the poll via command and the bot would await the response to the question.

I won't go into detail about storing the question in a database, because that's a totally different question. If you need help setting up a local database and store the polls, link to another question and I'll be happy to give more examples.

To go with your question, I would suggest using subStr to save each word after the command in an array, so you can later use those parts in the code. Something like this will store everything after !poll in the variable poll:

if (message.content.startsWith("!poll ")) {
    var poll = message.content.substr("!poll ".length);
    // Do something with poll variable //
    message.channel.send('Your poll question is: ' + poll);
});

For the user answering the poll, you can try using awaitMessage to ask the question, and give a set number of responses. You would want to wrap this in a command that queries your database for the available polls first, and use that identifier to actually get the right question and possible reponses. The example below just echos the response that is collected, but you would want to store the response in the database instead of sending it in a message.

if (message.content === '!poll') {
    message.channel.send(`please say yes or no`).then(() => {
            message.channel.awaitMessages(response => response.content === `yes` || response.content === 'no',  {
                max: 1, // number of responses to collect
                time: 10000, //time that bot waits for answer in ms
                errors: ['time'],
            })
                .then((collected) => {
                    var pollRes = collected.first().content; //this is the first response collected
                    message.channel.send('You said ' + pollRes);
                    // Do something else here (save response in database)
                })
                .catch(() => { // if no message is collected
                    message.channel.send('I didnt catch that, Try again.');
                });
        });
};
Related