skip to Main Content

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


  1. 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.

    Login or Signup to reply.
  2. I would probably do this a little differently.
    I use the following data in the config file to recreate your use case.

    {"config":["id1","id2","id3","id4","id5","id6","id7","id8","id9"]}
    

    I wrote this very basic logic to filter out the id you no longer want.

    const fs = require('fs');
    
    
    let jsonFile = fs.readFileSync('config.json');
    let data = JSON.parse(jsonFile);
    
    const newData = {config: data.config.filter((e) => e !== 'id1')};
    
    fs.writeFileSync("config.json", JSON.stringify(newData));
    

    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.

    {"config":["id2","id3","id4","id5","id6","id7","id8","id9"]}
    

    In theory you don’t need to add await to any of the operations you have done.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search