如何在discord.js中使用awaitMessages函数

问题描述

我有一些用于 discord.js 的代码,当用户加入服务器时,它会向用户发送一个 DM。然后他们必须输入提供给他们的密码,然后他们就会获得一个角色,允许他们访问频道。

const discord = require('discord.js');
const client = new discord.Client();

client.once('ready',() => {
    console.log('Ready!');
});

client.on('guildMemberAdd',guildMember => {
    console.log("Joined");
    guildMember.send("Welcome to the server! Please enter the password given to you to gain access to the server:")
      .then(function(){
        guildMember.awaitMessages(response => message.content,{
          max: 1,time: 300000000,errors: ['time'],})
        .then((collected) => {
            if(response.content === "Pass"){
              guildMember.send("Correct password! You Now have access to the server.");
            }
            else{
              guildMember.send("Incorrect password! Please try again.");
            }
          })
          .catch(function(){
            guildMember.send('You didnt input the password in time.');
          });
      });
});

client.login("token");

问题是,我真的不知道如何使用 awaitResponses 函数。我不知道如何称呼它,因为我找到的所有教程都将它与 message.member 一起使用。

当我运行代码时,出现以下三个错误UnhandledPromiseRejectionWarning: TypeError: guildMember.awaitMessages is not a function

UnhandledPromiseRejectionWarning:未处理的承诺拒绝。这个错误要么是因为在没有 catch 块的情况下抛出了异步函数,要么是因为拒绝了一个没有用 .catch() 处理过的承诺。要在未处理的承诺拒绝时终止节点进程,请使用 CLI 标志 --unhandled-rejections=strict(请参阅 https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode)。 (拒绝编号:1)

Unhandled promise rejections are deprecated. In the future,promise rejections that are not handled will terminate the Node.

我不知道这些是指什么行,所以我很困惑。

解决方法

以下是 awaitMessages 工作原理的简要概述:

首先,.awaitMessages() 函数扩展了 GuildChannel,这意味着您通过扩展 GuildMember 对象已经搞砸了一点。 - 您可以使用

轻松获取频道
const channelObject = guildMember.guild.channels.cache.get('Channel ID Here'); // Gets a channel object based on it's ID
const channelObject = guildMember.guild.channels.cache.find(ch => ch.name === 'channel name here') // Gets a channel object based on it's name

awaitMessages() 还使您能够为输入必须具有的特定条件添加过滤器。 我们以新加入的成员为例。我们可以简单地告诉客户端只接受与 guildMember 对象具有相同 id 的成员的输入,因此基本上只接受新成员。

const filter = m => m.author.id === guildMember.id

现在,最后,在我们收集了所有需要的资源之后,这应该是我们等待消息的最终代码。

const channelObject = guildMember.guild.channels.cache.get('Channel ID Here');
    const filter = m => m.author.id === guildMember.id
    channelObject.awaitMessages(filter,{
        max: 1,// Requires only one message input
        time: 300000000,// Maximum amount of time the bot will await messages for
        errors: 'time' // would give us the error incase time runs out.
    })

要了解有关 awaitMessages() 的更多信息,请click here