javascript - 如何在模块中填充集合以在事件/命令内使用

标签 javascript node.js visual-studio-code discord discord.js

我知道要填充诸如公会和 channel 之类的集合,机器人必须已经登录,即它可以在命令文件以及内部事件中使用。我所拥有的是一个模块,它将在我的控制不一致服务器中显示我的日志,并且我希望能够在我的事件和命令中引用该模块。

我尝试导入事件内部的模块,以及其他有意义的选项。

这是我的模块内的代码

const Discord = require('discord.js')
const bot = new Discord.Client()
const CC = '../settings/control-center.json'
const CCFile = require(CC)
const GUILD = bot.guilds.get(CCFile.GUILD)
const STARTUP = bot.channels.get(CCFile.STARTUP)
const INFO = bot.channels.get(CCFile.INFO)
const ERRORS = bot.channels.get(CCFile.ERRORS)
const RESTART = bot.channels.get(CCFile.RESTART)
const EXECUTABLES = bot.channels.get(CCFile.EXECUTABLES)

class Control {
    /**
     * Implement control center logging
     * @param {string} message - What to send to the startup channel
     * @return {string} The final product being sent to the startup channel
     */
    STARTUP(message) {
        return STARTUP.send(`${message}`)
    }
}

module.exports = Control

我希望能够全局使用这个模块/里面的函数,这样我的代码可以更加紧凑。那么我怎样才能拥有它,以便仅在机器人登录后加载此代码?

最佳答案

在您的模块代码中,您正在创建一个新的 Discord 客户端实例,并且从不调用登录方法。 更好的方法是在您的方法中传递机器人对象

模块文件

const CC = '../settings/control-center.json';
const CCFile = require(CC);
const GUILD = CCFile.GUILD;
const STARTUP = CCFile.STARTUP;
const INFO = CCFile.INFO;
const ERRORS = CCFile.ERRORS;
const RESTART = CCFile.RESTART;
const EXECUTABLES = CCFile.EXECUTABLES;

class Control {

  startup(bot, message) {
    return bot.channels.get(STARTUP).send(message);
  }

}

module.exports = Control

应用程序文件

// Use the bot here
const Discord = require('discord.js')
const bot = new Discord.Client() 
const control = require('path/to/control.js');

[...]

// to send a message when ready, try something like this
bot.on('ready', () => {
  control.startup(bot, 'bot is ready');
});

// don't forget to login
bot.login('YOUR-TOKEN-HERE');

关于javascript - 如何在模块中填充集合以在事件/命令内使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56071502/

相关文章:

javascript - 使用 jQuery 进行多级 JSON

javascript - 是否可以调用 Google API 并获取 map 图像并将图像保存在某个地方

node.js - Amazon S3 - 无法加载资源 : the server responded with a status of 403 (Forbidden)

python - 看不到输出,只能在终端

在 Visual Studio Code 中调试?

javascript - 如何使用正则表达式根据字符串过滤数组项?

javascript - 如何在 macOs 上的端口 21 上运行 ftp-server

javascript - 如何在 diff 文本区域中显示 php 获取的值?

javascript - 我的 'for' 循环未在 JavaScript 中运行(使用 Node.js 运行 JavaScript 文件)

visual-studio-code - Visual Studio Code 任务正在将工作目录添加到命令中