【问题标题】:Discord.js | Command Cooldown is set but not working不和谐.js |命令冷却时间已设置但不起作用
【发布时间】:2021-10-08 14:12:42
【问题描述】:

所以冷却时间所在的 message.js 和 help.js 是一个命令,help 命令当前设置为60 seconds,正如你在cooldown 看到的那样,但无论我在那里输入什么,它都没有' t 工作并且仍然设置为小于1 秒我猜输出请检查包含在这个问题中的GIF。

message.js:

const Discord = require("discord.js");
const settings = require("../../config/settings.json");

const cooldowns = new Discord.Collection();

module.exports = async (client, message) => {
    if (message.author.bot) return;
    const prefixesdatabase = client.settings.ensure(message.guild.id, settings);

    if (!client.settings.get(message.guild.id, "prefix")) {
        client.settings.set(message.guild.id, {
            prefix: settings.prefix
        });
    }

    if (message.content.match(new RegExp(`^<@!?${client.user.id}>( |)$`))) {
        message.reply(`my prefix is: \`${prefixesdatabase.prefix}\``);
    }

    if (!message.content.startsWith(prefixesdatabase.prefix)) return;
    const command = message.content
        .split(" ")[0]
        .slice(prefixesdatabase.prefix.length);
    const args = message.content.split(" ").slice(1);
    if (!cooldowns.has(command.name)) {
        cooldowns.set(command.name, new Discord.Collection());
    }
    const now = Date.now();
    const timestamps = cooldowns.get(command.name);
    const cooldownAmount = (command.cooldown || 2) * 1000;
    if (timestamps.has(message.author.id)) {
        const expirationTime = timestamps.get(message.author.id) + cooldownAmount;
        if (now < expirationTime) {
            const timeLeft = (expirationTime - now) / 2000;
            return message.reply(
                `Before using **${
                    prefixesdatabase.prefix
                }${command}**, please wait for **${timeLeft.toFixed(
                    1
                )} second for cooldowns!**`
            );
        }
    }
    timestamps.set(message.author.id, now);
    setTimeout(() => timestamps.delete(message.author.id), cooldownAmount);
    let cmd;
    if (client.commands.has(command)) {
        cmd = client.commands.get(command);
    } else if (client.aliases.has(command)) {
        cmd = client.commands.get(client.aliases.get(command));
    }
    try {
        cmd.run(client, message, args);
    } catch (e) {
        return console.log(`Invalid command: ${command}`);
    } finally {
        console.log(
            `${message.author.username} using command ${prefixesdatabase.prefix}${command}`
        );
    }
};

help.js

const Discord = require("discord.js");

module.exports.run = async (client, message, args) => {
    const settings = require("../../config/settings.json");
    const prefixesdatabase = client.settings.ensure(message.guild.id, settings);

    const helpArray = message.content.split(" ");
    const helpArgs = helpArray.slice(1);

    if (!helpArgs[0]) {
        const embed = new Discord.MessageEmbed()
            .setColor("#b491c8")
            .setDescription(
                `**My prefix:** \`${prefixesdatabase.prefix}\` , Slash Commands list for \`/help\`\nClick [HERE](https://discord.com/api/oauth2/authorize?client_id=${client.user.id}&permissions=8&scope=bot%20applications.commands) to invite me to your server.`
            )
            .addField("**:gear: Basic**", "`help`, `ping`, `vote`, `uptime`, `setprefix`")
            .addField(
                "**????️ Moderation**",
                "`ban`, `clear`, `clearwarn`, `createchannel`, `createemoji`, `kick`, `lockchannel`, `mute`, `rename`, `slowmode`, `unban`, `unlockchannel`, `unmute`, `warn`, `warnings`"
            )           
            .addField(
                "**⚙ Utility**",
                "`aes256`, `avatar`, `channel`, `embed`, `roleinfo`, `reverse`, `setafk`, `snipe`, `stats`, `timer`, `translate`, `whois`, `weather`, `youtube`"
            )
            .addField(
                "**:magic_wand: Pruning**",
                "`urole`, `unorole`, `krole`, `knorole`, `fetch`"
            )           
            .addField(
                "**:tada: Giveaways**",
                "`start-giveaway`, `reroll`, `end-giveaway`"
            )
            .addField(
                "**:frame_photo: Images**",
                "`captcha`, `circle`, `delete`, `gay`, `changemymind`, `trigger`, `clyde`, `petpet`, `magik`, `iphonex`"
            )
            .addField(
                "**:musical_note: Music**",
                "`play`, `stop`, `skip`, `queue`, `autoplay`, `loop`, `volume`, `pause`, `resume`"
            )
            .addField(
                "**:partying_face: Fun**",
                "`8ball`, `cat`, `deaes256`, `kiss`, `meme`, `ngif`, `pat`, `poke`, `smug`, `thigh`, `tickle`"
            )           
            .addFields(
                { name: ':desktop: Github (Source Code)', value: 'https://github.com/mashwishi/PruneBot' },
                { name: ':revolving_hearts: Support the Developer:', value: 'https://ko-fi.com/mashwishi' }   
              )         
            .setTitle('Prune Bot | Commands')
            .setFooter(`©${nowyear} ${client.user.username} Created by Mashwishi.\nCommand requested by: ${message.author.username}#${message.author.discriminator}`, `https://i.imgur.com/ypxq7B9.png`)
            .setThumbnail('https://i.imgur.com/ypxq7B9.png')    
            .setAuthor('Join our Discord Server', 'https://i.imgur.com/hKeHeEy.gif', 'https://discord.io/LIMYAW');
        message.channel.send({ embed });
    }

    if (helpArgs[0]) {
        let command = helpArgs[0];

        if (client.commands.has(command)) {
            command = client.commands.get(command);
            let alia = command.help.aliases;
            if (command.help.aliases < 1) alia = "No aliases";

            const embed = new Discord.MessageEmbed()
                .setAuthor(
                    `Command: ${command.help.name}`,
                    client.user.displayAvatarURL()
                )
                .setDescription(
                    `
            **Description:**\n\`\`\`${
                            command.help.description ||
                            "There is no Description for this command."
                        }\`\`\`\n**Usage:**\n\`\`\`${
                        command.help.usage || "No Usage"
                    }\`\`\`\n**Permissions:**\n\`\`\`${
                        command.help.accessableby || "Members"
                    }\`\`\`\n**Cooldown (in seconds):**\n\`\`\`${
                        command.help.cooldown || "No Cooldown"
                    }\`\`\`\n**Aliases:**\n\`\`\`${alia}\`\`\``
                    
                )
                .setColor("#4a4b4d")
                .setFooter(
                    `© ${nowyear} ${client.user.username} | This command requested by ${message.author.username}#${message.author.discriminator}`
                );

            message.channel.send(embed);
        } else {
            const embeds = new Discord.MessageEmbed()
                .setDescription(`${emojis.cross} Command is not found!`)
                .setColor("RED");

            return message.channel.send(embeds);
        }
    }
};

module.exports.help = {
    name: "help",
    description: "This command is used for displaying all commands.",
    usage: "p!help",
    accessableby: "Members",
    aliases: ['?', 'commands', 'command'],
    cooldown: 60
};

【问题讨论】:

  • 您在哪里使用/分配您在help.js 中导出的命令的help 信息?如果message 是Message 的一个实例,那么message.content 是String,所以你的command。
  • 我有command.js 文件pastebin.com/0GXWj0Np

标签: javascript discord discord.js


【解决方案1】:

在您的message.js 内部,您可能会将command 与导出的命令对象(例如来自help.js)混淆。使用更好的变量命名,比如commandText,这样很明显,它是一个文本/字符串。

您的命令对象是cmd,您可以使用它通过导出的函数.run() 执行命令。 cmd 还包含 .help 属性,其中包含您想要的 .cooldown 属性。

这里看一个简单的例子,我将如何处理这个问题。

// ... Somewhere in the code (probably index.js or main.js) ...

client.commands = new Map();
client.aliases = new Map();

// ... Inside of your command handler (command.js) ...

// The command variable defined as a require of command file (for example help.js)

client.commands.set(command.help.name, command);
command.help.aliases.forEach(alias => {
    client.aliases.set(alias, command.help.name);
});

// ... Inside of your message handler (message.js) ...

let commandText = message.content.split(" ")[0].slice(prefixesdatabase.prefix.length);
if (!client.commands.has(commandText)) {
    commandText = client.aliases.get(commandText);
    if (!commandText) return;
}

const command = client.commands.get(commandText);
const cooldownAmount = (command.help.cooldown || 2) * 1000;

// ... Rest of your code ...

请注意,我们使用command.help.cooldown 而不是command.cooldown 或command.name 等。因为导出的对象本身没有这些属性。您使用module.exports.help = { ... }向导出的对象添加了属性.help,其中包含name和cooldown等。

要将我的解决方案实施到您的代码中,您需要替换以下内容(在 message.js 内):

// ... Rest of your code ...

if (!message.content.startsWith(prefixesdatabase.prefix)) return;

let commandText = message.content.split(" ")[0].slice(prefixesdatabase.prefix.length);
if (!client.commands.has(commandText)) {
    commandText = client.aliases.get(commandText);
    if (!commandText) return;
}

const command = client.commands.get(commandText);
const args = message.content.split(" ").slice(1);

if (!cooldowns.has(command.help.name)) {
    cooldowns.set(command.help.name, new Discord.Collection());
}

const now = Date.now();
const timestamps = cooldowns.get(command.help.name);
const cooldownAmount = (command.help.cooldown || 2) * 1000;
if (timestamps.has(message.author.id)) {
    const expirationTime = timestamps.get(message.author.id) + cooldownAmount;
    if (now < expirationTime) {
        const timeLeft = (expirationTime - now) / 1000;
        return message.reply(
            `Before using **${
                prefixesdatabase.prefix
            }${commandText}**, please wait for **${timeLeft.toFixed(
                1
            )} second for cooldowns!**`
        );
    }
}

timestamps.set(message.author.id, now);
setTimeout(() => timestamps.delete(message.author.id), cooldownAmount);

try {
    command.run(client, message, args);
} catch (e) {
    return console.log(`Invalid command: ${commandText}`);
} finally {
    console.log(
        `${message.author.username} using command ${prefixesdatabase.prefix}${commandText}`
    );
}

结果:

【讨论】:

  • 你能帮我应用它吗,我尝试应用我从代码块中看到的东西,但它不起作用。
  • 你可以将请求推送到我的github项目PruneBot。 message.js event/client/message.js 和 help.js command/info/help.js。
  • 我已经在 command.js 中有这个 command.help.aliases.forEach(alias =&gt; { client.aliases.set(alias, command.help.name); });
  • @Mashwishi 我已经更新了我的答案,你可以看看。 :)
【解决方案2】:

在 help.js 中,cooldown 内有 module.exports.help 而不是 module.exports

您要么将其取出到普通的module.exports,要么将 message.js 从

const cooldownAmount = (command.cooldown || 2) * 1000;

到

const cooldownAmount = (command.help.cooldown || 2) * 1000;

我所说的将module.exports.help 更改为module.exports 我的意思是:

help.js

const Discord = require("discord.js");

module.exports.run = async (client, message, args) => {
    const settings = require("../../config/settings.json");
    const prefixesdatabase = client.settings.ensure(message.guild.id, settings);

    const helpArray = message.content.split(" ");
    const helpArgs = helpArray.slice(1);

    if (!helpArgs[0]) {
        const embed = new Discord.MessageEmbed()
            .setColor("#b491c8")
            .setDescription(
                `**My prefix:** \`${prefixesdatabase.prefix}\` , Slash Commands list for \`/help\`\nClick [HERE](https://discord.com/api/oauth2/authorize?client_id=${client.user.id}&permissions=8&scope=bot%20applications.commands) to invite me to your server.`
            )
            .addField("**:gear: Basic**", "`help`, `ping`, `vote`, `uptime`, `setprefix`")
            .addField(
                "**?️ Moderation**",
                "`ban`, `clear`, `clearwarn`, `createchannel`, `createemoji`, `kick`, `lockchannel`, `mute`, `rename`, `slowmode`, `unban`, `unlockchannel`, `unmute`, `warn`, `warnings`"
            )           
            .addField(
                "**⚙ Utility**",
                "`aes256`, `avatar`, `channel`, `embed`, `roleinfo`, `reverse`, `setafk`, `snipe`, `stats`, `timer`, `translate`, `whois`, `weather`, `youtube`"
            )
            .addField(
                "**:magic_wand: Pruning**",
                "`urole`, `unorole`, `krole`, `knorole`, `fetch`"
            )           
            .addField(
                "**:tada: Giveaways**",
                "`start-giveaway`, `reroll`, `end-giveaway`"
            )
            .addField(
                "**:frame_photo: Images**",
                "`captcha`, `circle`, `delete`, `gay`, `changemymind`, `trigger`, `clyde`, `petpet`, `magik`, `iphonex`"
            )
            .addField(
                "**:musical_note: Music**",
                "`play`, `stop`, `skip`, `queue`, `autoplay`, `loop`, `volume`, `pause`, `resume`"
            )
            .addField(
                "**:partying_face: Fun**",
                "`8ball`, `cat`, `deaes256`, `kiss`, `meme`, `ngif`, `pat`, `poke`, `smug`, `thigh`, `tickle`"
            )           
            .addFields(
                { name: ':desktop: Github (Source Code)', value: 'https://github.com/mashwishi/PruneBot' },
                { name: ':revolving_hearts: Support the Developer:', value: 'https://ko-fi.com/mashwishi' }   
              )         
            .setTitle('Prune Bot | Commands')
            .setFooter(`©${nowyear} ${client.user.username} Created by Mashwishi.\nCommand requested by: ${message.author.username}#${message.author.discriminator}`, `https://i.imgur.com/ypxq7B9.png`)
            .setThumbnail('https://i.imgur.com/ypxq7B9.png')    
            .setAuthor('Join our Discord Server', 'https://i.imgur.com/hKeHeEy.gif', 'https://discord.io/LIMYAW');
        message.channel.send({ embed });
    }

    if (helpArgs[0]) {
        let command = helpArgs[0];

        if (client.commands.has(command)) {
            command = client.commands.get(command);
            let alia = command.aliases;
            if (command.aliases < 1) alia = "No aliases";

            const embed = new Discord.MessageEmbed()
                .setAuthor(
                    `Command: ${command.name}`,
                    client.user.displayAvatarURL()
                )
                .setDescription(
                    `
            **Description:**\n\`\`\`${
                            command.description ||
                            "There is no Description for this command."
                        }\`\`\`\n**Usage:**\n\`\`\`${
                        command.usage || "No Usage"
                    }\`\`\`\n**Permissions:**\n\`\`\`${
                        command.accessableby || "Members"
                    }\`\`\`\n**Cooldown (in seconds):**\n\`\`\`${
                        command.cooldown || "No Cooldown"
                    }\`\`\`\n**Aliases:**\n\`\`\`${alia}\`\`\``
                    
                )
                .setColor("#4a4b4d")
                .setFooter(
                    `© ${nowyear} ${client.user.username} | This command requested by ${message.author.username}#${message.author.discriminator}`
                );

            message.channel.send(embed);
        } else {
            const embeds = new Discord.MessageEmbed()
                .setDescription(`${emojis.cross} Command is not found!`)
                .setColor("RED");

            return message.channel.send(embeds);
        }
    }
};

module.exports = {
    name: "help",
    description: "This command is used for displaying all commands.",
    usage: "p!help",
    accessableby: "Members",
    aliases: ['?', 'commands', 'command'],
    cooldown: 60
};

【讨论】:

    猜你喜欢
    • 2021-05-01
    • 2021-10-04
    • 1970-01-01
    • 2021-07-08
    • 1970-01-01
    • 2020-11-18
    • 1970-01-01
    • 2022-11-12
    • 2021-06-17
    相关资源
    最近更新 更多