启动时加载机器人功能

时间:2021-06-24 18:53:30

标签: javascript object discord.js

我希望能够从我的 Discord Bot 上的任何位置访问一些功能,并且我已经尝试了几个小时来导出所有功能,但我一直在思考如何真正为它们提供名字。

    async loadFunctions() {
        return glob(`${this.directory}Functions/*.js`).then(functions => { // Returns array of all files
            functions.forEach((m) => {
                const { name } = path.parse(m); // Takes the name of each file
                const File = require(m); // This takes the class from the file
                this.client.functions./* the 'name' variable */ = new File(this); // Create the function
            });
        });
    }

我相信我的代码是错误的,不会按照我想要的方式工作,但我不确定我应该做什么。 如果我只是this.client.functions = new File(this) 然后它将起作用,并且我可以访问该函数并按预期运行。但是,由于它在 forEach 中,它循环的每种类型都会覆盖名称,因为它是相同的,我认为它会类似于 this.client.functions[name] 但这也是错误的。任何帮助表示赞赏!

1 个答案:

答案 0 :(得分:0)

this.client.functions[name] 应该可以工作。您收到 TypeError: Cannot set property 'pagination' of undefined 的原因是 this.client.functions 未定义。在尝试向其添加新属性之前,您需要确保将其初始化为空对象 ({}):

async loadFunctions() {
  this.client.functions = {};

  return glob(`${this.directory}Functions/*.js`).then((functions) => {
    functions.forEach((m) => {
      const { name } = path.parse(m);
      const File = require(m);
      this.client.functions[name] = new File(this);
    });
  });
}
相关问题