我如何给一个人在discord.js按钮的角色?



一般来说,我对discord.js和javascript很陌生,我试图制作类似于反应角色的东西,但有按钮,所以如果你点击带有角色的按钮,它会删除它,如果你没有角色,它会添加它,但我得到的问题是成员的角色是"未定义的",我没有看到关于它的文章。

代码如下:

Client.on('interactionCreate', interaction => {
if (!interaction.isButton()) return;
if (!interaction.id == "ButtonRoles") return
const users = interaction.user.id
const User2 = interaction.options.getMember(users)

console.log(User2.roles)
if (User2.roles.has("915742313525952523")) {
interaction.reply({ content: 'Successfully added role!', ephemeral: true })
User2.roles.add("915742313525952523")
}
else {
interaction.reply({ content: 'Successfully removed role!', ephemeral: true })
User2.roles.remove("915742313525952523")
}

});
Client.on("message", (message) => {
if (message.content.toLowerCase() == "-createreactionrole") {
if (message.author.bot) return;

const row = new MessageActionRow()
.addComponents(
new MessageButton()
.setCustomId('ButtonRoles')
.setLabel('Announcement Pings')
.setStyle('SUCCESS')
.setEmoji("📣"),
);   
message.channel.send({ content: 'Please press the button for the role that you would like.', components: [row] })
}
});```

所以我不得不对你的代码做一些改变,使它正常工作,我已经标记如下:

对于intent,你的代码至少应该是这样的:
const Client = new Discord.Client({
intents: ['GUILDS', 'GUILD_MEMBERS', 'GUILD_MESSAGES']
})
Client.on('interactionCreate', async interaction => {
if (interaction.isButton()) {
const buttonID = interaction.customId;
if (buttonID === 'ButtonRoles') { // get button by customId set below
const member = interaction.member; // get member from the interaction - person who clicked the button
console.log(member.roles.cache);
if (member.roles.cache.has('915742313525952523')) { // if they already have the role
member.roles.remove('915742313525952523'); // remove it
return interaction.reply({
content: 'Successfully removed role!',
ephemeral: true
});
} else { // if they don't have the role
member.roles.add('915742313525952523'); // add it
return interaction.reply({
content: 'Successfully added role!',
ephemeral: true
})
}
}
}
});
Client.on("messageCreate", async message => { // corrected your event listener should be messageCreate not message as message is deprecated
if (message.content.toLowerCase() == "-createreactionrole") {
if (message.author.bot) return;
const row = new MessageActionRow()
.addComponents(
new MessageButton()
.setCustomId('ButtonRoles')
.setLabel('Announcement Pings')
.setStyle('SUCCESS')
.setEmoji("📣"),
);
message.channel.send({
content: 'Please press the button for the role that you would like.',
components: [row]
})
}
});

最新更新