【问题标题】:How to have collections populated in a module for use inside events/commands如何在模块中填充集合以在事件/命令中使用
【发布时间】:2019-09-28 00:04:28
【问题描述】:

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

我已经尝试在事件中导入模块,以及其他有意义的选项。

这是我模块中的代码

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

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

【问题讨论】:

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


    【解决方案1】:

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

    模块文件

    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');
    

    【讨论】:

    • 完全按预期工作,很好的解释,谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-10
    • 2013-01-12
    • 1970-01-01
    相关资源
    最近更新 更多