如何验证Discord机器人命令中用户输入的是有效成员提及还是无意义乱码
Fixing Member Mention Validation for Your Discord Bot's Bruh Command
Let’s sort out that validation issue you’re having! Your current code doesn’t actually check if the user’s input is a valid server member—instead, it just compares the message content to itself (which will always be true). Here’s how to properly validate mentions and make your command work as intended:
Updated Code
@client.command() async def bruh(ctx): await ctx.send("Who do you want to bruh?") def check(msg): return msg.author == ctx.author and msg.channel == ctx.channel msg = await client.wait_for("message", check=check) # Try to get the target member from mentions or input target_member = None # First, check if the user mentioned someone directly if msg.mentions: target_member = msg.mentions[0] else: # Fallback: try to match by username/nickname using MemberConverter try: target_member = await commands.MemberConverter().convert(ctx, msg.content) except commands.BadArgument: # If conversion fails, target_member stays None pass if target_member: # Double-check the member is in the current server (extra safety) if target_member in ctx.guild.members: # Replace with your actual person_x ID person_x_id = "123456789012345678" await ctx.send(f"<@!{person_x_id}>, <@!{ctx.author.id}> wants you to bruh <@!{target_member.id}>") else: await ctx.send("bruh that guy's not in the server") else: await ctx.send("Hey, that's not a valid member! Please @ someone in the server or use their exact username/nickname.")
Key Improvements Explained
- Direct Mention Handling:
msg.mentionsis a list ofMemberobjects that the user explicitly @mentioned. This is the most reliable way to get a valid server member, since Discord handles the mention parsing for you. - Fallback Member Lookup: Using
MemberConverterlets users input a username or nickname instead of just mentioning—this makes the command more user-friendly without sacrificing validation. If the input doesn’t match any server member, it throws aBadArgumenterror which we catch. - Proper Validation Check: Instead of that useless
msg.content == target_idcheck, we now verify thattarget_memberexists (meaning the input was valid) and that the member is actually in the current server. - Cleaner String Formatting: F-strings (
f"...") make the message construction way easier to read and maintain compared to old-style string concatenation.
What Was Wrong With Your Original Code?
The line if msg.content == target_id: does nothing useful because target_id is set to msg.content—so this condition will always be True. That’s why your bot was accepting any input, even gibberish. By replacing that with proper member validation, you ensure only valid server members are passed along.
内容的提问来源于stack exchange,提问作者Arikakate




