简体   繁体   English

Discord.js 为什么我的帮助命令不起作用?

[英]Discord.js why is my help command not working?

I have created a dynamic help command following the instructions on the documantation of discord.js.我按照 discord.js 的文档说明创建了一个动态帮助命令。 When I'm using //help, it's working properly, but //help ping, for example, is not.I'm not sure why this is happening, I've tried many things to fix that and nothing has worked.当我使用 //help 时,它可以正常工作,但例如,//help ping 不是。我不确定为什么会发生这种情况,我已经尝试了很多方法来解决这个问题,但没有任何效果。 Any insight?有什么见解吗? code below:下面的代码:

index.js 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帮助.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 });
    },
};

I'd need to see your ping command, and the error itself to know for sure, but I think your problem is in your index.js file.我需要查看您的 ping 命令,并确定错误本身,但我认为您的问题出在您的 index.js 文件中。 I followed the same guide for my bots, and I haven't run into this issue.我为我的机器人遵循了相同的指南,但我没有遇到这个问题。 Without being able to see the error and the ping command, here are some places to look to help your troubleshooting:在无法看到错误和 ping 命令的情况下,这里有一些地方可以帮助您进行故障排除:

  • If your problem is in your index.js file, my guess is it'll be in your try, catch statement, possibly where you're passing in arguments, it could be that help isn't receiving the arguments properly.如果您的问题出在您的 index.js 文件中,我猜它会出现在您的 try、catch 语句中,可能是您传入 arguments 的地方,这可能是帮助没有正确接收 arguments。 For example:例如:

Function(arg1, arg2) and Function(arg1) aren't the same thing. Function(arg1, arg2) 和 Function(arg1) 不是一回事。 They may be named the same, and share an argument, but the arguments you pass in determine which one is executed, so if you pass in two arguments, then it should execute the first function, and ignore the second.它们可能命名相同,并且共享一个参数,但是您传入的 arguments 确定执行哪个,因此如果您传入两个 arguments,那么它应该执行第一个 function,而忽略第二个。 If you pass in only one, then it should execute the second function, and ignore the first.如果只传入一个,那么它应该执行第二个 function,而忽略第一个。

I see in your try catch, that you're passing in a ton of arguments to the command, but the arguments help accepts don't match what you're trying to pass in, therefore it may not be seeing the arguments at all, which could explain why it works with no arguments, but fails when you try to pass one in.我在您的 try catch 中看到,您正在将大量 arguments 传递给命令,但 arguments 帮助接受与您尝试传递的内容不匹配,因此它可能根本看不到 ZDBC11CAA5BDA99F77E6FB4DAD882E,这可以解释为什么它在没有 arguments 的情况下工作,但是当你尝试传递一个时失败。

This is where seeing the error/result could help, as you only said it doesn't work properly, you didn't say what it did.这是查看错误/结果可能会有所帮助的地方,因为您只是说它不能正常工作,您没有说它做了什么。 If the command executed as if there was no arguments despite one existing, then that would count as "not working properly", but if the command gave you an error due to it not being able to process the parameters properly, then the issue would be in your help.js command如果执行的命令好像没有 arguments 尽管存在一个,那么这将被视为“无法正常工作”,但如果该命令由于无法正确处理参数而给您一个错误,那么问题将是在你的 help.js 命令中

  • If your problem is in your help.js file, since you said it works with no arguments, and the error occurs when you try to get info on a specific command, then the problem will be closer to the bottom of the code provided, as that's where the info is gathered, and printed.如果您的问题在您的 help.js 文件中,因为您说它在没有 arguments 的情况下工作,并且当您尝试获取特定命令的信息时发生错误,那么问题将更接近提供的代码的底部,如这就是收集和打印信息的地方。

The issue may be that it's not seeing which command you're talking about, doesn't know you're asking for it, or it can't get the requested information because it doesn't exist.问题可能是它没有看到您正在谈论的命令,不知道您在请求它,或者它无法获取请求的信息,因为它不存在。

  • If your problem is in your ping.js file, it could be because you're help.js is working fine, but ping.js might not have the information that help is looking for, for instance, if it didn't have a name, or the name in the code doesn't match the name of the file (i've run into that issue a lot...).如果您的问题出在您的 ping.js 文件中,可能是因为您的 help.js 工作正常,但 ping.js 可能没有 help 正在寻找的信息,例如,如果它没有名称,或者代码中的名称与文件的名称不匹配(我经常遇到这个问题......)。 It could also be that you're missing a "}" in the file, as that would wreck it as well.也可能是您在文件中缺少“}”,因为这也会破坏它。

Added args = global.args;添加 args = global.args; in the top of my help file, after the modules.export, it fixed the issue.在我的帮助文件顶部的 modules.export 之后,它解决了这个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM