My Discord bot uses the GuildMemberUpdate
event to validate whether a specific role has been added/removed from users in a server, and based on this, it performs certain actions on a database.
The event is expected to do the following, and in fact, it works correctly:
- Was role X added? Action 1 is performed.
- Was role X removed? Action 2 is performed.
The issue arises when, for some reason, the bot needs to be restarted. After restarting, if role X is removed from a user who already had it previously, the event stops working as expected. It doesn’t trigger either of the two conditions because, as seen in hasVipRoleNow
and hadVipRoleBefore
, both values are returned as false
:
const { Events } = require('discord.js');
module.exports = {
name: Events.GuildMemberUpdate,
async execute(oldMember, newMember) {
// This variable has the ID of the official server.
const guildId = 'MY_GUILD_ID';
// This variable has the ID of the VIP User role.
const vipRoleId = 'MY_ROLE_ID';
// The conditional checks if the event was triggered in the official server.
if (newMember.guild.id !== guildId) {
return;
}
const oldRoles = oldMember.roles.cache;
const newRoles = newMember.roles.cache;
const hasVipRoleNow = newRoles.has(vipRoleId);
const hadVipRoleBefore = oldRoles.has(vipRoleId);
if (!hadVipRoleBefore && hasVipRoleNow) {
try {
managePremiumStatus(true, newMember);
} catch (error) {
console.error(error);
}
}
if (hadVipRoleBefore && !hasVipRoleNow) {
try {
managePremiumStatus(false, newMember);
} catch (error) {
console.error(error);
}
}
},
};
The best approach I’ve come up with is to use a third if
statement so that if both values are false
, it performs the same behavior as the second if
.
if (!hadVipRoleBefore && !hasVipRoleNow) {
// Treat this area as the second 'if'.
}
However, I’m not sure if this is the correct solution or if there might be a better one.