Discord机器人按钮交互报错:Cannot read properties of undefined (reading 'cache')
解决Discord机器人按钮点击时角色判断的TypeError问题
错误原因
报错Cannot read properties of undefined (reading 'cache')是因为你用了interaction.user.roles——Discord的User对象没有roles属性,只有GuildMember(服务器成员)对象才有roles缓存,而interaction.member才是当前用户在服务器中的成员实例。
另外你的代码还有个隐藏问题:logchannel是if/else代码块里的局部变量,在块外调用logchannel.send()会直接报错未定义,得提前声明变量。
修复后的代码
if (interaction.customId === "button_one") { responseembed.description = `\u200b\n**${config.responses.response_1}**\n\u200b\n` // 提前声明logchannel变量,避免作用域问题 let logchannel; // 改用interaction.member获取服务器成员的角色缓存 if (interaction.member.roles.cache.has(config.lspd_role_id)) { logchannel = interaction.guild.channels.cache.get(config.lspd_channel_id) } else if (interaction.member.roles.cache.has(config.lssd_role_id)) { logchannel = interaction.guild.channels.cache.get(config.lssd_channel_id) } // 增加边界判断,避免无对应角色时logchannel未定义报错 if (logchannel) { logchannel.send({ embeds: [PriseService], ephemeral: false }) } // let invitecutie = new MessageButton() // .setLabel("Invite Link") // .setStyle("url") // .setURL("Link") // let buttonRow = new MessageActionRow() // .addComponent(invitecutie) //!If You Want Button in the Response remove // from the the Above 6 lines return interaction.reply({ embeds: [responseembed], ephemeral: true })//If you want to send link button add ,component: buttonRow after the ephermeral: true declaration }
额外注意事项
- 确保你的机器人有
GUILD_MEMBERS权限,不然可能无法获取成员角色信息 - 如果是在DM中触发的按钮交互,
interaction.member会是undefined,建议提前判断交互是否在服务器内:if (!interaction.guild) return interaction.reply('此操作仅能在服务器内使用')
内容的提问来源于stack exchange,提问作者arthur hubaud
相关产品推荐
相关产品推荐

