如何在Discord服务器中查找名称包含指定文本的角色?
Hey there! The issue with your current code is that you're using strict equality (===) to match the role name exactly to "Mod"—that's why it only picks up roles with that exact name. To match any role where the name includes "Mod" (regardless of case, like "MODerator" or "mod team"), we need to adjust the matching logic.
Here's the fix:
Instead of checking for an exact name match, we'll convert both the role name and our target string to the same case (lowercase, in this example) and use the includes() method to check if "mod" is present anywhere in the role name.
Updated Code:
client.on('message', msg => { if (msg.author == client.user) { return; } let message = msg.content.toLowerCase(); // Look for any role whose name includes "Mod" (case-insensitive) let allowedRole = msg.guild.roles.cache.find(r => r.name.toLowerCase().includes('mod')); if (message.includes("e!")) { if (message.includes('automod') && allowedRole) { if (automodOn) { automodOn = false; msg.channel.send("Automod has been `deactivated`."); } else { automodOn = true; msg.channel.send("Automod has been `activated`."); } } } });
Key Changes Explained:
r.name.toLowerCase().includes('mod'): Converts the role name to lowercase and checks if "mod" is a substring. This handles all case variations like "MOD", "mod", "Moderator", etc.- We kept the
allowedRolecheck in the condition (&& allowedRole) to make sure we only run the automod toggle if a matching role exists in the server.
If you ever want to make the match case-sensitive (only pick up roles with exactly "Mod" somewhere, not lowercase "mod"), just remove the .toLowerCase() calls:
let allowedRole = msg.guild.roles.cache.find(r => r.name.includes('Mod'));
内容的提问来源于stack exchange,提问作者R0CK3T_DEV

