如何获得另一个频道Discord.js的最后一条消息

时间:2019-08-22 17:01:46

标签: javascript node.js discord.js

好吧,我一直在尝试获取一个通道的最后一条消息,该消息是在另一个通道中编写命令的,就像这样:

频道1 :(我写)“获取频道2的最后一条消息 频道2:最后一条消息是(“ Hello”); 频道1:我收到频道2的最后一条消息,说,频道2的最后一条消息为。 “你好”。

我这样做了,但是没有用。

 if (message.channel.id === '613573853565681671') {
   message.channel.fetchMessages().then(collected => {
     const filtered = collected.filter(message => message.author.bot);
     const lastMessages = filtered.first(1); //Get the last message of this channel.
     const TextMessages = `${lastMessages[0].content}`;
     console.log(TextMessages + " is the last message of aviso jobs")

     if (TextMessages === "look") { //If the last message of this channel is look then go to the other channel

       if (message.channel.id === '613553889433747477') {
         message.channel.fetchMessages().then(collected => {
           const filtered = collected.filter(message => message.author.bot);
           const lastMessages2 = filtered.first(1); //Get the last message of this other channel.
           const TextMessages2 = `${lastMessages2[0].content}`;
           console.log(TextMessages2 + " is the last message of bot")
         });
       }
     }
   });
 }

但是这不起作用,这只会给我第一个频道的最后一条消息,而不是第二个频道。

1 个答案:

答案 0 :(得分:0)

我在理解您的代码时遇到了麻烦,因此这是我的处理方式,也许会对您有所帮助:

  if (message.content.startsWith("!lastmessage")) {
    let args = message.content.split(" "); //find every word of the message
    if (args.length > 1) { //make sure that there is at least 1 argument, which should be the target channel's id
      let target = message.guild.channels.find(c => c.id == args[1]) || null; // find the targeted channel
      if (target) { // make sure that the targeted channel exists, if it exists then fetch its last message
        target
          .fetchMessages({ limit: 1 })
          .then(f =>
            message.channel.send(
              `Last message from <#${target.id}> is...\n> ${f.first().content}`
            ) // send the last message to the initial channel
          );
      } else { //if target doesn't exist, send an error
        message.channel.send("Target does not exist!");
      }
    }
  }