Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
225 views
in Technique[技术] by (71.8m points)

javascript - how add data to json files with discord js

Hi I try to make sure that as soon as my discord bot joins a server it writes the es of the server in the JSON file and then the first channel of the discord server below but it does not work.

client.on("guildCreate", (guild) => { // This event triggers when the bot joins a guild. 
    let rawdata = fs.readFileSync('guilds.json');
    let guilds = JSON.parse(rawdata);
    console.log(`Joined new guild: ${guild.name}`);
    var chx = guild.channels.cache.filter(chx => chx.type === "text").find(x => x.position === 0);
    client.newGuild [chx.guild.id] = {
        MemberAdd: chx.id,
        MemberRemove: chx.id
    }
    fs.writeFile("./guilds.json", JSON.stringify (client.newGuild, null, 4), err => {
        if (err) throw err;
        console.log('Server succefull add')
    })
});

I get this error enter image description here

I try to do this:

{
    "801502579829112852":{
       "MemberAdd":"801514313340289034",
       "MemberRemove":"802125586923257886"
    },
    "802163006698946570":{
       "MemberAdd":"802163007173951521",
       "MemberRemove":"802163007173951521"
    }
 }

Thank you for your help !

question from:https://stackoverflow.com/questions/65865661/how-add-data-to-json-files-with-discord-js

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Replace your code with this one :

    guilds.newGuild [chx.guild.id] = {
        MemberAdd: chx.id,
        MemberRemove: chx.id
    }
    fs.writeFile("./guilds.json", JSON.stringify (guilds, null, 2), err => {
        if (err) throw err;
        console.log('Server successfully add')
    })

plus replace your guilds.json with :

{"newGuild":{}}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...