【问题标题】:Discord.js Clear command that skips pinned messagesDiscord.js 清除命令跳过固定消息
【发布时间】:2019-11-11 05:27:09
【问题描述】:

我是 JavaScript 新手,我想制作一个 Discord 机器人...我认为我的 Discord 机器人很好,但我似乎没有一个命令可以清除通道中写入的所有消息,除了固定的消息...

谁能给我一个有效的代码?

【问题讨论】:

标签: javascript discord discord.js


【解决方案1】:
  1. 要从频道中获取大量消息,请使用TextChannel.fetchMessages()
  2. 要过滤结果以仅包含未固定的消息,请在 Collection.filter() 函数中选中 Message.pinned
  3. 要一次删除所有这些消息,请使用TextChannel.bulkDelete()*

例子:

message.channel.fetchMessages({ limit: 100 })
  .then(fetched => {
    const notPinned = fetched.filter(fetchedMsg => !fetchedMsg.pinned);

    message.channel.bulkDelete(notPinned, true);
  })
  .catch(console.error);

Async/await 等效项(必须在 async function 内):

try {
  const fetched = await message.channel.fetchMessages({ limit: 100 });
  const notPinned = fetched.filter(fetchedMsg => !fetchedMsg.pinned);

  await message.channel.bulkDelete(notPinned, true);
} catch(err) {
  console.error(err);
}

*请记住,不能以这种方式删除超过 2 周的邮件。每次通话也有 2-100 条消息的限制。

【讨论】:

    【解决方案2】:

    由于我已经回答了一个非常相似的问题,所以我将重新使用我的代码。

    这种方式会比使用TextChannel.bulkDelete() 慢,但会删除超过 2 周的消息。
    正如懒惰提到的那样,为所有这些消息调用Message.delete() 将强加rate limits。 Discord.js 会为你处理它们,但你肯定会注意到它们。

    async function deleteReturnLast(chan, option, prevMsg, cond) {
      return chan.fetchMessages(option)
        .then(async msgs => {
          if (msgs.size === 0){
        if (cond(prevMsg)) {
          prevMsg.delete()
            .then(d => console.log('last message deleted: ' + d.content))
            .catch(err => console.log('ERR>>', err, prevMsg.content, option.before));   }
        return prevMsg;
          };
          let last = msgs.last();
          for (const[id, msg] of msgs) {
        let tmp = (id === last.id) ? prevMsg : msg;
        if (cond(tmp)) {
          tmp.delete()
            .then(d => console.log('Message deleted: ' + d.content))
            .catch(err => console.log('ERR>>', err));
        }
          };
          return last;
        })
        .catch(err => console.log('ERR>>', err));
    }
    
    function cond(msg) {
      return !msg.pinned;
    }
    
    client.on('message', async function(msg) {
      let chan = msg.channel;
      let last = chan.lastMessage;
      while (last !== (last = await deleteReturnLast(chan, {limit: 2, before: last.id}, last, cond))){
      };
    });
    

    【讨论】:

      猜你喜欢
      • 2022-09-30
      • 2018-08-26
      • 2021-04-14
      • 2021-07-25
      • 2021-11-16
      • 2021-04-04
      • 2020-11-02
      • 2021-03-01
      • 1970-01-01
      相关资源
      最近更新 更多