discord.py:如何验证回复为服务器内有效用户ID或提及?
Fixing User Validation for Your Discord Bot's Watch Command
Hey there, let's break down why your current code isn't validating user inputs properly, and fix it step by step:
The main issues with your existing code:
- You're calling
client.wait_for('message')before defining yourcheckfunction, so the check never actually gets used. Any message from anyone in any channel would trigger the next step. Also, you had a typo:channnelshould bechannel. - There's no logic to parse the user's response and verify if it's a real server user mention or valid ID.
- No error handling—invalid inputs just let the command keep running instead of notifying the user.
Here's the corrected, fully functional code with explanations:
import discord from discord.ext import commands @client.command() @commands.has_permissions(manage_messages=True) async def watch(ctx): # Step 1: Get and validate the target user await ctx.send("Please mention the user or send the ID of the user you would like to watch!") # Define the check FIRST, before calling wait_for def user_check(m): return m.author == ctx.author and m.channel == ctx.channel # Fixed the typo here # Wait for the user's response, using our check to filter valid messages user_response = await client.wait_for('message', check=user_check) target_user = None # Check if the message contains a user mention (@someone) if user_response.mentions: target_user = user_response.mentions[0] else: # Try to parse the input as a user ID try: user_id = int(user_response.content.strip()) # Fetch the user to verify the ID exists target_user = await client.fetch_user(user_id) except ValueError: # Input wasn't a numeric ID await ctx.send("Oops! That's not a valid user mention or ID. Please try again.") return except discord.NotFound: # ID is numeric but doesn't match any real user await ctx.send("Hmm, that user ID doesn't belong to anyone on Discord. Double-check it!") return # Step 2: Get the situation description await ctx.send("Please Describe the situation") desc_response = await client.wait_for('message', check=user_check) situation = desc_response.content # Add your actual monitoring logic here await ctx.send(f"Got it! I'll keep an eye on {target_user.mention} regarding: {situation}")
Key fixes explained:
- Proper check function setup: We define the
user_checkbefore callingwait_for, and pass it as thecheckparameter. This ensures only the command initiator's messages in the same channel are accepted. - User validation logic:
- We first check if the message has any
mentions—Discord.py automatically parses mentions into user objects for us. - If no mentions, we try converting the input to an integer (user IDs are numeric) and use
fetch_userto confirm the ID is linked to a real user. - We catch common errors (non-numeric input, non-existent user) and send clear error messages before exiting the command.
- We first check if the message has any
- Reusable check: We reuse the same
user_checkfor both prompts to keep the code clean.
Now when someone enters an invalid user mention/ID, the bot will immediately let them know and stop the command—no more proceeding with bad inputs!
内容的提问来源于stack exchange,提问作者FakeBlob
相关产品推荐
相关产品推荐

