【问题标题】:Discord.js why is my help command not working?Discord.js 为什么我的帮助命令不起作用?
【发布时间】:2020-11-22 19:55:23
【问题描述】:

我按照 discord.js 文档的说明创建了一个动态帮助命令。当我使用 //help 时,它可以正常工作,但例如,//help ping 不是。我不确定为什么会发生这种情况,我已经尝试了很多方法来解决这个问题,但没有任何效果。有什么见解吗?代码如下:

index.js

// nodejs for filesystem
const fs = require("fs");
// require the discord.js module
const Discord = require("discord.js");
global.Discord = Discord;
// require canvas module for image manipulation
const Canvas = require("canvas");
// link to .json config file
const { prefix, token, adminRole } = require("./config.json");

// create a new discord client
const client = new Discord.Client();
client.commands = new Discord.Collection();
global.client = client;

const commandFiles = fs.readdirSync("./commands").filter(file => file.endsWith(".js"));

// ...
let target;
let targetName;
global.target = "000000000000000000";
global.targetName = "null";
global.adminRole = "738499487319720047";
// 737693607737163796
let hasRun = false;

for (const file of commandFiles) {
    const command = require(`./commands/${file}`);

    // set a new item in the Collection
    // with the key as the command name and the value as the exported module
    client.commands.set(command.name, command);
}

const cooldowns = new Discord.Collection();

// event triggers only once, right after bot logs in
client.once("ready", () => {
    console.log("Ready!");
    console.log(adminRole);
    client.user.setActivity("You", { type: "WATCHING" });
});

// for new member join - sends message including attachent
client.on("guildMemberAdd", async member => {
    const channel = member.guild.channels.cache.find(ch => ch.name === "welcome");
    global.channel = channel;
    if (!channel) return;

    const canvas = Canvas.createCanvas(700, 250);
    const ctx = canvas.getContext("2d");

    const background = await Canvas.loadImage("./wallpaper.jpg");
    ctx.drawImage(background, 0, 0, canvas.width, canvas.height);

    ctx.strokeStyle = "#74037b";
    ctx.strokeRect(0, 0, canvas.width, canvas.height);

    // Slightly smaller text placed above the member's display name
    ctx.font = "28px sans-serif";
    ctx.fillStyle = "#ffffff";
    ctx.fillText("Welcome to the server,", canvas.width / 2.5, canvas.height / 3.5);

    // Add an exclamation point here and below
    ctx.fillStyle = "#ffffff";
    ctx.fillText(`${member.displayName}!`, canvas.width / 2.5, canvas.height / 1.8);

    ctx.beginPath();
    ctx.arc(125, 125, 100, 0, Math.PI * 2, true);
    ctx.closePath();
    ctx.clip();

    const avatar = await Canvas.loadImage(member.user.displayAvatarURL({ format: "jpg" }));
    ctx.drawImage(avatar, 25, 25, 200, 200);

    const attachment = new Discord.MessageAttachment(canvas.toBuffer(), "welcome-image.png");

    channel.send(`Welcome to the server, ${member}!`, attachment);
});

// listening for messages.
client.on("message", message => {
    hasRun = false;

    // if (!message.content.startsWith(prefix) || message.author.bot) return;

    // log messages
    console.log(`<${message.author.tag}> ${message.content}`);

    // create an args var (const), that slices off the prefix entirely, removes the leftover whitespaces and then splits it into an array by spaces.
    const args = message.content.slice(prefix.length).trim().split(/ +/);
    global.args = args;

    // Create a command variable by calling args.shift(), which will take the first element in array and return it
    // while also removing it from the original array (so that you don't have the command name string inside the args array).
    const commandName = args.shift().toLowerCase();
    const command = client.commands.get(commandName) ||
        client.commands.find(cmd => cmd.aliases && cmd.aliases.includes(commandName));

    if (message.author.id === global.target) {

        // more code (excluded because its too long)
    }


    if (!command) return;

    if (command.guildOnly && message.channel.type !== "text") {
        return message.reply("I can't execute that command inside DMs!");
    }


    if (command.args && !args.length) {

        let reply = `You didn't provide any arguments, ${message.author}!`;

        if (command.usage) {
            reply += `\nThe proper usage would be: \`${prefix}${command.name} ${command.usage}\``;
        }

        return message.channel.send(reply);

    }

    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 || 3) * 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(`please wait ${timeLeft.toFixed(1)} more second(s) before reusing the \`${command.name}\` command.`);
        }
    }

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


    try {
        target, targetName = command.execute(message, command, args, target, targetName);
    }
    catch (error) {
        console.error(error);
        message.reply("there was an error trying to execute that command!");
    }

});

client.login(token);

help.js

const { prefix } = require("../config.json");

module.exports = {
    name: "help",
    description: "List all of my commands or info about a specific command.",
    aliases: ["commands"],
    usage: "[command name]",
    cooldown: 5,
    execute(message, args) {
        const data = [];
        const { commands } = message.client;

        if (!args.length) {
            data.push("Here's a list of all my commands:");
            data.push(commands.map(command => command.name).join(", "));
            data.push(`\nYou can send \`${prefix}help [command name]\` to get info on a specific command!`);

            return message.author.send(data, { split: true })
                .then(() => {
                    if (message.channel.type === "dm") return;
                    message.reply("I've sent you a DM with all my commands!");
                })
                .catch(error => {
                    console.error(`Could not send help DM to ${message.author.tag}.\n`, error);
                    message.reply("it seems like I can't DM you!");
                });
        }

        const name = args[0].toLowerCase();
        const command = commands.get(name) || commands.find(c => c.aliases && c.aliases.includes(name));

        if (!command) {
            return message.reply("that's not a valid command!");
        }

        data.push(`**Name:** ${command.name}`);

        if (command.aliases) data.push(`**Aliases:** ${command.aliases.join(", ")}`);
        if (command.description) data.push(`**Description:** ${command.description}`);
        if (command.usage) data.push(`**Usage:** ${prefix}${command.name} ${command.usage}`);

        data.push(`**Cooldown:** ${command.cooldown || 3} second(s)`);

        message.channel.send(data, { split: true });
    },
};

【问题讨论】:

    标签: javascript node.js discord.js


    【解决方案1】:

    我需要查看您的 ping 命令,并确定错误本身,但我认为您的问题出在您的 index.js 文件中。我为我的机器人遵循了相同的指南,但我没有遇到这个问题。在无法看到错误和 ping 命令的情况下,这里有一些地方可以帮助您进行故障排除:

    • 如果您的问题出在您的 index.js 文件中,我猜它可能出在您的 try、catch 语句中,可能是您传入参数的地方,也可能是帮助没有正确接收参数。例如:

    Function(arg1, arg2) 和 Function(arg1) 不是一回事。它们可能命名相同,并且共享一个参数,但是您传入的参数决定了执行哪个参数,因此如果您传入两个参数,那么它应该执行第一个函数,而忽略第二个函数。如果你只传入一个,那么它应该执行第二个函数,而忽略第一个。

    我在您的 try catch 中看到,您正在向命令传递大量参数,但帮助接受的参数与您尝试传递的参数不匹配,因此它可能看不到参数完全没有,这可以解释为什么它可以在没有参数的情况下工作,但是当你尝试传入一个参数时会失败。

    这是查看错误/结果可能会有所帮助的地方,因为您只是说它不能正常工作,您没有说它做了什么。如果命令执行时好像没有参数,尽管存在一个参数,那么这将算作“无法正常工作”,但如果该命令由于无法正确处理参数而给您一个错误,那么问题将是在你的 help.js 命令中

    • 如果您的问题出在您的 help.js 文件中,因为您说它无需参数即可工作,并且当您尝试获取特定命令的信息时会出现错误,那么问题将更接近代码的底部提供,因为这是收集和打印信息的地方。

    问题可能是它没有看到您正在谈论的命令,不知道您在请求它,或者它无法获取请求的信息,因为它不存在。

    • 如果您的问题出在 ping.js 文件中,可能是因为您的 help.js 工作正常,但 ping.js 可能没有 help 正在寻找的信息,例如,如果它没有没有名称,或者代码中的名称与文件的名称不匹配(我经常遇到这个问题......)。也可能是您在文件中缺少“}”,因为这也会破坏它。

    【讨论】:

    • args 是个愚蠢的问题,我在文件中使用它们的任何地方都将它们从 ags 更改为 global.args,它工作正常..
    【解决方案2】:

    添加 args = global.args;在我的帮助文件顶部的 modules.export 之后,它解决了这个问题。

    【讨论】:

      猜你喜欢
      • 2020-11-14
      • 2018-07-28
      • 2020-10-15
      • 2021-07-26
      • 2019-04-13
      • 2011-11-27
      • 2021-12-20
      • 2021-01-12
      • 1970-01-01
      相关资源
      最近更新 更多