XtoManuel
XtoManuel
DIAdiscord.js - Imagine an app
Created by XtoManuel on 8/25/2024 in #djs-questions
Is there a way to get a log of added or removed roles for a member?
I have used this code for a long time to achieve this until suddenly I encountered an error when a member is not in the cache. When the guildMemberUpdate event occurs, it logs that all roles the member already had have been added again.
export default async (client, oldMember, newMember) => {
// Get roles of the oldMember from the cache (not ideal but necessary if no other option)
const oldRolesIds = oldMember.roles.cache.map((role) => role.id);

// Get roles of the newMember from the cache (not ideal but necessary if no other option)
const newRolesIds = newMember.roles.cache.map((role) => role.id);

// Compare the length of old and new roles
if (oldRolesIds.length !== newRolesIds.length) {
// Log the differences in roles if there is a change
await sendLogs(client, `\`\`\`\nOld roles: [ ${oldRolesIds.join(", ")} ]\nNew roles: [ ${newRolesIds.join(", ")} ]\n\`\`\``);
}
} catch (error) {
// Log any errors that occur during processing
console.error(`Error processing guildMemberUpdate: ${error}`);
}
};
export default async (client, oldMember, newMember) => {
// Get roles of the oldMember from the cache (not ideal but necessary if no other option)
const oldRolesIds = oldMember.roles.cache.map((role) => role.id);

// Get roles of the newMember from the cache (not ideal but necessary if no other option)
const newRolesIds = newMember.roles.cache.map((role) => role.id);

// Compare the length of old and new roles
if (oldRolesIds.length !== newRolesIds.length) {
// Log the differences in roles if there is a change
await sendLogs(client, `\`\`\`\nOld roles: [ ${oldRolesIds.join(", ")} ]\nNew roles: [ ${newRolesIds.join(", ")} ]\n\`\`\``);
}
} catch (error) {
// Log any errors that occur during processing
console.error(`Error processing guildMemberUpdate: ${error}`);
}
};
Here is an example of the logs with this code, showing this issue:
Old roles: [ 418586876899885056 ]
New roles: [ 807991856868229200, 807994083204792380, 807991313542676520, 874292095840563280, 807991901932224552, 873953249055621172, 807991887055028266, 418586876899885056 ]
Old roles: [ 418586876899885056 ]
New roles: [ 807991856868229200, 807994083204792380, 807991313542676520, 874292095840563280, 807991901932224552, 873953249055621172, 807991887055028266, 418586876899885056 ]
where 418586876899885056 is the ID of the server (guild).
7 replies