【问题标题】:Discord.js - Attempting to add a delay to Deleting message commandDiscord.js - 尝试为删除消息命令添加延迟
【发布时间】:2021-08-28 16:10:32
【问题描述】:

这里是编码新手; 我正在制作一个不和谐的机器人。 我想在这个“清除消息”命令中添加一个计时器功能,以便在它继续实际清除消息之前等待几秒钟,并让用户知道将要删除的内容。

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);
        });
    }
}

在获取消息时,我希望它还获取由键入命令的人发出的两条新消息,以及机器人响应。 我尝试在这里添加一个计时器功能:

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 函数上方也不能解决我的问题。 不知道如果它会弄乱获取我想要删除的消息,我将如何实现它。

【问题讨论】:

    标签: javascript discord


    【解决方案1】:

    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 更具可读性。

    【讨论】:

      猜你喜欢
      • 2018-08-26
      • 2021-07-25
      • 2022-09-28
      • 2022-09-30
      • 1970-01-01
      • 2020-11-02
      • 2021-12-08
      • 2017-07-31
      • 1970-01-01
      相关资源
      最近更新 更多