I'm using Discord.js to create a basic Discord bot. When the bot is first started, I run client.guilds.array()
to get a list of all guilds that the bot is currently subscribed to. I save this to a database that's used by other programs.
However, as people add / remove the bot from their guilds, I'd like to keep an updated list of guilds. I realize I could just re-run clients.guilds.array()
every minute or something, but that seems inefficient.
Is there an event that fires when your bot is added to a guild and/or channel? From what I've read, the guildMemberAdd
event seems to fire for all users / bots who are already subscribed to the guild. Is there any such event to let your bot know when it's been added to a guild?
Yes there is and you can view it in the client events https://discord.js.org/#/docs/main/stable/class/Client . A simple example to update an array of guilds using the event:
const discord = require("discord.js");
const client = new discord.Client();
let guildArray = client.guilds.array();
//joined a server
client.on("guildCreate", guild => {
console.log("Joined a new guild: " + guild.name);
//Your other stuff like adding to guildArray
})
//removed from a server
client.on("guildDelete", guild => {
console.log("Left a guild: " + guild.name);
//remove from guildArray
})