[Solved] Display all Guild Names of a Bot in discord.js


guilds.json

{
    Placeholder: null
}

The above is the file with the guild IDs

const fs = require('fs');
const Discord = require('discord.js');
const client = new Discord.Client();

client.on('ready', () => {
    let guilds = client.guilds.cache
    const json = {}
    guilds.forEach(g => {
        json[g.name] = g.id
    });
    fs.writeFileSync('./guilds.json', JSON.stringify(json))
});

client.on('guildCreate', guild => {
    const file = fs.readFileSync('./guilds.json', 'utf8');
    const json = JSON.parse(file);
    json[guild.name] = guild.id;
    fs.writeFileSync('./guilds.json', JSON.stringify(json));
})

client.on('guildDelete', guild => {
    const file = fs.readFileSync('./guilds.json', 'utf8');
    const json = JSON.parse(file);
    delete json[guild.name];
    fs.writeFileSync('./guilds.json', JSON.stringify(json));
})

client.on('guildUpdate', (oldGuild, newGuild) => {
    if(oldGuild.name === newGuild.name) return;
    const file = fs.readFileSync('./guilds.json', 'utf8');
    const json = JSON.parse(file);
    delete json[oldGuild.name];
    json[newGuild.name] = newGuild.id;
    fs.writeFileSync('./guilds.json', JSON.stringify(json));
});

My fs syntax may be wrong, but at least you should get the idea. On ready, you put all the guilds into the file, on guild create, you add that guild to the file, on guild delete, you delete the guild from the file.

10

solved Display all Guild Names of a Bot in discord.js