My discord bot, using discords, is using a module that allows users to pick one or more roles from a message with buttons. Those roles are then added (or removed if clicked again) from that guild member. The message is also updated to show the amount of members for each role in the role picker. This data is retrieved from discord itself. This all works fine.
However, when an admin manually adds or removes a role with the guild member, the messages that contain role pickers also need to update their counts. Here I run into an issue.
The main .js file listens to the guildMemberUpdate event and then calls the role picker module to handle the event.
client.on('guildMemberUpdate', (oldMember, newMember) => {
rolepicker.onGuildMemberUpdate(client, newMember);
});
This works fine. So I receive the event and it is send to the role picker module.
onGuildMemberUpdate: async function(client, member) {
logger.log({module: logmodule, level: 'debug', message: 'onGuildMemberUpdate()'});
const sqlSelectItems = `SELECT rolepickerId FROM rolepicker WHERE guildId = "${member.guild.id}" AND messageId IS NOT NULL`;
const items = await mysqlLib.query(sqlSelectItems).catch(err => {
logger.log({module: logmodule, level: 'warn', message: 'DB Error in retrieving role pickers in onGuildMemberUpdate: ' + err, stack: err.stack});
});
if ( items != null && items.length > 0 ) {
for ( i = 0 ; i < items.length ; i++ ) {
const rolepickerId = items[i].rolepickerId;
const guildid = member.guild.id;
await rolepicker.updateRolepicker(client, guildid, rolepickerId);
}
}
},
In the updateRolepicker function the message is retrieved and updated. Before actually counting the amount of members of each role, I do call:
await guilds.members.fetch();
to make sure that all data of all guilds members is retrieved.
However, it seems that the updated member data during the guildMemberUpdate event is not yet fully progressed through the discord system, as it role changes are not in the guilds.members collection even after the fetch() call.
I did found a workaround using:
setTimeout(function() { rolepicker.updateRolepicker(client, guildid, rolepickerId)}, 1000);
This delays the actual update of the role picker messages. When using this it does get the updated data in the guild.members collections.
However, using a setTimeout delay is not a clean solution as who knows how long it might take each time for the data to be actually fully updated on discord.
I hope someone can help me find a better solution.