How to make by bot to leave a server with a guild id

Viewed 1007

I want my bot to leave a discord server by using ;leave <GuildID>.

The code below does not work:

if (message.guild.id.size < 1)
  return message.reply("You must supply a Guild ID");
if (!message.author.id == 740603220279164939)
  return;

message.guild.leave()
  .then(g => console.log(`I left ${g}`))
  .catch(console.error);
1 Answers

You're most likely not supposed to be looking at message.guild.id, since that returns the ID of the guild you're sending the message in. If you want to get the guild ID from ;leave (guild id), you'll have to cut out the second part using something like .split().

// When split, the result is [";leave", "guild-id"]. You can access the
// guild ID with [1] (the second item in the array).
var targetGuild = message.content.split(" ")[1];

!message.author.id will convert the author ID (in this case, your bot ID) into a boolean, which results to false (since the ID is set and is not a falsy value). I'm assuming that you mean to have this run only if it the author is not the bot itself, and in that case, you're most likely aiming for this:

// You're supposed to use strings for snowflakes. Don't use numbers.
if (message.author.id == "740603220279164939") return;

And now, you just have to use the guild ID that you got from the message content and use that to leave the guild. To do that, just grab the Guild from your bot cache, and then call .leave(). All in all, your code should now look like this:

// Get the guild ID
var targetGuild = message.content.split(" ")[1];
if (!targetGuild) // targetGuild is undefined if an ID was not supplied
    return message.reply("You must supply a Guild ID");

if (message.author.id == "740603220279164939") // Don't listen to self.
    return;

client.guilds.cache.get(targetGuild) // Grab the guild
    .leave() // Leave
    .then(g => console.log(`I left ${g}`)) // Give confirmation after leaving
    .catch(console.error);
Related