簡體   English   中英

我的 Discord.JS 代碼有一個奇怪的錯誤,你能幫我解決這個問題嗎?

[英]My code for Discord.JS is having a strange error, can you please help me solve this?

出於某種原因,當我鍵入帶有多個數字的清除命令時,它會給出錯誤“DiscordAPIError:未知消息”(查看圖像以獲取完整錯誤),您能幫忙解決這個問題嗎? 我懷疑是因為這些函數已經被聲明了,所以第二次會感到困惑。

錯誤圖片:

在此處輸入圖像描述

順便說一下,這是我的命令代碼:

 if (msg.content.startsWith("$purge")) {
        if (msg.content.match(/\d+/)) {
            if (isNaN(Number(msg.content.split(' ')[1])) == false) {
                channel = msg.channel
                msg.delete()
                for (f = 1; f <= Number(msg.content.split(' ')[1]); f++) {
                    msg.channel.messages.fetch().then(e => {
                        e.every(function (value) {
                            if (value.deleted == false) {
                                message = value;
                            }
                        })
                        message.delete()
                    })
                }
            }
            else {
                if (isNaN(Number(msg.content.split(' ')[1])) == true) {
                    msg.channel.send("Please include an amount of messages to purge in the right place")
                }
                
            }
        }
        else {
            if (!msg.content.match(/\d+/)) {
                msg.channel.send("Please include an amount of messages to purge")
            }
            
        }
        
        
    }

編輯:我意識到發生了什么,仍然不知道如何在不使用 bulkDelete() 的情況下修復它

問題來自這部分:

msg.channel.messages.fetch().then((e) => {
  e.every(function (value) {
    if (value.deleted == false) {
      message = value;
    }
  });
  message.delete();
});

messages.fetch()返回一個 promise ,當它解析消息集合時(您將其命名為e )。 您嘗試檢查每條消息是否都有已deleted的屬性,如果沒有,您只需將消息分配給(全局?) message變量。 當您以異步方式在 for 循環中工作時,您要刪除的消息可能已經被刪除。

discord.js 中有一個bulkDelete()方法,您可以將其用於清除命令。 您只需提供要在頻道中刪除的消息數量,它會執行 rest:

channel.bulkDelete(5)
  .then(messages => console.log(`Bulk deleted ${messages.size} messages`))
  .catch(console.error);

您可以像這樣簡化代碼:

const prefix = '$';
// remove the prefix and split by spaces
const args = msg.content.slice(prefix.length).split(/ +/);
// remove the command from the args array
const command = args.shift().toLowerCase();

if (command === 'purge') {
  if (isNaN(args[0])) {
    return msg.channel.send(
      'Please include an amount of messages to purge in the right place',
    );
  }
  // add an extra to delete the last message with the purge command too
  const amount = Number(args[0]) > 100 ? 101 : Number(args[0]) + 1;

  msg.channel.bulkDelete(amount, true)
  .then((_message) => {
    console.log(`Bot cleared ${_message.size}messages`);
  });
}

channel.bulkDelete(5).then(messages => console.log( Bulk deleted ${messages.size} messages )).catch(console.error);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM