首页 > 解决方案 > 参考 DM 通道

问题描述

我正在尝试创建一个命令,该命令允许用户在通过 DM 提示后创建密码。我可以向用户发送消息,但无法读取用 a 发回的消息,MessageCollector因为我找不到引用 DM 频道的方法。

我曾尝试使用bot.on("message", message)此处的另一个实例,但这会在系统中造成泄漏,导致第二个实例永远不会消失。

我也不能让用户使用命令说!CreatePassword ***,因为这个功能与许多其他功能有严格的联系。

也许我在做一些根本错误的事情,或者以一种糟糕的方式解决问题,但我需要一种方法来引用 DM 频道。

这是迄今为止我的代码的最佳迭代。

function createAccount(receivedMessage, embedMessage)
{
    const chan = new Discord.DMChannel(bot, receivedMessage.author);

    const msgCollector = new Discord.MessageCollector(chan , m => m.author.id == receivedMessage.author.id);
    msgCollector.on("collect", (message) => 
    {
        // Other Code
        msgCollector.stop();
        // Removing an embed message on the server, which doesn't have a problem.
        embedMessage.delete();
    })
}

如有必要,我可以显示我的其余代码。

感谢您的时间。我为此失眠了一整夜。

标签: javascriptnode.jsdiscorddiscord.js

解决方案


我会这样做(我会假设这receivedMessage是触发命令的消息,如果我错了,请纠正我)

async function createAccount(receivedMessage, embedMessage) {
  // first send a message to the user, so that you're sure that the DM channel exists.
  let firstMsg = await receivedMessage.author.send("Type your password here");

  let filter = () => true; // you don't need it, since it's a DM.
  let collected = await firstMsg.channel.awaitMessages(filter, {
      maxMatches: 1, // you only need one message
      time: 60000 // the time you want it to run for
    }).catch(console.log);

  if (collected && collected.size > 0) {
    let password = collected.first().content.split(' ')[0]; // grab the password
    collected.forEach(msg => msg.delete()); // delete every collected message (and so the password)
    await firstMsg.edit("Password saved!"); // edit the first message you sent
  } else await firstMsg.edit("Command timed out :("); // no message has been received

  firstMsg.delete(30000); // delete it after 30 seconds
}

推荐阅读