繁体   English   中英

如何获取特定频道discordjs的最后一条消息

[英]How to get the last message of a specific channel discordjs

我正在尝试获取特定频道的最后一条消息,但我无法做到这一点,我希望如果我在另一个频道(频道 1)中编写命令,该命令会给我另一个频道(频道)的最后一条消息2)。

我的代码是:

client.on('message', (message)=>{
    if(message.channel.id === '613553889433747477'){
        if(message.content.startsWith('start')){

                message.channel.fetchMessages({ limit: 1 }).then(messages => {
                    let lastMessage = messages.first();
                    console.log(lastMessage.content);
                  })
                  .catch(console.error);
        }
    }
    });

我清理了你的代码,并添加了一些解释正在发生的事情的注释。
如果您有更多问题,我建议您访问官方 Discord.js Discord 服务器。
https://discord.gg/bRCvFy9

client.on('message', message => {

  // Check if the message was sent in the channel with the specified id.
  // NOTE, this defines the message variable that is going to be used later.
  if(message.channel.id === '613553889433747477'){
    if(message.content.startsWith('start')) {

      // Becuase the message varibable still refers to the command message,
      // this method will fetch the last message sent in the same channel as the command message.
      message.channel.fetchMessages({ limit: 1 }).then(messages => {
        const lastMessage = messages.first()
        console.log(lastMessage.content)
      }).catch(err => {
        console.error(err)
      })
    }
  }
})

如果你想从另一个频道获取消息,你可以这样做。
并使用命令start #channel

client.on('message', message => {

  // Check if the message was sent in the channel with the specified id.
  if(message.channel.id === '613553889433747477'){
    if(message.content.startsWith('start')) {

      // Get the channel to fetch the message from.
      const channelToCheck = message.mentions.channels.first()

      // Fetch the last message from the mentioned channel.
      channelToCheck.fetchMessages({ limit: 1 }).then(messages => {
        const lastMessage = messages.first()
        console.log(lastMessage.content)
      }).catch(err => {
        console.error(err)
      })
    }
  }
})

可以在此处找到有关在消息中提及频道的更多信息。 https://discord.js.org/#/docs/main/stable/class/Message?scrollTo=mentions

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM