How can I make a random response in Discord.js

后端 未结 2 335
旧巷少年郎
旧巷少年郎 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]}`);
        };
    });
    
    0 讨论(0)
  • 2021-01-27 19:04
    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

    0 讨论(0)
提交回复
热议问题