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

Discord.js:如何检测用户1分钟内对指定消息的回复?

问题描述

想要实现的功能

我正尝试为Discord机器人创建一个猜词命令处理器,它会从数组中随机选取一个动物,用户需根据提示在1分钟内猜出所选单词。

遇到的问题

当前命令处理器仅允许执行特定代码一次,因此无法检测用户是否回复了机器人的指定消息,也就无法实现1分钟内的回复检测。

现有代码

// Copyright © 2022 <copyright holders>

// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


const Discord = require("discord.js");
const { prefix, colors } = require("./../utils/config.json");
const embedColor = colors.default;
const embedError = colors.error;

module.exports = {
  name: "guess",
  description: "Find a secret animal by following the hints to get reputation.",
  aliases: ["?", "h"],
  usage: "[prefix] + ping",
  guildOnly: false,
  args: false,
  slash: true,
  permissions: {
    bot: [],
    user: [],
  },
  execute: async (message, args, client) => {
    const { commands } = message.client;

    function question() {
      // Sending message

      const animals = ["pig", "elephant", "shark", "dog", "cat", "lion", "wolf", "bee", "snake", "bird"];

      const random = Math.floor(Math.random() * animals.length);
      const random_choice = (animals[random]);


//    msg2 = message.channel.send("See or Change?");
//    if (msg2.type === 'REPLY')
//      console.log(msg1.content);

      let filter = m => m.author.id === message.author.id
      message.channel.send(`Are you sure to delete all data? \`YES\` / \`NO\``).then(() => {
        message.channel.awaitMessages(filter, {
          max: 1,
          time: 10000,
          errors: ['time']
        })
        .then(message => {
          message = message.first();
          if (message.content.toLowerCase() == random_choice) {
            message.channel.send(`Got it right`)
          } else {
            message.channel.send('The Animal was: \`' + random_choice + '\`!')
          }
        })
        .catch(collected => {
          message.channel.send('Timeout');
        });
      })
    }

    let { channel, reference: reply } = message

    const cmdHelpEmbed = new Discord.MessageEmbed()
      .setTitle("**PING**")
      .setDescription(`Hey, ` + message.author.username + `! I am ready to play guess game`)
      .setColor(embedColor)
      .addFields(
        {
          name: 'How to play?',
          value: 'This game is simple, I will select a random animal and give you 3 hints. You just need to find the correct animal to win reputation. To answer reply to this message, within 1 minute'
        }, {
          name: '\u200B',
          value: '**RULES**'
        }, {
          name: 'Rule 1:',
          value: 'No Cheating',
          inline: true
        },
        {
          name: 'Rule 2:',
          value: 'Have fun!',
          inline: true
        },
      );

    message.channel.send({
      embeds: [cmdHelpEmbed],
    });

    var delayInMilliseconds = 5000; // 5 seconds

    setTimeout(function() {
      question();
    }, delayInMilliseconds);
  },
};
解决方案

核心问题分析

你的代码存在三个关键问题:

  1. 游戏提示文本错误,显示的是删除数据的确认语,与猜动物功能无关
  2. 未设置针对“回复机器人指定消息”的过滤规则,仅限制了发送者ID
  3. 超时时间设为10秒,不符合需求的1分钟时限

修复后的代码

const Discord = require("discord.js");
const { prefix, colors } = require("./../utils/config.json");
const embedColor = colors.default;
const embedError = colors.error;

module.exports = {
  name: "guess",
  description: "Find a secret animal by following the hints to get reputation.",
  aliases: ["?", "h"],
  usage: "[prefix]guess",
  guildOnly: false,
  args: false,
  slash: true,
  permissions: {
    bot: [],
    user: [],
  },
  execute: async (message, args, client) => {
    const animals = ["pig", "elephant", "shark", "dog", "cat", "lion", "wolf", "bee", "snake", "bird"];
    const randomIndex = Math.floor(Math.random() * animals.length);
    const targetAnimal = animals[randomIndex];

    // 动物对应的提示(可扩展为3条)
    const hints = {
      pig: "粉色农场动物,喜欢滚泥巴",
      elephant: "长鼻子大耳朵,体型庞大",
      shark: "海洋顶级捕食者,有锋利牙齿",
      dog: "人类的忠诚伙伴",
      cat: "爱舔毛,会抓老鼠",
      lion: "草原之王,群居生活",
      wolf: "犬科群居动物,夜晚嚎叫",
      bee: "会采蜜,尾部有螫针",
      snake: "无腿爬行动物,部分有毒",
      bird: "有翅膀,多数会飞行"
    };
    const hintText = hints[targetAnimal];

    // 发送游戏提示消息并保存引用
    const gameMsg = await message.channel.send({
      embeds: [
        new Discord.MessageEmbed()
          .setTitle("猜动物游戏开始!")
          .setDescription(`提示:${hintText}\n请在1分钟内**回复这条消息**猜出动物名称!`)
          .setColor(embedColor)
      ]
    });

    // 过滤规则:仅接受当前用户对游戏消息的回复
    const filter = m => {
      return m.author.id === message.author.id && m.reference?.messageId === gameMsg.id;
    };

    try {
      // 等待用户回复,超时1分钟
      const collected = await message.channel.awaitMessages(filter, {
        max: 1,
        time: 60000,
        errors: ['time']
      });

      const userReply = collected.first().content.toLowerCase();
      if (userReply === targetAnimal) {
        message.channel.send(`恭喜答对!正确答案是\`${targetAnimal}\`!`);
        // 此处可添加增加声望的逻辑
      } else {
        message.channel.send(`答错啦,正确答案是\`${targetAnimal}\`!`);
      }
    } catch (err) {
      message.channel.send(`时间到!正确答案是\`${targetAnimal}\`!`);
    }
  },
};

修复说明

  • 替换了错误的提示文本,改为对应动物的线索提示
  • 新增回复过滤逻辑,确保只检测用户对游戏消息的回复
  • 将超时时间调整为60000毫秒(1分钟),匹配需求
  • 简化代码结构,移除冗余的setTimeout和question函数
  • 修正Embed标题为“猜动物游戏开始!”,符合功能场景

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 12:03:24