【问题标题】:Bot not replying correctly in a private message机器人未在私人消息中正确回复
【发布时间】:2019-06-27 19:35:02
【问题描述】:

因此,此代码块是玩家 A(挑战者)向玩家 B(目标)发出挑战的代码的一部分。机器人会向玩家 B 发送一条私人消息,告诉他们他们受到了挑战,并询问他们是接受还是拒绝挑战。
以下代码似乎没有响应玩家 B 的回复。

if (message.channel.id === '541736552582086656') return target.send("Do you accept the challenge? Please reply with 'accept' or 'deny'.")
  .then((newmsg) => {
    newmsg.channel.awaitMessages(response => response.content, {
      max: 1,
      time: 150000,
      errors: ['time'],
    }).then((collected) => {
      if (collected === 'accept') {
        newmsg.channel.send("You have ***accepted*** the challenge. Please wait while your battlefield is made...");
      } else if (collected === 'deny') {
        newmsg.channel.send("You have ***denied*** the challenge.")
      }
    }).catch(() => {
      newmsg.channel.send('Please Accept or Deny the challenge.');
    });
  });
}

在此代码块之前,我设置了将消息记录到服务器上的通道,向挑战者和目标发送挑战信息。机器人通过 pm 成功联系到他们被挑战的目标,但回复(即使回复“接受”仍然会认为它被拒绝了。
感谢您的所有帮助!

【问题讨论】:

  • 有人通过 PM 发送“接受”后,console.log(collected) 打印什么?
  • 它获取 _content: 'accept'。
  • 根据他们的doccollected 将是CollectionMessages。所以collected 永远不能等于'accept'! (此外,如果用户没有准确输入“接受”或“拒绝”,您的 if-else-if 逻辑将不会回复任何内容。)
  • 那么,我该如何解决这个问题?

标签: javascript node.js discord.js


【解决方案1】:

扩展@Stock Overflaw 的答案,awaitMessages 将始终返回获取消息的集合,这意味着collected === 'accepted' 将不起作用。您正在检查集合对象是否与字符串相同。

您需要从集合中获取第一条(仅在您的情况下)消息,并根据字符串检查其内容。您将在下面找到您的.then(...) 声明已重写。试一试,让我知道结果如何。

附:您的收藏过滤器不会像您预期的那样工作。过滤器仅检查是否将消息添加到集合中。由于您的“过滤器”是response => response.content,它只会检查response.content 是否为空、nullundefined

.then((collected) => {
  // Grabs the first (and only) message from the collection.
  const reply = collected.first();

  if (reply.content === 'accept'){
    reply.channel.send("You have ***accepted*** the challenge. Please wait while your battlefield is made...");
  } else if (reply.content === 'deny') {
    reply.channel.send("You have ***denied*** the challenge.") 
  } else {
    reply.channel.send("Your response wasn't valid.");
    /*
     * Code here to handle invalid responses
     */
  }
})

【讨论】:

  • 天哪。我不敢相信我没有意识到这一点。我让它变得比它需要的复杂得多!非常感谢!效果很好!
猜你喜欢
  • 1970-01-01
  • 2022-11-11
  • 2018-11-19
  • 2012-09-21
  • 2017-07-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-26
相关资源
最近更新 更多