【问题标题】:Trying to fetch 5 messages and then react to them - discord.js尝试获取 5 条消息然后对它们做出反应 - discord.js
【发布时间】:2021-04-11 14:24:59
【问题描述】:

我正在尝试从一个频道获取 5 条以前的消息,然后使用 discord.js 对它们做出反应

message.channel.messages.fetch(channelID).then(channel => {
            channel.messages.fetch({limit : 5}).then(message => {
                message.react("✅");
            })
        })

我得到的错误:UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'messages' of undefined

【问题讨论】:

    标签: javascript discord.js fetch message


    【解决方案1】:

    您的代码中有两个问题(其中一个似乎有些人在这里忽略了)。

    您的第一个错误出现在以下行中,说明:

    message.channel.messages.fetch(channelID).then(channel => {
    

    Channel#messages#fetch() 方法返回的不是 Channel 对象,而是消息对象。由于您正在尝试从 channel 对象中获取消息,因此您应该获取的是频道而不是消息。尝试用以下内容替换您的行:

    client.channels.fetch(channelID).then(channel => { ... }
    

    第二个问题是,当您在 Discord.js 中获取多个消息时,该方法返回一个对象集合,而不是一个对象。与常规的单个消息对象不同,消息对象的集合没有react() 方法属性,应使用forEach() 迭代器将其拆分,以在每条消息之间分别添加反应,如下所示:

    client.channels.fetch(channelID).then(channel => {
      channel.messages.fetch({ limit: 5 }).then(messages => {
        messages.forEach(async message => {
          await message.react('✅') // It is recommended to await a reaction method before going on to the next one.
        })
      })
    })
    

    【讨论】:

    • 谢谢谢谢谢谢!你解决了我的问题!
    • @AlexCh 没问题!您介意将我的答案标记为正确,以便其他人也能发现它有用吗?
    【解决方案2】:

    考虑到您已经将频道作为消息属性,您应该执行以下操作:

    message.channel.messages.fetch({ limit: 5 }).then(message => {
        message.react("✅");
    })
    

    【讨论】:

    • 你好,感谢您的回答,我仍然遇到同样的错误,我已经在这里初始化了我的频道let channel = guild.channels.cache.find(ch => ch.id == <id>);
    • 能否请您记录 channel 变量以查看是否正确找到它?
    • 好吧,看来频道找到正确了。消息也一样。您能否更新问题描述,因为您在上一条评论中编写的代码与您在原始问题中发布的代码有很大不同?
    【解决方案3】:

    问题是MessageManager#fetch() 返回所有获取消息的集合(映射)。您正在尝试直接在本质上是多条消息列表上调用.react()。使用.forEach() 对每条消息做出反应。

    message.channel.messages.fetch(channelID).then(channel => {
                channel.messages.fetch({limit : 5}).then(messages => {
                    messages.forEach(msg => {
                       msg.react('✅')
                    })
                })
           })
    

    Documentation for MessageManager#fetch()

    【讨论】:

      猜你喜欢
      • 2021-05-26
      • 2021-06-24
      • 2021-07-27
      • 2021-05-14
      • 1970-01-01
      • 1970-01-01
      • 2020-12-10
      • 2018-04-03
      • 1970-01-01
      相关资源
      最近更新 更多