问题
I've been trying to put a random reply but the other answers and tutorials I found didn't exactly work. Most of the tutorials have
const messages = [
"seriously?! You thought I would reply",
"hm, yeh thats a pretty random question - Don't ya think?",
"Ok I'm actually running out of options now",
"Please stop asking me",
"Ok, im done!",
"⛔"
];
const randomMessage = messages[Math.floor(Math.random() * messages.length)];
And to complete it and send the message
module.exports = {
name: 'random',
description: 'random?',
execute(message, args){
message.channel.send(randomMessage);
}
}
However, the answer isn't really randomized. When I run the bot from the command prompt/terminal, the bot gets a random answer, but then when the user actually runs it, it only gives one answer.
For example, the answers can be 1, 2, or 3. When I run the bot one answer gets picked randomly; let's say 2. Then no matter what all users say, it will only give the answer of 2 as the reply. If I run the bot again and get, let's say 3, then the reply will only be 3.
回答1:
As Gabriel Andrade said, you need to put the randomMessage
constant inside of the execute function. If you don't, the random message will only be evaluated once when you start the bot.
module.exports = {
name: 'random',
description: 'random?',
execute(message, args){
// Now the randomMessage will be recalculated every time the command is run
const randomMessage = messages[Math.floor(Math.random() * messages.length)];
message.channel.send(randomMessage);
}
}
来源:https://stackoverflow.com/questions/64097858/random-message-reply-discord-js-2020