如何在discord.js中设置反应限制并存储参与者到变量?
实现Discord Ticket系统的前8位反应限制与用户存储
核心修改思路
- 用数组存储参与用户ID,避免重复计入
- 限制参与人数不超过8人
- 针对单条活动消息单独处理反应,避免全局事件冲突
修改后的完整代码
// 定义存储参与用户的数组 const participants = []; const maxPlayers = 8; const Playemoji = '🎲'; // 确保该变量已提前定义 const Players = '你的角色ID'; // 替换为实际的参与者角色ID // 创建活动Embed const Playembed = new Discord.EmbedBuilder() .setColor(0x0099FF) .setTitle(`inventors passion. host: ${message.author}`) .setDescription(`${message.author} is hosting inventors passion. if you would like to play react with 🎲!`) .setFooter({ text: `仅限前${maxPlayers}位用户参与` }); // 发送Embed并获取消息对象 const activityMessage = await channel.send({ embeds: [Playembed] }); // 给消息添加指定表情反应 await activityMessage.react(Playemoji); // 监听该消息的反应添加事件 activityMessage.on('reactionAdd', async (reaction, user) => { // 处理部分加载的消息/反应 if (reaction.message.partial) await reaction.message.fetch(); if (reaction.partial) await reaction.fetch(); // 过滤机器人、非指定表情、已参与用户 if (user.bot || reaction.emoji.name !== Playemoji || participants.includes(user.id)) return; // 检查剩余名额 if (participants.length < maxPlayers) { // 记录用户ID participants.push(user.id); // 给用户添加参与者角色 const member = await reaction.message.guild.members.fetch(user.id); await member.roles.add(Players); // 可选:更新Embed显示当前参与人数 const updatedEmbed = Playembed.setDescription( `${message.author} is hosting inventors passion. if you would like to play react with 🎲!\n已参与:${participants.length}/${maxPlayers}` ); await activityMessage.edit({ embeds: [updatedEmbed] }); } else { // 名额已满,移除用户反应并提示 await reaction.users.remove(user); // 尝试发送私信提示(忽略发送失败的情况) await user.send('名额已满,无法参与本次活动!').catch(() => null); } });
关键逻辑说明
- 用户存储:
participants数组会记录所有成功参与的用户ID,后续可直接通过该数组获取参与名单 - 名额控制:每次触发反应时先检查数组长度,小于8才执行添加角色逻辑
- 无效反应过滤:直接排除机器人、重复参与用户和非指定表情的反应,减少无效操作
- 用户反馈:名额满时自动移除用户的反应,并尝试发送私信告知结果
内容的提问来源于stack exchange,提问作者amazing mustard
相关产品推荐
相关产品推荐

