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

如何验证回复消息为指令发起用户?Discord机器人代码咨询

解决Discord机器人消息发送者验证问题

我来帮你搞定这个验证逻辑的问题!你的核心误区是没搞清楚wait_for的check函数参数类型——它接收的是完整的Message对象,不是单独的user对象,咱们调整一下就能完美实现只接收指令发起者的回复了:

修正后的完整代码

await ctx.send("Which inventory do you want to access?")
await ctx.send("Mining, Collecting, Farming, Fishing or Fighting?")

def check(message):
    # 双重验证:消息发送者是指令发起者,且消息在同一个频道(避免跨频道误触发)
    return message.author == ctx.author and message.channel == ctx.channel

# 等待符合条件的用户回复
type_check = await self.bot.wait_for('message', check=check)

# 处理用户选择(这里用elif比多个if更高效)
user_choice = type_check.content.lower()
if user_choice == "mining":
    await ctx.send("You chose Mining!")
elif user_choice == "collecting":
    await ctx.send("You chose Collecting!")
elif user_choice == "farming":
    await ctx.send("You chose Farming!")
elif user_choice == "fishing":
    await ctx.send("You chose Fishing!")
elif user_choice == "fighting":
    await ctx.send("You chose Fighting!")
else:
    await ctx.send("Invalid choice! Please pick one of the listed options.")

关键细节说明

  • check函数必须返回布尔值:只有返回True时,wait_for才会把这条消息作为结果返回
  • 额外加上message.channel == ctx.channel是为了避免用户在其他频道乱回复也触发逻辑,让指令更严谨
  • 最后加else分支处理无效输入,能提升机器人的交互体验

进阶优化建议

如果以后要加更多 inventory 选项,用字典映射会让代码更易维护:

# 把选项和回复提前存在字典里
choice_response = {
    "mining": "You chose Mining!",
    "collecting": "You chose Collecting!",
    "farming": "You chose Farming!",
    "fishing": "You chose Fishing!",
    "fighting": "You chose Fighting!"
}

# 直接通过字典获取回复,没有匹配到就返回默认提示
await ctx.send(choice_response.get(user_choice, "Invalid choice! Please pick one of the listed options."))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 07:22:59