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

Discord按钮权限开发报错Cannot read property 'roles' of undefined求助

问题原因
  • 错误的属性调用:Discord.js 中 interaction.user 是全局用户对象,仅包含用户名、ID 等通用用户属性,不存在 guild 字段,因此 interaction.user.guild 返回 undefined,读取 undefined.roles 就会触发你遇到的类型错误。
  • 身份组校验逻辑错误:你当前的代码只是校验服务器是否存在名为Staff的身份组,没有校验触发交互的用户是否持有该身份组,就算修复了属性错误也达不到你要的权限控制效果。
  • 拼写错误:代码中的ephmeral为错误拼写,正确写法是ephemeral,拼写错误会导致仅自己可见的消息属性失效。
  • 交互响应逻辑缺陷:如果没有提前调用interaction.deferReply()延迟响应,直接使用interaction.followUp()会抛出无响应对象的错误,需要根据你的前置逻辑调整响应方法。
解决方案

你需要先从交互对象中获取服务器实例和当前用户的服务器成员实例,再做权限校验,同时将重复的校验逻辑抽离简化,修正后的代码如下:

collector.on('collect', async interaction => {
  // 先判断交互是否在服务器内触发,避免DM场景报错
  if (!interaction.inGuild()) {
    return interaction.reply({ content: "该功能仅可在服务器内使用", ephemeral: true });
  }
  // 1. 从服务器实例获取Staff身份组
  const wikiStaffRole = interaction.guild.roles.cache.find(role => role.name === "Staff");
  if (!wikiStaffRole) {
    return interaction.reply({ content: "服务器未配置Staff身份组,功能暂不可用", ephemeral: true });
  }
  // 2. 校验当前用户是否持有Staff身份组
  const hasStaffPermission = interaction.member.roles.cache.has(wikiStaffRole.id);
  if (!hasStaffPermission) {
    // 若你提前调用了deferReply,请将此处reply替换为followUp
    return interaction.reply({ content: `${interaction.user} dude you need to be a staff member`, ephemeral: true });
  }
  // 权限校验通过后再处理对应按钮逻辑
  let replyContent = '';
  if (interaction.customId === "yes") {
    replyContent = 'This report has been marked as completed.';
  } else if (interaction.customId === "no") {
    replyContent = 'This report has been denied.';
  } else if (interaction.customId === "what") {
    replyContent = 'This report has been marked as inconclusive.';
  }
  newUserEmbed.edit({ embeds: [], content: replyContent, components: [] });
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 21:39:01