簡體   English   中英

Discord.js - 嘗試向刪除消息命令添加延遲

[英]Discord.js - Attempting to add a delay to Deleting message command

在這里編碼的新手; 我正在制作一個 discord 機器人。 我想在這個“清除消息”命令中添加一個計時器 function 以便在它繼續實際清除消息之前等待幾秒鍾,並讓用戶知道將要刪除的內容。

module.exports = {
    name: 'clear',
    description: "Clears messages",
    async execute (message, args){
        if (!message.member.hasPermission("MANAGE_MESSAGES")) return message.reply(`You can't use this command.`);
        if(!args[0]) return message.reply("Enter the amount of messages that you would like to clear.");
        if(isNaN(args[0])) return message.reply("Enter a number.");

        if(args[0] > 100) return message.reply("100 messages is the highest amount of messages you can clear.");
        if(args[0] < 1) return message.reply("1 messages is the least amount of messages you can clear.");
        
        await message.channel.messages.fetch({limit: 2 + args[0]}).then(messages =>{
            message.channel.send('Deleting '+args[0]+' messages in 5 seconds...')
            message.channel.bulkDelete(messages);
        });
    }
}

在獲取消息時,我希望它還可以獲取由鍵入命令的人發出的兩條新消息,以及機器人響應。 我嘗試在這里添加一個計時器 function :

await message.channel.messages.fetch({limit: 2 + args[0]}).then(messages =>{
            message.channel.send('Deleting '+args[0]+' messages in 5 seconds...')
            setTimeout(5000)
            message.channel.bulkDelete(messages);

但它會導致以下錯誤:

UnhandledPromiseRejectionWarning: TypeError [ERR_INVALID_CALLBACK]: Callback must be a function. Received 5000
    at setTimeout (timers.js:135:3)
    at C:\Users\ACER\Desktop\lucariobot\commands\clear.js:14:13

將 setTimeout(以及警告消息)放在await message.channel.messages.fetch function 上方也不能解決我的問題。 不知道如果它會弄亂獲取我想要刪除的消息,我將如何實現它。

setTimeout的第一個參數是在持續時間之后調用的回調(第二個參數)

例如,

await message.channel.messages.fetch({limit: 2 + args[0]}).then(messages =>{
    message.channel.send('Deleting '+args[0]+' messages in 5 seconds...')
    setTimeout(() => {
        message.channel.bulkDelete(messages);
    }, 5000)
    ...
            

作為一般說明,混合await和經典 Promise 鏈接( .then )很有趣。 就像是

// helper so you can await a setTimeout
function sleep(seconds) {
  return new Promise(r => setTimeout(r, seconds * 1000))
}


const messages = await message.channel.messages.fetch({limit: 2 + args[0]})
message.channel.send('Deleting '+args[0]+' messages in 5 seconds...')
await sleep(5) // see above
message.channel.bulkDelete(messages);

使您的代碼保持平坦,並且 imo 更具可讀性。

暫無
暫無

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

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