You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 your check function, so the check never actually gets used. Any message from anyone in any channel would trigger the next step. Also, you had a typo: channnel should be channel.
  • 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:

  1. Proper check function setup: We define the user_check before calling wait_for, and pass it as the check parameter. This ensures only the command initiator's messages in the same channel are accepted.
  2. 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_user to 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.
  3. Reusable check: We reuse the same user_check for 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 07:36:11