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
相关产品推荐
相关产品推荐

