我已经按照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 });
},
};
答案 0 :(得分:1)
我需要查看您的ping命令和错误本身才能确定,但是我认为您的问题出在您的index.js文件中。我遵循了与我的机器人相同的指南,但还没有遇到这个问题。在看不到错误和ping命令的情况下,以下是一些可以帮助您进行故障排除的地方:
Function(arg1,arg2)和Function(arg1)不同。它们的名称可能相同,并且共享一个参数,但是您传入的参数确定执行了哪个参数,因此,如果传入两个参数,则它应该执行第一个函数,而忽略第二个函数。如果只传递一个,则它应该执行第二个函数,而忽略第一个。
我在您的try catch中看到,您正在向该命令传递大量参数,但是参数帮助接受的内容与您要传递的内容不匹配,因此可能看不到参数完全可以解释为什么它不使用任何参数,但是当您尝试传入一个参数时失败。
在这里看到错误/结果可能会有所帮助,因为您只说它无法正常工作,而您没有说出它是怎么做的。如果命令执行后好像没有参数就好像没有参数执行,那将算作“无法正常工作”,但是如果该命令由于无法正确处理参数而给您带来错误,那么问题将是在您的help.js命令中
问题可能是它没有看到您正在谈论的命令,不知道您要的命令,或者因为它不存在而无法获取所请求的信息。
答案 1 :(得分:0)
添加的args = global.args;在我的帮助文件顶部,在modules.export之后,它解决了该问题。