javascript - Discord.js - 尝试向删除消息命令添加延迟
问题描述
在这里编码的新手;我正在制作一个不和谐的机器人。我想在这个“清除消息”命令中添加一个计时器功能,以便在它继续实际清除消息之前等待几秒钟,并让用户知道将要删除的内容。
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函数上方也不能解决我的问题。不知道如果它会弄乱获取我想要删除的消息,我将如何实现它。
解决方案
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 更具可读性。
推荐阅读
- c# - 从 .NET 探查器访问 ThreadStatic 字段
- dart - 如何在 PreferredSizeWidget 中垂直居中 Widget
- c# - Unity OnTriggerEnter2D
- gradle - 插件块方法从何而来?
- postgresql - PostgreSQL 可以创建的用户数
- pip - 是否可以将 python 二进制扩展打包到针对不同硬件的轮子中?
- python - 创建集合的 Python 性能比较 - set() 与 {} 文字
- c - 结构如何分配内存?
- spring - 使用 mssql 的 Windows 身份验证连接到 localhost 的问题
- function - 如何从代码编译代码