【问题标题】:Store multiple channel IDs in a JSON file在 JSON 文件中存储多个频道 ID
【发布时间】:2020-09-03 05:24:29
【问题描述】:

我正在使用 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 命令,这将允许我添加一个。

我尝试了this 指南,但没有成功。

【问题讨论】:

    标签: javascript json discord discord.js


    【解决方案1】:

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

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

    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
    }
    

    【讨论】:

    • 好的,我相信我添加的正确。所以,在我添加频道的命令中,我只输入addChannelID('channel_id')。假设这是正确的,在运行我得到的代码时:TypeError: Cannot read property 'push' of undefined
    • 嗯,您必须将'channel_id' 替换为频道的实际ID,例如message.channel.id。此外,您必须确保 channelIDs 在您正在使用的文件中正确声明,并且您的 JSON 文件具有设置为空数组的相应属性
    猜你喜欢
    • 2021-09-18
    • 2012-11-27
    • 1970-01-01
    • 2017-06-21
    • 2019-05-25
    • 2016-01-17
    • 2011-02-27
    • 1970-01-01
    • 2018-02-01
    相关资源
    最近更新 更多