discord.js clearr指令如何限制仅接受数字输入并提示非法值
修复后完整代码
module.exports = { name: 'clearr', description: "Clear messages!", async execute(client, message, args) { if(!args[0]) { // 若需要保留仅固定ID用户可使用的权限,可改回原filter的固定ID写法 let filter = m => m.author.id === message.author.id message.channel.send(`How many messages do you want to delete?`).then(() => { message.channel.awaitMessages(filter, { max: 1, time: 10000, errors: ['time'] }) .then(collected => { const replyMsg = collected.first() const deleteCount = parseInt(replyMsg.content.trim()) // 校验是否为有效数字,且符合discord bulkDelete接口1-100条的数量限制 if (isNaN(deleteCount) || deleteCount < 1 || deleteCount > 100) { return replyMsg.channel.send("Not an appropriate value") .then(msg => msg.delete({timeout: 5000})) .catch(console.error) } // 第二个参数true表示自动过滤14天以上无法删除的消息,避免接口报错 replyMsg.channel.bulkDelete(deleteCount, true) .then(() => { replyMsg.channel.send (`\`${deleteCount} message\` successfully deleted!`) .then(msg => { msg.delete({ timeout: 5000 }) }) }) .catch(console.error); }) // 超时未回复处理,不需要可以直接删除这段catch .catch(() => { message.channel.send("Request timed out, please try again.") .then(msg => msg.delete({timeout: 5000})) }) }) } } }
核心修改说明
- 新增输入校验逻辑:提取用户回复的内容转为整数,校验是否为1-100之间的有效正整数,不符合要求直接返回指定错误提示
- 修正
bulkDelete入参:原代码直接传入用户回复的消息对象,改为传入校验后的删除数量,符合接口参数要求 - 优化变量命名:把收集到的用户回复变量从
message改为collected,避免和外层触发指令的message变量重名导致逻辑异常 - 可选优化:过滤器默认改为匹配触发指令的用户,所有用户都可以正常使用该指令,需要保留权限限制可改回原有固定ID的写法
内容的提问来源于stack exchange,提问作者user17263435
相关产品推荐
相关产品推荐

