Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

480
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda