首页 > 解决方案 > Discord js直接消息等待不起作用

问题描述

所以我的不和谐机器人向 DM 中的用户询问 API 机密。我想等待用户的响应,以便我可以用我的密钥做更多的事情。

client.on('messageCreate')用户请求添加密钥后,我调用此函数

async function takeApiSecret(msg) {

    const botMsg = await msg.author.send("Please provide your api secret");
    const filter = collected => collected.author.id === msg.author.id;

    const collected = await botMsg.channel.awaitMessages(filter, {
      max: 1,
      time: 50000,
  }).catch(() => {
    msg.author.send('Timeout');
  });

但是我无法等待用户的回复并收集它。相反,当我回复时,我的client.on('messageCreate'). 任何线索我可能做错了什么?

标签: javascriptnode.jsasync-awaitdiscord.js

解决方案


在 discord.js v13.x 中,参数awaitMessages()略有变化。filter和不再有单独的参数optionsfilter现在包含在选项中。这应该可以解决您的问题:

const filter = collected => collected.author.id === msg.author.id;

const collected = await botMsg.channel.awaitMessages({
    filter,
    max: 1,
    time: 50000,
}).catch(() => {
    msg.author.send('Timeout');
});

您可以在此处找到文档。出于某种原因,这些选项似乎没有完整记录,但您可以查看该页面上的示例以查看新格式。


此外,如果每当通过 DM 发送消息时调用此代码,您可能需要防止收集的消息触发其余的messageCreate事件侦听器代码。这是您可以做到的一种方法:

外部messageCreate处理程序:

const respondingUsers = new Set();

就在之前awaitMessages()

respondingUsers.add(msg.author.id);

在您的内部.then().catch()您的awaitMessages()

respondingUsers.delete(msg.author.id);

在您的处理程序顶部附近messageCreate,在您进行其他检查之后(例如,检查消息是否为 DM):

if (respondingUsers.has(msg.author.id)) return;

如果我们将所有这些放在一起,它可能看起来像这样(显然,修改它以使用您的代码):

const respondingUsers = new Set();

client.on('messageCreate', msg => {

    if (msg.channel.type != "DM") return;
    if (respondingUsers.has(msg.author.id)) return;

    respondingUsers.add(msg.author.id);
    
    const filter = collected => collected.author.id === msg.author.id;

    const collected = botMsg.channel.awaitMessages({
        filter,
        max: 1,
        time: 50000,
    })
    .then(messages => {
        msg.author.send("Received messages");
        respondingUsers.delete(msg.author.id);
    })
    .catch(() => {
        msg.author.send('Timeout');
        respondingUsers.delete(msg.author.id);
    });

})

推荐阅读