You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Discord.js v13 如何为添加反应的用户分配角色(附现有嵌入与反应代码)

如何在Discord.js中实现点击反应分配角色的功能

我来帮你在现有代码基础上搞定这个功能!核心思路是给你发送的规则消息添加一个反应收集器,专门监听用户的✅反应,然后自动给对应用户分配指定角色。下面是修改后的完整代码,我会把关键改动的地方标出来:

if (message.content.startsWith(`${prefix}rr`)) {
  // 第一步:定义你要分配的目标角色(替换成你服务器里的角色名称)
  const verifyRole = message.guild.roles.cache.find(role => role.name === "已验证");
  if (!verifyRole) {
    return message.reply("找不到指定的角色,请检查角色名称是否正确!");
  }

  let embed = new MessageEmbed()
    .setColor("#ffffff")
    .setTitle("📌 Our Servers Rules 📌")
    .setDescription("To keep our server safe we need a few basic rules for everyone to follow!")
    .setFooter("Please press ✅ to verify and unlock the rest of the server!")
    .addFields(
      { name: "1.", value: "Stay friendly and don't be toxic to other users, we strive to keep a safe and helpful environment for all!", },
      { name: "2.", value: "Keep it PG-13, don't use racist, homophobic or generally offensive language/overly explicit language!", },
      { name: "3.", value: "If you want to advertise another server/website etc please contact me first!", },
      { name: "4.", value: "Don't cause drama, keep it civil!" },
      { name: "5.", value: "If you have any questions please contact me @StanLachie#4834", }
    );

  message.channel.send({ embeds: [embed] }).then((sentMessage) => {
    sentMessage.react("✅");

    // 第二步:创建反应收集器,只监听这条消息的✅反应
    const filter = (reaction, user) => {
      return reaction.emoji.name === "✅" && !user.bot; // 排除机器人的反应,避免误触发
    };

    const collector = sentMessage.createReactionCollector({ filter, time: 86400000 }); // 收集器有效期1天,可自行调整时长

    // 第三步:处理收集到的反应,给用户分配角色
    collector.on("collect", (reaction, user) => {
      // 获取用户的服务器成员对象
      const member = message.guild.members.cache.get(user.id);
      if (member) {
        member.roles.add(verifyRole)
          .then(() => {
            console.log(`已给用户 ${user.tag} 分配角色 ${verifyRole.name}`);
            // 可选:给用户发送私信提示
            user.send(`你已成功验证,获得了 ${verifyRole.name} 角色!`).catch(err => console.log("无法发送私信给用户"));
          })
          .catch(err => {
            console.error("分配角色失败:", err);
            message.reply(`无法给用户 ${user.tag} 分配角色,请检查机器人权限!`);
          });
      }
    });

    // 可选:收集器结束时的日志提示
    collector.on("end", collected => {
      console.log(`反应收集器已结束,共收集到 ${collected.size} 次有效反应`);
    });
  });
}

关键部分说明:

  • 角色获取:先通过角色名称找到目标角色,如果找不到直接报错提示,避免后续逻辑出错;也可以用角色ID查找(更稳定):message.guild.roles.cache.get("角色ID")
  • 反应过滤器:确保只处理✅的反应,并且忽略机器人的操作,防止无效触发
  • 反应收集器:绑定到你发送的规则消息上,设置了1天的有效期,你可以根据需要调整时长,或者去掉time参数让收集器一直生效
  • 角色分配逻辑:获取用户的服务器成员对象,调用roles.add()分配角色,同时处理成功和失败的情况,方便调试和给用户反馈

注意事项:

  • 确保你的机器人拥有管理角色的权限,并且机器人的角色位置要高于你要分配的角色,否则无法完成角色添加操作

内容的提问来源于stack exchange,提问作者StanLachie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 22:47:51