Create a Discord.JS V13 Button
How to create a button in Discord.JS V13.
Created by / Mohammad Hajjiri
Many people have been confused on how to create a Discord.JS Button at the release of Discord.JS V13, whereas due to that, I'm more than happy to share with you guys on how to create a simple button and how you could easily interact with it.
This code is a code for a slash command (/
), and not a message command (prefix like !
). You must have a slash-command handler for this code to work or else it will NOT work.
Let us first start by requiring the necessary classes in Discord.JS which are MessageEmbed()
, MessageActionRow()
, and MessageButton()
, using this code:
const { MessageEmbed, MessageActionRow, MessageButton } = require('discord.js');
Afterwards, let's create the code for the message + the button. In this case, we will be using collectors!
const embed = new MessageEmbed()
.setColor(black)
.setDescription(`Press the button for a cookie. 🍪`)
const row = new MessageActionRow()
.addComponents(
new MessageButton()
.setCustomId('cookie')
.setLabel('🍪')
.setStyle('PRIMARY')
);
const m = await interaction.followUp({ embeds: [embed], components: [row] });
const filter = (int) => int.message.id === m.id && int.user.id === interaction.member.id;
const collector = interaction.channel.createMessageComponentCollector({ filter, max: 1, componentType: 'BUTTON', time: 15000 });
collector.on('end', async (ButtonInteraction) => {
ButtonInteraction = ButtonInteraction.first();
if (!ButtonInteraction) {
row.components[0].setDisabled(true);
return await interaction.editReply({ components: [row] })
} else {
switch (ButtonInteraction.customId) {
case 'cookie':
embed.setDescription('A cookie for you. 🍪');
return await ButtonInteraction.update({ embeds: [embed], components: [] });
break;
};
};
});
Lastly, try out the command, and you have, successfully, created your first Discord.JS button!