问题
The title explains it I guess. I have no code written down and it would be nice if someone explains the steps to the code. I want it to send a random link for a wallpaper from a website each time the command 'a wallpaper' is used. Any helpers?
回答1:
client.on('message', (message) => {
if (message.content.startsWith('!wallpaper')) {
// Here you can choose between creating your array with your own links or use a api that will generate it for you. For now i'll use an array
const wallpapers = [
'https://cdn.discordapp.com/attachments/726436777283289088/734088186711769088/images.png',
'https://cdn.discordapp.com/attachments/726436777283289088/734088144730718258/images.png',
'https://cdn.discordapp.com/attachments/726436777283289088/734087421918183484/images.png',
// You can add as many as you want
];
// Here we will create a random number. Math.random only creates a randomly generated number between 0 and 1.
const response = wallpapers[Math.floor(Math.random() * wallpapers.length)];
message.reply(response);
}
});
If you'd like, you can see more information about randomization in w3school / Randomization
回答2:
You would have to create an Array containing the responses you want to send. Then, you can use Math.random to get a random number between 0 and 1 (1 inclusive) and Math.floor to get the index ranging from 0 to arrayLength - 1.
const Responses = [
"image 1",
"image 2",
"image 3",
"image 4",
"image 5"
];
const Response = Math.floor(Math.random() * Responses.length);
console.log(Responses[Response])
client.on("message", message => {
if (message.author.bot) return false;
if (!message.guild) return false;
if (message.content.indexOf(Prefix) !== 0) return false;
const arguments = message.content.slice(Prefix.length).split(/ +/g); // Splitting the message.content into an Array with the arguments.
// Input --> !test hello
// Output --> ["test", "hello"]
const command = arguments.shift().toLowerCase();
// Removing the first element from arguments since it's the command, and storing it in a variable.
if (command == "random") {
const Response = Math.floor(Math.random() * Responses.length);
message.channel.send(`Here is your random response: ${Responses[Response]}`);
};
});
来源:https://stackoverflow.com/questions/63894234/how-can-i-make-a-random-response-in-discord-js