索引文件
const Discord = require('discord.js');
const client = new Discord.Client();
client.commands = new Discord.Collection();
client.events = new Discord.Collection();
const prefix = '!'
['command_handler', 'event_handler'].forEach(handler =>{;
require(`./handlers/${handler}`)(client, discord)
})
client.login(`IREMOVEDTOKENFORTHIS`)
```
(imagine a folder that is named handlers and the stuff below is in it)
```
command_handlers : (below is the file contents)
const fs = require('fs');
const Discord = require('discord.js');
const client = new Discord.Client();
module.exports = (client, Discord) =>{
const command_files = fs.readdirSync(`./commands/`).filter(file => file.endsWith('.js'));
for(const file of command_files){
const command = require(`../commands/${file}`)
if(command.name){
client.commands.set(command.name, command)
} else{
continue;
}
}
}
事件处理程序
const fs = require('fs');
const Discord = require('discord.js');
const client = new Discord.Client();
module.exports= (client, Discord)=>{
const load_dir = (dir) =>{
const event_files = fs.readdirSync(`./events/${dir}`).filter(file => file.endsWith('.js'));
for (const file of event_files){
const event = require(`../events/${dir}/${file}`)
const event_name = file.split('.')[0]
client.on(event_name,event.bind(Discord, client));
}
}
['client', 'guild'].forEach(e => load_dir(e));
}
消息文件(在事件文件夹下-->公会)
const Discord = require('discord.js');
const client = new Discord.Client();
module.exports = (Discord, client, message, args) => {
const prefix = '!'
const cmd = args.shift().toLowerCase();
const command = client.commands.get(cmd);
if(command) commands.execute(client, message, args, Discord)
}
错误
['command_handler', 'event_handler'].forEach(handler =>{;
^
TypeError: Cannot read property 'forEach' of undefined
at Object.<anonymous> (E:SoftwareDiscord BotsBombBotindex.js:8:38)
at Module._compile (internal/modules/cjs/loader.js:1063:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
at internal/main/run_main_module.js:17:47
我的机器人名称是 Bombbot,我曾经 https://www.youtube.com/watch?v=Sihf7B8D4Y8 教程,这对以前的教程有所帮助,但这个教程如果有点混乱,我已经多次重写了代码。我也尝试删除整个函数,但这会使我的代码无用。
由于JavaScript的自动分号插入(ASI)功能,您遇到了这个问题。
const prefix = '!'
['command_handler', 'event_handler'].forEach(handler => {
require(`./handlers/${handler}`)(client, discord)
})
执行方式
const prefix = '!'['command_handler', 'event_handler'].forEach(handler => {
require(`./handlers/${handler}`)(client, discord)
})
'!'['command_handler', 'event_handler']
返回undefined
,因此返回错误。
在prefix
声明的末尾添加一个分号。
const prefix = '!';
和
['command_handler', 'event_handler'].forEach(handler =>{;
应该是
['command_handler', 'event_handler'].forEach(handler => {