如何在Discord.Net的SocketMessage中检查用户是否拥有指定角色
How to Check if a User Has a Specific Role in Discord.Net (SocketMessage)
Hey there, let's fix up your role checking code! The main issues in your current snippet are how you're accessing the user's guild roles and checking for the specific role. Here's a breakdown of what's wrong and how to fix it:
What's Not Working in Your Code:
arg.Authoris aSocketUser—this object doesn't have access to guild-specific role data, even after casting toIGuildUser(you should first confirm the message is in a guild channel).- There's no
Roleproperty onIGuildUser—you need to check against the user's collection of roles instead.
Corrected Code with Explanations:
private async Task CheckMessage(SocketMessage arg) { // Skip bot messages (you already have this, great!) if (arg.Author.IsBot) return; // Ensure the message was sent in a guild channel (not a DM) if (arg.Channel is not SocketGuildChannel guildChannel) return; // Get the guild-specific user object var guild = guildChannel.Guild; SocketGuildUser guildUser = guild.GetUser(arg.Author.Id); // If the user isn't in the guild anymore, exit early if (guildUser == null) return; // Option 1: Check for the role by name (case-insensitive) bool hasPopRole = guildUser.Roles.Any(role => role.Name.Equals("pop", StringComparison.OrdinalIgnoreCase)); // Option 2: Check for the role by ID (RECOMMENDED—names can change!) // Replace this with your actual role's ID from Discord ulong popRoleId = 123456789012345678; bool hasPopRoleById = guildUser.Roles.Any(role => role.Id == popRoleId); // Use whichever check fits your needs if (hasPopRole) { var emoji = new Emoji("💩"); await arg.AddReactionAsync(emoji); } }
Important Notes:
- Guild Channel Check: We first verify the message is in a
SocketGuildChannelbecause DMs don't have guild roles—trying to get a guild user from a DM will cause errors. - Guild User Retrieval: Using
guild.GetUser(arg.Author.Id)gives us the fullSocketGuildUserobject, which includes all the user's roles in that guild. - Role Checking Best Practices:
- Using the role ID is better because server admins can change role names, but the ID stays the same.
- If you must use the role name, adding
StringComparison.OrdinalIgnoreCasemakes the check work regardless of uppercase/lowercase differences.
That should do it! This code will correctly check if the user has the "pop" role and add the reaction if they do.
内容的提问来源于stack exchange,提问作者palka tt
相关产品推荐
相关产品推荐

