Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

481
Views
Discord.js - Cómo cambiar el estilo del botón

Así es como creo y envío el botón:

 client.on('messageCreate', (message) => { /* ... Checking Command ... */ const actionRow = new MessageActionRow().addComponents( new MessageButton() .setStyle("PRIMARY") .setLabel("X") .setCustomId("test")); message.channel.send({ content: "Test", components: [actionRow] }); }

Aparece un botón azul en el chat, como se esperaba.

Este es mi Button-Listener:

 client.on("interactionCreate", (interaction) => { if (interaction.isButton()) { if (interaction.customId === "test") { //Before: console.log(interaction.component); interaction.component.setStyle("DANGER"); //After: console.log(interaction.component); } } });

El registro del objeto-componente antes y después de .setStyle("DANGER") también revela que el estilo se cambió de Primario a Peligro con éxito.

Pero en mi cliente de Discord, el estilo/color no cambió, y además recibo un error que dice que la interacción falló.

La propiedad de estilo no parece ser de solo lectura: https://discord.js.org/#/docs/main/stable/class/MessageButton?scrollTo=style

Entonces, ¿qué estoy haciendo mal?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Actualizaste el estilo solo localmente, no enviaste el componente cambiado a la API de Discord.

Para deshacerse del error "Esta interacción falló", debe responder a la interacción. Una forma de responder es usar MessageComponentInteraction.update() , que actualiza el mensaje original.

 client.on("interactionCreate", (interaction) => { if (interaction.isButton()) { if (interaction.customId === "test") { // Change the style of received button component interaction.component.setStyle("DANGER"); // Respond to the interaction, // and send updated component to the Discord API interaction.update({ components: [ new MessageActionRow().addComponents(interaction.component) ] }); } } });

ingrese la descripción de la imagen aquí

Para hacer que esto funcione con múltiples botones, use el siguiente ejemplo.

 client.on("interactionCreate", (interaction) => { if (interaction.isButton()) { // Make this work only for certain buttons, // with IDs like switch_0, switch_1, etc. if (interaction.customId.startsWith("switch_")) { // Change the style of the button component, // that triggered this interaction interaction.component.setStyle("DANGER"); // Respond to the interaction, // and send updated components to the Discord API interaction.update({ components: interaction.message.components }); } } });

ingrese la descripción de la imagen aquí

about 4 years ago · Juan Pablo Isaza Report

0

Para cualquier espectador futuro que pueda estar usando Discordjs V14+, ya no puede editar los componentes directamente, por lo que debe volver a crearlos para poder editarlos. ¡Esta es una solución que se me ocurrió que cambia el color cuando se hace clic!

 const collector = interaction.channel.createMessageComponentCollector({ time: 15000 }); collector.on('collect', async i => { //loop through each action row on the embed and update it accordingly let newActionRowEmbeds = i.message.components.map(oldActionRow => { //create a new action row to add the new data updatedActionRow = new ActionRowBuilder(); // Loop through old action row components (which are buttons in this case) updatedActionRow.addComponents(oldActionRow.components.map(buttonComponent => { //create a new button from the old button, to change it if necessary newButton = ButtonBuilder.from(buttonComponent) //if this was the button that was clicked, this is the one to change! if(i.component.customId == buttonComponent.customId){ //If the button was a primary button then change to secondary, or vise versa if(buttonComponent.style == ButtonStyle.Primary){ newButton.setStyle(ButtonStyle.Secondary) } else if (buttonComponent.style == ButtonStyle.Secondary){ newButton.setStyle(ButtonStyle.Primary) } } return newButton })); return updatedActionRow }); // and then finally update the message await i.update({components: newActionRowEmbeds}) });
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!