I am making a discord bot in which i have created a config.json
file, where i am storing the channels id added by the add_channel command and i want to remove them though the rmvchannel command. But when i am running the below code, instead of only deleting the value spliced function is making the whole array blank.
const fs = require('fs');
let jsonInput = fs.readFileSync('config.json');
if (!jsonInput) return console.log("NO JSON FOUND");
let jsonData = JSON.parse(jsonInput);
var config = jsonData;
module.exports = {
data: new SlashCommandBuilder()
.setName("rmv_channel")
.setDescription("Remove Channel Command")
.addChannelOption((option) =>
option
.setName("channel")
.setDescription("the channel")
.setRequired(true)
),
async execute(interaction) {
let channel = await interaction.options.getChannel("channel").id;
let array = await config.channels;
let index = array.indexOf(String(channel));
array.splice(index, 1);
config.channels = await array;
var json = JSON.stringify(config);
fs.writeFileSync("config.json", json);
interaction.reply({ content: "Channel Removed !!" });
},
};
this is config.json file
{
"channels":[]
}
i tried this code by modifying it but nothing seems to work
2
Answers
I think the following code is not correct.
let array = await config.channels;
Perhaps, it may not work correctly.
The value of "array" is none.
You can check the value of "array", using "console.log" function.
Or, you can make the reference of the "config.channels", using slice() function.
I would probably do this a little differently.
I use the following data in the config file to recreate your use case.
I wrote this very basic logic to filter out the id you no longer want.
All I do is read the file, parse it to Json, filter the config property to anything that isn’t id1 and then write that to the file.
This is the result I get after running that simple example.
In theory you don’t need to add await to any of the operations you have done.