【问题标题】:How can I call Discord.js functions from a lib.js file into index.js?如何将 lib.js 文件中的 Discord.js 函数调用到 index.js 中?
【发布时间】:2022-01-21 17:21:32
【问题描述】:

我正在尝试创建一个包含我的函数的单独类,这样 index.js 就不会变得混乱。我遇到的问题是我的新 lib.js 文件无法与 discord.js 一起使用。我计划添加多个更复杂的功能,因此将lib.start() 替换为msg.channel.send('Game Started') 不会解决我的问题。有没有办法让 discord.js 命令在 lib.js 中工作,以便我可以将它们调用到 index.js 中?

index.js

const Discord = require('discord.js')
const client = new Discord.Client();

const lib = require("./classes/lib");

const { token } = require('./Data/config.json');

client.on('ready', () => {
  console.log(`Logged in as ${client.user.tag}!`);
})

client.on('message', async msg => {
  if(msg.content.startsWith("m!")) {
    const command = msg.content.substring(2)

    switch(command) {
      
      //Calling 'start()'
      case "start game" : lib.start(); break;
    
      default: msg.channel.send('Unknown Command');
    
    }
  } 
})

client.login(token)

lib.js

function start() {
    msg.channel.send('Game Started');   //Trying to get this to work
}

module.exports = {start};

【问题讨论】:

    标签: javascript node.js function discord discord.js


    【解决方案1】:

    在函数中传入对消息的引用

    client.on('message', async msg => {
      if(msg.content.startsWith("m!")) {
        const command = msg.content.substring(2)
    
        switch(command) {
          
          //Calling 'start()'
          case "start game" : lib.start(msg); break;
        
          default: msg.channel.send('Unknown Command');
        
        }
      } 
    })
    
    function start(msg) {
        msg.channel.send('Game Started');
    }
    
    module.exports = {start};
    

    您可能还想创建start 和其他函数async,只要记住它们被调用时await

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-08-18
      • 1970-01-01
      • 2020-12-03
      • 1970-01-01
      • 1970-01-01
      • 2022-10-14
      • 2020-02-15
      • 1970-01-01
      相关资源
      最近更新 更多