首页 > 解决方案 > 在 JSON 文件中存储多个频道 ID

问题描述

我正在使用 Discord.js 制作一个机器人,它只需要跟踪某个频道中的消息,我目前对此进行了硬编码以用于测试目的。

var { channelID } = require(`./config.json`);

bot.on("message", async (message) => {
    const args = message.content.split(/ +/g);
    if (message.channel.id === channelID) {
        // ...
    }
});

我想让它在一个 JSON 文件中存储多个 ID 并有一个[p]setchannel命令,这将允许我添加一个。

我试过这个指南,没有运气。

标签: javascriptjsondiscorddiscord.js

解决方案


您可能想要做的是存储一个 ID 数组,以便您以后可以检索它们。

您应该channelIDs将 JSON 文件中的一个属性设置为一个空数组。在您的代码中,您可以像这样获取它:

const { channelIDs } = require('./config.json') // Now it's an empty array: []

当你想更新这个数组时,你应该先更新你的本地数组,然后你可以更新配置文件:要做到这一点,你可以fs.writeFileSync()JSON.stringify().

const fs = require('fs')

function addChannelID(id) {
  channelIDs.push(id) // Push the new ID to the array

  let newConfigObj = { // Create the new object...
    ...require('./config.json'), // ...by taking all the current values...
    channelIDs // ...and updating channelIDs
  }

  // Create the new string for the file so that it's not too difficult to read
  let newFileString = JSON.stringify(newConfigObj, null, 2) 

  fs.writeFileSync('./config.json', newFileString) // Update the file
}

设置此功能后,您可以随时添加一个新 ID,只需调用addChannelID('channel_id').
要检查是否应考虑消息来自的通道,您可以使用以下命令:

if (channelIDs.includes(message.channel.id)) {
  // OK
}

推荐阅读