首页 > 解决方案 > 如何在 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() 处理的承诺。要在未处理的 Promise 拒绝时终止节点进程,请使用 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.

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

标签: discord.jsdm

解决方案


以下是关于 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()请单击此处


推荐阅读