Discord.js如何禁止用户在响应命令提问未结束时执行其他命令
方案失效的核心原因
你之前用全局isActive变量的方案逻辑方向正确,但存在两个核心问题导致失效:
- 全局状态会让所有用户互斥,只要有一个用户正在交互,全服用户都无法使用命令,且如果交互过程中代码抛出异常没有复位状态,会导致全局永久锁死
- 没有区分用户维度的状态,同一个用户触发交互后,他发的其他命令依然会被全局
message监听器捕获执行
修复步骤
步骤1:定义用户维度的交互锁
在代码全局位置定义一个Set结构,用于存储当前正在交互流程中的用户ID:
// 全局位置定义,存储处于交互中的用户ID const interactingUsers = new Set();
步骤2:修改命令入口拦截逻辑
将两个命令的入口判断统一添加拦截逻辑,正在交互中的用户发送的命令直接忽略:
原来的入口判断:
if (!message.content.startsWith(prefix) || message.author.bot) return;
修改为:
if (!message.content.startsWith(prefix) || message.author.bot || interactingUsers.has(message.author.id)) return;
步骤3:命令启动时加锁
在进入对应命令逻辑的第一行,将当前用户加入锁集合:
盒子游戏命令加锁:
if (command === "b" || command === "box") { interactingUsers.add(message.author.id); // 新增加锁逻辑 // 原有代码不变 }
商店命令加锁:
if (command === "store") { interactingUsers.add(message.author.id); // 新增加锁逻辑 // 原有代码不变 }
步骤4:所有交互结束分支解锁
在每个命令的所有退出分支(正常结束、输入错误、超时、报错等所有场景)都将用户从锁集合中移除,推荐用try/finally兜底避免漏写:
盒子游戏解锁示例
用try包裹原有box命令的所有逻辑,finally块统一解锁:
if (command === "b" || command === "box") { interactingUsers.add(message.author.id); try { // 原有box命令的所有代码放在这里 } finally { interactingUsers.delete(message.author.id); } }
商店命令解锁示例
除了try/finally兜底,还要在异步收集器的所有结束分支补充解锁:
if (command === "store") { interactingUsers.add(message.author.id); try { message.channel.send(`╭⋟────────────────────────╮ ──•~ Type the product code (number) to buy it. ✦✧✦✧ STORE » 1 - Green Seed: 0 coins. ╰────────────────────────⋞`) message.channel.awaitMessages(m => m.author.id == message.author.id, {max: 1, time: 10000}).then(collected => { if (collected.first().content.toLowerCase() == '1') { message.reply(`You bought 1 "Green seed" with success!`); seedGreen++; seedTotal++; } else { message.reply(`Something happened, and it wasn't possible to complete your order..`); } }).catch(() => { message.reply('Your order was cancelled due to lack of response.'); }).finally(() => { // 收集器结束后统一解锁 interactingUsers.delete(message.author.id); }); } catch (e) { // 报错兜底解锁 interactingUsers.delete(message.author.id); } }
修改后,用户进入任意交互流程时,发送的其他带前缀命令都会被直接拦截,不会触发其他命令执行。
内容的提问来源于stack exchange,提问作者user15882013
相关产品推荐
相关产品推荐

