How can I make a random response in Discord.js

后端 未结 2 341
旧巷少年郎
旧巷少年郎 2021-01-27 18:09

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

2条回答
  •  时光取名叫无心
    2021-01-27 18:37

    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]}`);
        };
    });
    

提交回复
热议问题