I'm currently learning how to use Discords Buttons but I ran into a problem. The following code should create a button with the command /startgame, when you press this button it should just say "hello".
const { SlashCommandBuilder } = require("@discordjs/builders")
const { MessageButton, MessageActionRow } = require("discord.js")
module.exports ={
data: new SlashCommandBuilder()
.setName("startgame")
.setDescription("Startet das Spiel"),
async execute(interactionCreate) {
if (interactionCreate.isCommand()) {
const row1 = new MessageActionRow()
.addComponents(
new MessageButton()
.setCustomId("start")
.setLabel(" Start ")
.setStyle(3)
.setDisabled(false),
)
await interactionCreate.reply({content: " ", components: [row1]})
}
else if(interactionCreate.isButton()) {
switch (interactionCreate.customId) {
case "start": {
return interactionCreate.reply("hello")
}
}
}
}
}
It creates the button, but when you press it, it only says: This interaction failed I appreciate any help.
OK so one of these parts should be under your event listener interactionCreate rather than in a command. So if you have that section in your main bot.js file it would look like this:
Command File
const {
SlashCommandBuilder
} = require("@discordjs/builders")
const {
MessageButton,
MessageActionRow
} = require("discord.js")
module.exports = {
data: new SlashCommandBuilder()
.setName("startgame")
.setDescription("Startet das Spiel"),
async execute(interaction) {
const row1 = new MessageActionRow()
.addComponents(
new MessageButton()
.setCustomId("start")
.setLabel(" Start ")
.setStyle(3)
)
return interaction.reply({
components: [row1]
})
}
}
bot.js file - could be named whatever you named it
client.on('interactionCreate', async interaction => {
if (interaction.isButton()) {
const buttonID = interaction.customId
if (buttonID === 'start') {
interaction.reply({
content: 'Hello'
})
}
}
})