繁体   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