是否可以将 Discord 斜杠命令用作模块?

时间:2021-07-30 15:03:29

标签: node.js discord.js

首先,我是 node.js 和 discord.js 的初学者。

我目前正在开发我自己的 discord bot 以获取乐趣,我想知道是否可以“存储”斜杠命令的数据。这是我的意思的一个例子:

    const response = new Discord.MessageEmbed()
      .properties()
      .properties()
      etc...
    
    module.exports = () {
      const data = {
        data: {
          type: 4, // I don't know what type to use  for embed message so please correct me if I'm wrong
          data: {
            content: response
          }
        }
      }
    }

这是否可以将嵌入的消息数据“存储”在 rules.js 中并像这样在 main.js 中使用它:

    const rules = require('rules.js') //the file would be in a "commands" folder but I'm keeping this simple

    client.ws.on('INTERACTION_CREATE', async (interaction) => {
      const command = interaction.data.name.toLowerCase()
      if (command === 'rules') {
        client.api.interactions(interaction.id, interaction.token).callback.post(data) // or post(rules.data) ??? again, I'm a beginner
      }
    })

2 个答案:

答案 0 :(得分:0)

你应该尝试创建一个函数而不是保存和导出模块,因为像模块一样使用实例类是危险的,因为它会导致内存问题,所以为此编写一个工厂

答案 1 :(得分:0)

您可以尝试以下方法:

//file name: slashCmd.js
const Discord = require('discord.js')
module.exports = async function(client, cmdObj) {
     client.api.applications(client.user.id).commands.post(cmdObj)
}

您可以根据需要自定义函数,但您可以在 index.js 中执行此操作

const slashCmd = require('./slashCmd.js');
const client = new Discord.Client()
client.on('ready', () => {
    slashCmd(client, {
        name: 'cmdName',
        description: 'cmdDesc'
    })
})