如何为提交Discord模态框的服务器成员分配角色?
如何在Discord模态框提交后为成员添加角色?
要实现审核通过后给提交模态框的成员添加角色,你需要在现有代码基础上添加按钮交互处理逻辑,同时把提交用户的ID传递到审核按钮中,具体步骤如下:
1. 修改审核按钮的自定义ID,携带提交用户ID
在创建审核按钮时,把提交模态框的用户ID拼接到按钮的customId里,这样点击按钮时就能定位到目标用户:
// 把提交用户的ID拼接到按钮自定义ID中 const buttoninvyes = new ButtonBuilder() .setCustomId(`buttoninvyes-${interaction.user.id}`) // 新增用户ID后缀 .setLabel('Принять') .setStyle(ButtonStyle.Success); const buttoninvno = new ButtonBuilder() .setCustomId(`buttoninvno-${interaction.user.id}`) // 同样处理拒绝按钮 .setLabel('отклонить') .setStyle(ButtonStyle.Danger);
2. 添加按钮交互的处理逻辑
在同一个interactionCreate事件中,新增对按钮交互的判断,解析出目标用户ID后执行添加角色的操作:
client.on('interactionCreate', async interaction => { // 优先处理按钮交互 if (interaction.isButton()) { // 拆分按钮自定义ID,获取操作类型和目标用户ID const [action, targetUserId] = interaction.customId.split('-'); // 替换为你服务器中要添加的角色ID const roleId = "你的角色ID"; const targetUser = await interaction.guild.members.fetch(targetUserId); if (action === 'buttoninvyes') { // 为用户添加角色 await targetUser.roles.add(roleId); // 给审核者发送临时反馈 await interaction.reply({content: `已为 ${targetUser.user.tag} 添加角色`, ephemeral: true}); // 给提交用户发私信通知 await targetUser.send('你的申请已通过,已为你添加对应角色!'); } else if (action === 'buttoninvno') { // 拒绝申请的反馈逻辑 await interaction.reply({content: `已拒绝 ${targetUser.user.tag} 的申请`, ephemeral: true}); await targetUser.send('你的申请未通过,如有疑问可联系管理员。'); } // 禁用审核按钮,防止重复操作 await interaction.message.edit({components: []}); return; } // 处理模态框提交逻辑(保留你原有的代码,仅修改按钮部分) if (!interaction.isModalSubmit()) return; let name = interaction.fields.getTextInputValue('nameInput'); let age = interaction.fields.getTextInputValue('ageInput'); let time = interaction.fields.getTextInputValue('timeInput'); let online = interaction.fields.getTextInputValue('onlineInput'); let bio = interaction.fields.getTextInputValue('bioInput'); const buttoninvyes = new ButtonBuilder() .setCustomId(`buttoninvyes-${interaction.user.id}`) .setLabel('Принять') .setStyle(ButtonStyle.Success); const buttoninvno = new ButtonBuilder() .setCustomId(`buttoninvno-${interaction.user.id}`) .setLabel('отклонить') .setStyle(ButtonStyle.Danger); // 将两个按钮放在同一行,优化界面展示 const buttonRow = new ActionRowBuilder().addComponents(buttoninvyes, buttoninvno); let embedinvreq = new EmbedBuilder() .setTitle('Новая завявка в Famq') .setDescription(`Данные игрока: \n Игровое имя - ***${name}*** \n Discord - ***${interaction.user}*** \n возраст - ***${age}*** \n часовой пояс - ***${time}*** \n время игры - ***${online}*** \n биография - ***${bio}***`) .setColor('LuminousVividPink') .setTimestamp(); const channelinv = "1173243142032609340"; await client.channels.cache.get(channelinv).send({embeds: [embedinvreq], components: [buttonRow]}); // 给提交用户发送提交成功的临时反馈 await interaction.reply({content: '你的申请已提交,等待管理员审核!', ephemeral: true}); });
3. 关键注意事项
- 权限配置:确保机器人拥有
管理角色权限,且机器人的角色位置高于要添加的目标角色(否则无法执行添加操作)。 - 角色ID替换:务必将代码中的
你的角色ID替换为服务器内实际角色的ID。 - 异常处理:可添加
try/catch块捕获异常(比如用户已退出服务器、机器人权限不足等情况)。
内容的提问来源于stack exchange,提问作者user21981612
相关产品推荐
相关产品推荐

