DiscordJS(节点)向用户发送 PM 并等待回复

DiscordJS (Node) Sending PM to user and await reply

我正在尝试让我的机器人在用户键入命令时向用户发送私人消息,然后等待对私人消息的回复。

预期流量:

我尝试了从此处和文档中找到的大量示例,但其中 none 有效。

message.author.send('test').then(function () {
  message.channel
    .awaitMessages((response) => message.content, {
      max: 1,
      time: 300000000,
      errors: ['time'],
    })
    .then((collected) => {
      message.author.send(`you replied: ${collected.first().content}`);
    })
    .catch(function () {
      return;
    });
});

message.author.send('test') returns 已发送的消息,因此您应该使用返回的消息来设置消息收集器。目前,您正在使用 message.channel.awaitMessages 并等待用户发送 !auth 消息的频道中的消息,而不是机器人发送响应的频道。

查看下面的工作代码。它使用 async-await,因此请确保父函数是 async 函数。我使用 createMessageCollector instead of awaitMessages 因为我认为它更具可读性。

try {
  // wait for the message to be sent
  let sent = await message.author.send('test');
  // set up a collector in the DM channel
  let collector = sent.channel.createMessageCollector({
    max: 1,
    time: 30 * 1000,
  });

  // fires when a message is collected
  collector.on('collect', (collected) => {
    collected.reply(`✅ You replied: _"${collected.content}"_`);
  });

  // fires when we stopped collecting messages
  collector.on('end', (collected, reason) => {
    sent.reply(`I'm no longer collecting messages. Reason: ${reason}`);
  });
} catch {
  // send a message when the user doesn't accept DMs
  message.reply(`❌ It seems I can't send you a private message...`);
}

确保不要忘记启用 DIRECT_MESSAGES 意图。例如:

const { Client, Intents } = require('discord.js');

const client = new Client({
  intents: [
    Intents.FLAGS.GUILDS,
    Intents.FLAGS.GUILD_MESSAGES,
    Intents.FLAGS.DIRECT_MESSAGES,
  ],
});