首页 > 解决方案 > 如何在 Discord.js 中做出随机响应

问题描述

我猜标题解释了它。我没有写下代码,如果有人解释代码的步骤会很好。每次使用“壁纸”命令时,我希望它从网站发送壁纸的随机链接。有帮手吗?

标签: javascriptnode.jsdiscorddiscord.jsbots

解决方案


您必须创建一个Array包含您要发送的响应的内容。然后,您可以使用Math.random获取 0 到 1(包括 1)之间的随机数,并Math.floor获取范围从 0 到 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]}`);
    };
});

推荐阅读