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

discord.py调用client.wait_for提示Check is not defined如何解决

错误原因

client.wait_for()方法的check参数需要传入一个自定义校验函数,用于筛选符合要求的事件消息,你没有提前定义该变量因此触发NameError。

适配需求的check定义

你的需求是捕获发送=hi命令的用户后续在同频道发送的消息,直接在wait_for调用前定义如下函数即可:

def check(message):
    # 校验规则:消息发送者 = 命令调用者,且消息所在频道 = 命令触发频道
    return message.author == ctx.author and message.channel == ctx.channel

完整可运行的命令示例

你可以直接替换原有=hi命令的逻辑,下面的代码还额外加了超时处理避免机器人无限等待:

import discord
from discord.ext import commands

bot = commands.Bot(command_prefix='=', intents=discord.Intents.all())

@bot.command(name='hi')
async def hi(ctx):
    await ctx.send('请输入你要发送的内容:')
    # 定义check校验函数
    def check(message):
        return message.author == ctx.author and message.channel == ctx.channel
    
    try:
        # 等待用户回复,最多等30秒
        msg = await bot.wait_for('message', check=check, timeout=30)
    except TimeoutError:
        await ctx.send('等待超时,请重新调用命令')
        return
    # 回复用户发送的内容
    await ctx.send(msg.content)

注意:你需要在Discord开发者后台开启机器人的消息内容权限,同时代码中初始化bot时正确配置Intents才能正常读取消息内容

自定义规则说明

如果需要额外的校验规则,只需要修改check函数的返回条件即可,比如要求用户发送的内容必须是数字:

def check(message):
    return message.author == ctx.author and message.channel == ctx.channel and message.content.isdigit()

内容的提问来源于stack exchange,提问作者streetlight006

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 01:06:03