最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - Writing JSON File with Discord.js - Stack Overflow

matteradmin10PV0评论

Im trying to develop a little warn system for my Discord Bot. If someone types !warn @mention Reason, it should store the data in a JSON File. It works, but only with one User in one Guild. What I want is, that the JSON File looks like this:

     {
        "superniceguildid": 
          {
            "member": "636302212787601408",
            "warns": 3
        },
         {
            "meber": "7837439745387549"
            "warns": 1
       }
}

Now only this exists:

{
    "627818561947041816": {
        "guild": "636302212787601408",
        "warns": 3
    },
   
}

How can I do it, that the File is generating like above? My current code is this:

module.exports = {
    name: 'warn',
    description: "test",
    execute(message, args){
        const { Client, MessageEmbed } = require("discord.js")
        const client = new Client()

        const fs = require("fs")
        const ms = require("ms")
        warns = JSON.parse(fs.readFileSync("./warns.json", "utf8"))
        client.servers = require ("./servers.json")
        let guild = client.servers[message.guild.id].message
        
        
/*Embeds*/
const oops = new MessageEmbed()
        .setTitle("Error")
        .setColor("RED")
        .setDescription("You cant warn a member. Please ask a Moderator")
        .setAuthor("MemeBot", "this is a link")

const Mod = new MessageEmbed()
        .setTitle("Error")
        .setColor("RED")
        .setDescription("You cant warn a Moderator.")
        .setAuthor("MemeBot", "linkhere xD")
/**Commands */
let wUser = message.mentions.users.first() || message.guild.members.cache.fetch(`${args[0]}`)
if (!wUser) return message.channel.send("Are you sure, that this was a User? I think it wasn't one...")
let wReason = args.join(" ").slice(27)
if (!wReason) return message.channel.send("Please tell me, why you want to warn this person. Because, you know, it's a warn :D");
if(!message.member.hasPermission("KICK_MEMBERS")) return message.channel.send(oops)
if(wUser.hasPermission("KICK_MEMBERS")) return message.channel.send(Mod)


if(!warns[message.guild.id]) warns[message.guild.id] = {
    user: wUser.id,
    warns: 0
}


warns[wUser.id].warns++



fs.writeFile("./warns.json", JSON.stringify(warns, null, 4), err => {
    if(err) console.log(err)
});

let warnEmbed = new MessageEmbed()
.setTitle("Warned")
.setColor("YELLOW")
.addField("Warned User", `${wUser}`)
.addField("Moderator", `${message.author.id}`)
.addField("Reason", `${wReason}`)
.addField("Number of Warnings", warns[wUser.id].warns)
.addField("Warned at", `${message.createdAt}`)

let warnonEmbed = new MessageEmbed()
.setTitle("Warned")
.setColor("YELLOW")
.addField("Warned on", `${message.guild.name}`)
.addField("Moderator", `${message.author}`)
.addField("Reason", `${wReason}`)
.addField("Warned at", `${message.createdAt}`)
        
let logchannel = message.guild.channels.cache.find(c => c.id === 'id');
if(!logchannel) return 

wUser.send(warnonEmbed)
logchannel.send(warnEmbed)

}
}

Im trying to develop a little warn system for my Discord Bot. If someone types !warn @mention Reason, it should store the data in a JSON File. It works, but only with one User in one Guild. What I want is, that the JSON File looks like this:

     {
        "superniceguildid": 
          {
            "member": "636302212787601408",
            "warns": 3
        },
         {
            "meber": "7837439745387549"
            "warns": 1
       }
}

Now only this exists:

{
    "627818561947041816": {
        "guild": "636302212787601408",
        "warns": 3
    },
   
}

How can I do it, that the File is generating like above? My current code is this:

module.exports = {
    name: 'warn',
    description: "test",
    execute(message, args){
        const { Client, MessageEmbed } = require("discord.js")
        const client = new Client()

        const fs = require("fs")
        const ms = require("ms")
        warns = JSON.parse(fs.readFileSync("./warns.json", "utf8"))
        client.servers = require ("./servers.json")
        let guild = client.servers[message.guild.id].message
        
        
/*Embeds*/
const oops = new MessageEmbed()
        .setTitle("Error")
        .setColor("RED")
        .setDescription("You cant warn a member. Please ask a Moderator")
        .setAuthor("MemeBot", "this is a link")

const Mod = new MessageEmbed()
        .setTitle("Error")
        .setColor("RED")
        .setDescription("You cant warn a Moderator.")
        .setAuthor("MemeBot", "linkhere xD")
/**Commands */
let wUser = message.mentions.users.first() || message.guild.members.cache.fetch(`${args[0]}`)
if (!wUser) return message.channel.send("Are you sure, that this was a User? I think it wasn't one...")
let wReason = args.join(" ").slice(27)
if (!wReason) return message.channel.send("Please tell me, why you want to warn this person. Because, you know, it's a warn :D");
if(!message.member.hasPermission("KICK_MEMBERS")) return message.channel.send(oops)
if(wUser.hasPermission("KICK_MEMBERS")) return message.channel.send(Mod)


if(!warns[message.guild.id]) warns[message.guild.id] = {
    user: wUser.id,
    warns: 0
}


warns[wUser.id].warns++



fs.writeFile("./warns.json", JSON.stringify(warns, null, 4), err => {
    if(err) console.log(err)
});

let warnEmbed = new MessageEmbed()
.setTitle("Warned")
.setColor("YELLOW")
.addField("Warned User", `${wUser}`)
.addField("Moderator", `${message.author.id}`)
.addField("Reason", `${wReason}`)
.addField("Number of Warnings", warns[wUser.id].warns)
.addField("Warned at", `${message.createdAt}`)

let warnonEmbed = new MessageEmbed()
.setTitle("Warned")
.setColor("YELLOW")
.addField("Warned on", `${message.guild.name}`)
.addField("Moderator", `${message.author}`)
.addField("Reason", `${wReason}`)
.addField("Warned at", `${message.createdAt}`)
        
let logchannel = message.guild.channels.cache.find(c => c.id === 'id');
if(!logchannel) return 

wUser.send(warnonEmbed)
logchannel.send(warnEmbed)

}
}
Share Improve this question edited Dec 1, 2020 at 11:44 Hibiscus 7467 silver badges19 bronze badges asked Mar 17, 2020 at 16:06 Mr BrickstarMr Brickstar 3083 gold badges6 silver badges17 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 2

That particular layout doesn't make a lot of hierarchical sense. You might want to nest the user inside the guild and any parameters belonging to the user inside that. Something like this...

"superniceguildid": 
{
    "636302212787601408":
    {
        "warns": 3
    },
    "7837439745387549":
    {
        "warns": 1
    }
},

Accessing it then would be as easy as using something like the following:

let guildWarns = warns["superniceguildid"];
let userWarns = guildWarns["636302212787601408"];
let numberOfWarns = userWarns.warns;

you can bine that as well.

let numberOfWarns = warns["superniceguildid"]["636302212787601408"].warns;

Of course, remember that if it doesn't exist it will be undefined.

Post a comment

comment list (0)

  1. No comments so far