【发布时间】:2020-04-15 19:16:27
【问题描述】:
我正在使用 Discord.js 编写一个 Discord 机器人,并且我正在尝试创建一个 .clear 命令来清除消息。问题是我无法删除消息,因为我在尝试使用 bulkDelete 时收到了await is only valid in async function。我在bot.on('message', msg => { 部分对此进行了编码。这是我的代码:
if (msg.content.startsWith('.clear')) {
if(msg.member.hasPermission('MANAGE_MESSAGES')) {
const args = msg.content.split(' ').slice(1);
const amount = args.join(' ');
if(!amount) {
const noNumbers = new Discord.RichEmbed()
.setColor('#0099ff')
.setDescription(':no_entry: Vous n\'avez pas précisé combien de messages devraient être supprimés !')
msg.channel.send(noNumbers)
}
if(isNaN(amount)) {
const notNumber = new Discord.RichEmbed()
.setColor('#0099ff')
.setDescription(':no_entry: Ce paramètre n\'est pas un nombre !')
msg.channel.send(notNumber)
}
if(amount > 100) {
const tooMuch = new Discord.RichEmbed()
.setColor('#0099ff')
.setDescription(':no_entry: Vous ne pouvez pas supprimer plus de 100 messages à la fois !')
msg.channel.send(tooMuch)
}
if(amount < 1) {
const tooLess = new Discord.RichEmbed()
.setColor('#0099ff')
.setDescription(':no_entry: Vous ne pouvez pas supprimer moins d\'un message !')
msg.channel.send(tooLess)
}
else {
await msg.channel.messages.fetch({limit: amount}).then(messages => {
msg.channel.bulkDelete(messages)
});
}
}
}
谢谢! (不要介意嵌入描述,我是法国人)
【问题讨论】:
-
既然已经使用
then语法,为什么还要使用await? -
@Bergi 如果他返回的承诺本身返回一个新的承诺,这是合法的。但是,您是对的,还不如再链接另一个。我实际上认为这个函数不需要使用异步等待。如果它返回一个值,它可能更容易阅读,但您基本上是将操作推迟到消息获取完成之后。
标签: javascript async-await discord