如何使用Express发送最新的消息ID?

时间:2020-05-21 05:07:42

标签: node.js express discord.js

我有以下代码,当我运行它时,出现此错误:

TypeError: Cannot read property 'first' of undefined

我正在使用discord.js v12.0.2,并表达了v4.16.2
这是我的代码:

app.get("/last", function(req, res) {
  res.header("Access-Control-Allow-Origin", "*")
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")

  res.send(String(client.channels.cache.get('540281078213246998').messages.fetch({ limit: 1 }).messages.first().id))
})

我正在尝试获取Discord频道中最后一封邮件的ID。

2 个答案:

答案 0 :(得分:1)

当您使用MessageManager.fetch()时,它将返回一个Promise,该Promise用MessageCollection的消息来解决;这意味着您必须:

  • 等待实现诺言
  • 检查是否已返回收藏集(这种情况在您的情况下永远都不会发生,但我还是会介绍)
  • 从消息中获取ID

这是我的处理方式:

client.channels.cache.get('540281078213246998').messages.fetch({ limit: 1 }).then(msg => {
  if (msg instanceof Map) // If the function returned a Collection...
    msg = msg.first() // ...set it to the first value.

  res.send(msg.id)
})

答案 1 :(得分:0)

易于解决, messageCollection#fetch返回Promise,因此您需要在其中等待或使用.then函数。