簡體   English   中英

Discord.js 為什么我的幫助命令不起作用?

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

我按照 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);

幫助.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 });
    },
};

我需要查看您的 ping 命令,並確定錯誤本身,但我認為您的問題出在您的 index.js 文件中。 我為我的機器人遵循了相同的指南,但我沒有遇到這個問題。 在無法看到錯誤和 ping 命令的情況下,這里有一些地方可以幫助您進行故障排除:

  • 如果您的問題出在您的 index.js 文件中,我猜它會出現在您的 try、catch 語句中,可能是您傳入 arguments 的地方,這可能是幫助沒有正確接收 arguments。 例如:

Function(arg1, arg2) 和 Function(arg1) 不是一回事。 它們可能命名相同,並且共享一個參數,但是您傳入的 arguments 確定執行哪個,因此如果您傳入兩個 arguments,那么它應該執行第一個 function,而忽略第二個。 如果只傳入一個,那么它應該執行第二個 function,而忽略第一個。

我在您的 try catch 中看到,您正在將大量 arguments 傳遞給命令,但 arguments 幫助接受與您嘗試傳遞的內容不匹配,因此它可能根本看不到 ZDBC11CAA5BDA99F77E6FB4DAD882E,這可以解釋為什么它在沒有 arguments 的情況下工作,但是當你嘗試傳遞一個時失敗。

這是查看錯誤/結果可能會有所幫助的地方,因為您只是說它不能正常工作,您沒有說它做了什么。 如果執行的命令好像沒有 arguments 盡管存在一個,那么這將被視為“無法正常工作”,但如果該命令由於無法正確處理參數而給您一個錯誤,那么問題將是在你的 help.js 命令中

  • 如果您的問題在您的 help.js 文件中,因為您說它在沒有 arguments 的情況下工作,並且當您嘗試獲取特定命令的信息時發生錯誤,那么問題將更接近提供的代碼的底部,如這就是收集和打印信息的地方。

問題可能是它沒有看到您正在談論的命令,不知道您在請求它,或者它無法獲取請求的信息,因為它不存在。

  • 如果您的問題出在您的 ping.js 文件中,可能是因為您的 help.js 工作正常,但 ping.js 可能沒有 help 正在尋找的信息,例如,如果它沒有名稱,或者代碼中的名稱與文件的名稱不匹配(我經常遇到這個問題......)。 也可能是您在文件中缺少“}”,因為這也會破壞它。

添加 args = global.args; 在我的幫助文件頂部的 modules.export 之后,它解決了這個問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM