【发布时间】:2021-06-06 22:42:16
【问题描述】:
我的 discord 机器人有一个命令处理程序。它可以很好地加载命令模块(并且控制台日志也表明了这一点),但是我无法让它执行第一个命令模块之外的命令。代码如下:
const Discord = require("discord.js");
const client = new Discord.Client();
client.commands = new Discord.Collection();
const prefix = "f$";
const fs = require("fs");
try {
const files = fs.readdirSync("./commands/");
let jsFiles = files.filter(filename => filename.split(".").pop() === "js");
for (const filename of jsFiles) {
let command = require(`./commands/${filename}`);
if (!command) return console.error(`Command file '${filename}' doesn't export an object.`);
client.commands.set(command.name, command);
console.log(`Loaded command: ${command.name}`);
}
} catch (err) {
console.error(`Error loading command: '${err}'`);
}
console.log("Finished loading\n");
client.on("ready", () => {
console.log("Client ready!");
});
client.on("message", async message => {
if (message.author.bot) return;
if (!message.content.startsWith(prefix)) return;
let args = message.content.slice(prefix.length).trim().split(/ +/g);
//console.log(args);
let cmdName = args.shift().toLowerCase();
for (const command of client.commands.values()) {
console.log(command.name);
console.log(cmdName);
console.log(command === cmdName);
if (command.name !== cmdName /*&& !command.aliases.includes(cmdName)*/) return;
try {
await command.executor(message, args, client);
} catch (err) {
console.error(`Error executing command ${command.name}: '$```{err.message}'`);
}
}
});
client.login(TOKEN).catch(err => console.log(`Failed to log in: ${err}`));
在每个命令模块中你都有这个位:
module.exports = {
name: "command",
description: "description of command",
aliases: [],
executor: async function (message, args, client) {
(我还没有为此做别名,所以别名行要么是空的,要么被删除。)
【问题讨论】:
标签: javascript node.js discord.js bots