【问题标题】:Input From Single User on Discord.jsDiscord.js 上单个用户的输入
【发布时间】:2020-10-06 18:42:35
【问题描述】:

我希望能够获得用户的响应。问题是我不知道如何确保我得到特定用户的响应而不是其他人的响应。我怎么能做到这一点? 例如询问最小和最大数字,然后从它们之间获取一个随机数。

这是我尝试过的:

const Discord = require('discord.js');


const client = new Discord.Client();

const prefix = '-';

client.on('message', message => {
    if(!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();


if(command === random) {
    message.channel.send('Please enter your starting number')
    channel.fetchMessages({ limit: 1 }).then(messages => {
        let min = messages.first();
    })
    message.channel.send('Please enter your limit')
    channel.fetchMessages({ limit: 1 }).then(messages => {
        let max = messages.first();
    })

    getRndInteger(min,max)

    function getRndInteger(min, max) {
        console.log(Math.floor(Math.random() * (max - min + 1) ) + min); 
      }

    
}

});

我希望它等到激活它的用户说出一个数字(它也可能有超时)。

【问题讨论】:

    标签: node.js discord discord.js


    【解决方案1】:

    您可以使用Channel.createMessageCollector() 等待目标用户回复,这是一个简单的示例:

    let min, max;
    const filter = (msg) => msg.author.id === message.author.id; // only match messages from whoever sent the command
    const collector = message.channel.createMessageCollector(filter, { max: 2 });
    collector.on("collect", (m) => {
      if(!min) { // if min hasn't already been set, set it
        min = parseInt(m.content);
      } else { // otherwise set max
        max = parseInt(m.content);
      }
    });
    collector.on("end", () => {
      getRndInteger(min, max);
    });
    

    还有其他方法可以解决这个问题,但我认为这是最直接的,因为否则您将需要多个侦听器。

    【讨论】:

    • 它的意思是`ReferenceError: getRndInteger is not defined`
    • 您好,这是由于在定义之前尝试使用getRndInteger() 造成的。要解决此问题,您必须在调用之前将function getRndInteger(min, max) { ... } 放在某处。最好在消息监听器之外定义函数。
    猜你喜欢
    • 2021-02-08
    • 2020-12-21
    • 1970-01-01
    • 2021-04-29
    • 2021-04-18
    • 1970-01-01
    • 2021-07-16
    • 1970-01-01
    • 2021-07-27
    相关资源
    最近更新 更多