I am trying to create a button system where if you do not have a specific role, you are unable to use a button. However, the code I have created doesn't seem to work.
collector.on('collect', async interaction => {
const wikiStaffRole = interaction.user.guild.roles.cache.find(role => role.name == "Staff");
if (interaction.customId === "yes") {
if (!wikiStaffRole) {
return interaction.followUp({ content: `${interaction.user} dude you need to be a staff member`, ephmeral: true });
}
newUserEmbed.edit({ embeds: [], content: 'This report has been marked as completed.', components: [] });
return;
} else if (interaction.customId === "no") {
if (!wikiStaffRole) {
return interaction.followUp({ content: `${interaction.user} dude you need to be a staff member`, ephmeral: true });
}
newUserEmbed.edit({ embeds: [], content: 'This report has been denied.', components: [] });
return;
} else if (interaction.customId === "what") {
if (!wikiStaffRole) {
return interaction.followUp({ content: `${interaction.user} dude you need to be a staff member`, ephmeral: true });
}
newUserEmbed.edit({ embeds: [], content: 'This report has been marked as inconclusive.', components: [] });
return;
}
});
Instead, I just get an error that states that it cannot read the property 'roles' of undefined. I cannot figure out any ways to fix this.
You tried accessing the non-existent guild property of a User object. This property does not exist on Users but does exist on GuildMember and Interaction objects. This code should work:
const wikiStaffRole = interaction.guild.roles.cache.find(role => role.name == "Staff")
Keep in mind that if it is not in a guild, this will throw an error. You can use optional chaining (?.) to prevent that
const wikiStaffRole = interaction.guild?.roles.cache.find(role => role.name == "Staff")
I think you wanted to check if the member had the role though. You are actually checking if the entire server has the role. This will check only the member's roles
const wikiStaffRole = interaction.member?.roles.cache.find(role => role.name == "Staff")
//optional chaining because member would be null if it was sent in a DM