Discord. js почему моя команда помощи не работает? - PullRequest
0 голосов
/ 02 августа 2020

Я создал команду Dynami c help, следуя инструкциям по документированию разногласий. 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 });
    },
};

Ответы [ 2 ]

0 голосов
/ 03 августа 2020

Добавлен args = global.args; в верхней части моего файла справки, после modules.export, проблема была устранена.

0 голосов
/ 02 августа 2020

Мне нужно увидеть вашу команду ping и саму ошибку, чтобы знать наверняка, но я думаю, что ваша проблема в вашем файле index. js. Я следовал тому же руководству для своих ботов, и я не сталкивался с этой проблемой. Не имея возможности увидеть ошибку и команду ping, вот несколько мест, которые помогут вам в устранении неполадок:

  • Если ваша проблема в вашем файле index. js, я предполагаю, что это ' будет в вашем операторе try, catch, возможно, где вы передаете аргументы, возможно, справка не получает аргументы должным образом. Например:

Функция (arg1, arg2) и Function (arg1) не одно и то же. Они могут называться одинаково и иметь общий аргумент, но передаваемые вами аргументы определяют, какой из них выполняется, поэтому, если вы передадите два аргумента, он должен выполнить первую функцию и проигнорировать второй. Если вы передадите только одну, тогда она должна выполнить вторую функцию и проигнорировать первую.

Я вижу в вашем try catch, что вы передаете команде тонну аргументов, но аргументы help accept не соответствует тому, что вы пытаетесь передать, поэтому он может вообще не видеть аргументы, что могло бы объяснить, почему он работает без аргументов, но терпит неудачу, когда вы пытаетесь передать один.

Здесь может помочь просмотр ошибки / результата, поскольку вы только сказали, что она не работает должным образом, вы не сказали, что она сделала. Если команда выполняется так, как если бы не было аргументов, несмотря на наличие одного из них, это будет считаться «некорректно работающим», но если команда выдала вам ошибку из-за того, что она не смогла правильно обработать параметры, тогда проблема будет в вашей помощи. js команда

  • Если ваша проблема в вашей помощи. js файл, поскольку вы сказали, что он работает без аргументов, и ошибка возникает, когда вы пытаетесь получить информацию о a specifici c, тогда проблема будет ближе к нижней части предоставленного кода, так как именно там информация собирается и печатается.

Проблема может заключаться в том, что он не видит, какой команда, о которой вы говорите, не знает, что вы ее запрашиваете, или она не может получить запрошенную информацию, потому что она не существует.

  • Если ваша проблема в вашем пинге . js, это может быть потому, что вы помогли. js работает нормально, но ping. js может не иметь информации, которую ищет справка, например, если у него не было имени e, или имя в коде не соответствует имени файла (я часто сталкивался с этой проблемой ...). Также может быть, что вам не хватает символа "}" в файле, так как это тоже приведет к его повреждению.
...