Discord.js开发报错:TypeError: servguild.roles.find is not a function 求助
Fixing the
TypeError: servguild.roles.find is not a function Error in Your Discord Bot Hey there! The error you're hitting is a common one with newer Discord.js versions—let's break down what's wrong and fix it right away:
Why This Error Occurs
In older Discord.js versions (pre-v12), guild.roles was directly a collection of roles, so calling .find() on it worked. But starting with v12, guild.roles became a RoleManager object, and the actual role data lives inside its .cache property. That's why servguild.roles.find isn't a valid function anymore.
Corrected Code (With Safety Checks)
Here's the fixed version of your code, plus extra checks to avoid other potential crashes:
client.on('message', message => { // Ignore messages from bots to prevent loops if (message.author.bot) return; const parts = message.content.split(" "); if (message.content.startsWith("sr")) { const servguild = message.guild; // Make sure we're in a server (DMs don't have guilds) if (!servguild) { message.reply("This command only works in servers!"); return; } const member = message.mentions.members.first(); // Check if a member was actually mentioned if (!member) { message.reply("Please tag a member to assign the role to!"); return; } // Access roles via the cache and find by name const role = servguild.roles.cache.find(role => role.name === 'Business Owners✔'); // Verify the role exists on the server if (!role) { message.reply("The 'Business Owners✔' role doesn't exist here!"); return; } // Assign the role with error handling member.addRole(role) .then(() => message.reply(`Successfully gave ${member.user.tag} the ${role.name} role!`)) .catch(err => message.reply(`Oops, couldn't assign the role: ${err}`)); } });
Key Changes Explained
- Replaced
servguild.roles.find('name', 'Business Owners✔')withservguild.roles.cache.find(role => role.name === 'Business Owners✔')to access the role collection correctly. - Added safety checks for:
- Bot messages (to avoid unintended behavior)
- Using the command in DMs (where guilds don't exist)
- Missing member mentions
- Non-existent target roles
- Added error handling for the role assignment to catch permission issues or other unexpected problems.
Quick Extra Tips
- Ensure your bot has the Manage Roles permission in the server—otherwise, the role assignment will fail.
- If you need to fetch roles not stored in the cache (rare for most use cases), use
servguild.roles.fetch()instead of.cache—just note this returns a promise, so you'll needasync/awaitor.then()to handle it.
内容的提问来源于stack exchange,提问作者Ape
相关产品推荐
相关产品推荐

