Search code examples
javascriptdiscorddiscord.js

discord.js - guildMemberRemove doesn't work, guildMemberAdd works perfectly fine


Sorry if this is poorly formatted, I've never written a question on here before.

First of all, this is my first time writing anything in JavaScript, so this might be some dumb mistake I'm making that's causing my problem.

What I want to do is send a message when a member joins the server, and send a different message when a member leaves. When someone joins the server, the join message is sent and everything works perfectly fine, but when a member leaves, absolutely nothing happens. I put in some console.logs in the joinMessage and leaveMessage functions, and I get an output for joinMessage but nothing for remove. I have enabled Presence Intent and Server Members Intent on the Discord developer portal.

The join and leave message functions are down at the bottom, but I went ahead and added the entire thing so people could help me better. The bot token and channel IDs have been removed, and they are correct in my version of the code.

console.log('Starting');

const Discord = require('discord.js');
const { Client, Intents } = require('discord.js');
const commandHandler = require("./commands");
const client = new Discord.Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES, Intents.FLAGS.GUILD_MEMBERS] });
client.login('token');
var server = client.guilds.cache.get('server');

client.on('ready', ready);
function ready()
{
    console.log('Authenticated');
    server = client.guilds.cache.get('server');
}

client.on('messageCreate', receivedMessage);
function receivedMessage(msg)
{
    commandHandler(msg);
}


client.on('guildMemberAdd', joinMessage);
function joinMessage(member)
{
    let channelWelcome = server.channels.cache.get('welcome');
    let channelIntro = server.channels.cache.get('intro');
    channelWelcome.send(`Welcome to the server, ${member}! Head over to ${channelIntro} and introduce yourself!`); 
}


client.on('guildMemberRemove', leaveMessage);
function leaveMessage(member)
{
    let channelWelcome = server.channels.cache.get('welcome');
    channelWelcome.send(`${member} has left the server.`); 
}

I've been trying to figure this out for about an hour, so I'd really appreciate it if someone could help me solve this. Thanks!


Solution

  • You need to include following intent: GUILD_PRESENCES

    So your code needs to look like this:

    const client = new Discord.Client({ intents: [Intents.FLAGS.GUILD_PRESENCES, Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES, Intents.FLAGS.GUILD_MEMBERS] });
    

    Now your bot will detect if a member leaves the guild.