node.js - Discord.js 命令处理对我不起作用
问题描述
我创建了一个 Discord.js 机器人,我想用fs分隔每个命令,例如 ./commands/ping.js。它起作用了,但不知道为什么,一个小时后它就崩溃了。我对机器人没有任何兴趣,而且没有人可以访问代码-当然-。该机器人可以工作,并且没有错误消息。事件,如准备就绪和消息也可以正常工作,但是直接在文件中的命令不起作用。例如,它会提示“BOT 已启动”,但 ping.js 无法正常工作。
这是 index.js,但如果您需要其他任何调试,请发表评论!
const fs = require('fs');
const Discord = require('discord.js');
const { prefix, token } = require('./config.json');
const client = new Discord.Client();
client.commands = new Discord.Collection();
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
client.commands.set(command.name, command);
}
fs.readdir('./events/', (err, files) => {
files.forEach(file => {
const eventHandler = require(`./events/${file}`)
const eventName = file.split('.')[0]
client.on(eventName, (...args) => eventHandler(client, ...args))
})
})
client.login(token);
谢谢大家!~阿科斯
解决方案
健在这里,
这应该适合你:)。我试图留下一些评论,以便您可以理解代码,如果您对此代码有任何问题,请发表评论并编辑代码以使其正常工作
const fs = require('fs');
const Discord = require('discord.js');
const { prefix, token } = require('./config.json');
const client = new Discord.Client();
client.commands = new Discord.Collection();
fs.readdir("./commands/", (err, files) => {
// check for errors
if (err) console.log(err);
// get name of file
let jsfile = files.filter(f => f.split(".").pop() === "js");
// if it cannot find any commands
if (jsfile.length <= 0) {
console.log("Couldn't find commands.");
return;
}
// log the amount of files
console.log(`Loading ${jsfile.length} commands!`);
// load the command
jsfile.forEach((f, i) => {
// grab the module.exports from the file
let props = require(`./commands/${f}`);
console.log(`${i+1}: ${f} loaded!`);
client.commands.set(props.name, props);
});
});
// apparently this works so i'll leave it chief :)
fs.readdir('./events/', (err, files) => {
files.forEach(file => {
const eventHandler = require(`./events/${file}`)
const eventName = file.split('.')[0]
client.on(eventName, (...args) => eventHandler(client, ...args))
})
})
client.login(token);
好好过~不知道
推荐阅读
- wordpress - 隐藏 WordPress 页面标题的最佳方法
- javascript - 将 Vue.js 中一行的一些变量作为参数传递给 vue.js 方法并使用 axios 发送出去
- php - PHP中的一个班轮foreach
- java - 如何从 JSON 中提取日期,其中年、日和月作为单独的字段,格式为 yyyy-mm-dd
- javascript - 在 react.js 中异步导入 npm 模块
- webpack - “必须安装用于 webpack 的 CLI”以进行生产构建?
- simulation - AnyLogic如何将吸引子选择设置为自由和随机
- python - 如何在 Seaborn 热图中自定义颜色条的位置?
- flutter - 读取超时的 Firebase 消息注销通知失败
- java - 如何在电报中使用 InlineQueryResultDocument 和 GetFile?