如何在Discord机器人主脚本中调用functions文件夹文件并传入client?
问题解决方法
1. 核心错误原因
报错require(...) is not a function是因为你functions文件夹里的处理器文件没有导出一个可接收client参数的函数,主脚本直接调用require()的返回值自然会失败。
2. 修正处理器文件的导出格式
所有处理器文件必须导出一个以client为参数的函数,示例如下:
命令处理器示例(functions/commands/loadCommands.js)
const fs = require('fs'); const path = require('path'); module.exports = (client) => { // 加载commands文件夹下的所有命令 const commandRoot = path.join(__dirname, '../../commands'); const commandFolders = fs.readdirSync(commandRoot); for (const folder of commandFolders) { const folderPath = path.join(commandRoot, folder); const commandFiles = fs.readdirSync(folderPath).filter(file => file.endsWith('.js')); for (const file of commandFiles) { const command = require(path.join(folderPath, file)); client.commands.set(command.data.name, command); } } };
事件处理器示例(functions/events/loadEvents.js)
const fs = require('fs'); const path = require('path'); module.exports = (client) => { // 加载events文件夹下的所有事件 const eventRoot = path.join(__dirname, '../../events'); const eventFolders = fs.readdirSync(eventRoot); for (const folder of eventFolders) { const folderPath = path.join(eventRoot, folder); const eventFiles = fs.readdirSync(folderPath).filter(file => file.endsWith('.js')); for (const file of eventFiles) { const event = require(path.join(folderPath, file)); if (event.once) { client.once(event.name, (...args) => event.execute(...args, client)); } else { client.on(event.name, (...args) => event.execute(...args, client)); } } } };
3. 主脚本优化(可选,提升健壮性)
用path模块拼接绝对路径,避免相对路径出错,同时增加函数类型检查:
const fs = require('fs'); const path = require('path'); // 遍历functions文件夹加载处理器 const functionsDir = path.join(__dirname, 'functions'); const functionFolders = fs.readdirSync(functionsDir); for (const folder of functionFolders) { const folderPath = path.join(functionsDir, folder); const functionFiles = fs.readdirSync(folderPath).filter(file => file.endsWith('.js')); for (const file of functionFiles) { const filePath = path.join(folderPath, file); const handler = require(filePath); // 仅执行导出为函数的文件,避免报错 if (typeof handler === 'function') { handler(client); } else { console.warn(`跳过非函数导出文件:${filePath}`); } } }
4. ES模块替代方案(若使用"type": "module")
如果你的项目用ES模块(package.json中设置"type": "module"),可以这样实现:
主脚本
import fs from 'fs/promises'; import path from 'path'; async function loadFunctions(client) { const functionsDir = path.join(process.cwd(), 'functions'); const functionFolders = await fs.readdir(functionsDir); for (const folder of functionFolders) { const folderPath = path.join(functionsDir, folder); const functionFiles = (await fs.readdir(folderPath)).filter(file => file.endsWith('.js')); for (const file of functionFiles) { const filePath = path.join(folderPath, file); const { default: handler } = await import(filePath); if (typeof handler === 'function') { handler(client); } } } } // 在client初始化完成后调用 await loadFunctions(client);
处理器文件示例
export default (client) => { // 处理器逻辑代码 };
内容的提问来源于stack exchange,提问作者Kyle Kilgore
相关产品推荐
相关产品推荐

