【问题标题】:How do I Get the Client User's Last Message?如何获取客户端用户的最后一条消息?
【发布时间】:2017-12-25 16:18:38
【问题描述】:

您将如何获取机器人最后一条消息的对象?我尝试做类似的事情:

if (message.content.split(' ')[0] === 'test') {
   message.channel.sendMessage('Test')
   console.log(client.user.lastMessage.content)
}

如果我触发条件,控制台会给我一个错误:TypeError: Cannot read property 'content' of undefined

【问题讨论】:

  • 该错误意味着client.user.lastMessage 未定义。这意味着可能没有 lastMessage(因为请记住,从技术上讲,消息仍然可以发送,因为 nodeJS 是非阻塞的),或者可能 lastMessage 属性是错误的
  • 所以 node.js 在继续下一个命令之前不会等待线程完成?如果是这样,我尝试使用 setTimeout() 等待 3 秒,然后再将消息记录到控制台中。有没有办法在消息继续执行之前检测消息的实际发送时间?
  • 回调。 sendMessage(String) 是否会重载回调参数?
  • 我的意思是我建议只尝试 console.log(client.user),看看是否有 lastMessage 参数或 getter
  • 啊。 lastMessage 变量在对象中根本不存在。 lastMessageID 也是 null。是否有另一种方法来设置 client.user.lastMessage 对象,因为它似乎没有处于 read-only 模式?

标签: javascript node.js discord discord.js


【解决方案1】:

client.user.lastmessage 的值是null 的原因是您刚刚启动机器人,并且在您运行'test' 命令之前它没有发送任何消息。

为了解决这个问题,我会检查它是否为空(如果不是),如果它,请使用MessageCollector 并等待您的消息发送出去。

    if (client.user.lastMessage == null) {
        // Set the collector for the same channel
        // Ensure the id is the same
        var myID = client.user.id;
        // Create collector and wait for 5 seconds (overkill but you never know with bad internet/lots of traffic)
        const collector = new Discord.MessageCollector(msg.channel, m => m.author.id === myID, { time: 5000 });
        collector.on('collect', message => {
            console.log(message.content);
            collector.stop("Got my message");
        });
    } else {
        console.log(client.user.lastMessage.content);
    }

我测试的确切代码块:

    client.on('message', msg => {
        if (msg.content === '$ping') {
            msg.reply("Pong!")
            if (client.user.lastMessage == null) {
                const collector = new Discord.MessageCollector(msg.channel, m => m.author.id === client.user.id, { time: 10000 });
                collector.on('collect', message => {
                    console.log(message.content);
                    collector.stop("Got my message");
                })
            } else {
                console.log(client.user.lastMessage.content);
            }
        }
    }

【讨论】:

  • 我在让机器人发送消息后执行了您的代码 sn-p,但它从不向控制台输出任何内容。
  • @Meh 这对我有用吗?查看我的编辑,了解我测试过的确切代码块
  • 我更新了 discord.js 库,它看起来很有效。显然,我使用的版本是 2017 年 1 月的。
猜你喜欢
  • 2021-02-03
  • 2021-03-13
  • 1970-01-01
  • 1970-01-01
  • 2019-03-31
  • 2018-01-15
  • 2013-06-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多