javascript - 在 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
命令,这将允许我添加一个。
我试过这个指南,没有运气。
解决方案
您可能想要做的是存储一个 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
}
推荐阅读
- composer-php - Drupal Composer 需求无法解析为一组可安装的包
- python - sudo -H pip install 和 pip --user install 的区别
- c# - ASP.NET Core 2.1 Web API - ConfigurationManager.ConnectionStrings 返回 null
- swift - Eureka - DateRow 加载日期而不更改其当前值
- java - 从 Oracle JDK 迁移到 OpenJDK
- python - 嵌套的 dict 键被覆盖
- javascript - 本地存储中 >100Mb 的数据
- javascript - 如果有新请求则取消请求(承诺)
- git - Git合并忽略空行
- android - 如何在使用导航架构时将数据传递给第一个片段?