gpt4 book ai didi

javascript - Discord.js - 如何改变按钮的样式

转载 作者:行者123 更新时间:2023-12-02 18:36:05 24 4
gpt4 key购买 nike

这就是我创建和发送按钮的方式:

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] });
}

如预期的那样,聊天中会出现一个蓝色按钮。

这是我的按钮监听器:

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);
}
}
});

.setStyle("DANGER") 之前和之后记录组件对象还显示,样式已成功从 Primary 更改为 Danger。

但在我的 Discord 客户端中,样式/颜色没有改变,除此之外我还收到一个错误,说交互失败。

样式属性似乎不是只读的:https://discord.js.org/#/docs/main/stable/class/MessageButton?scrollTo=style

那我做错了什么?

最佳答案

您只在本地更新了样式,没有将更改后的组件发送回 Discord API。

要消除“此交互失败”错误,您需要 respond到互动。一种响应方式是使用 MessageComponentInteraction.update() ,更新原始消息。

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)
]
});

}
}
});

enter image description here

要使它与多个按钮一起使用,请使用下面的示例。

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
});

}
}
});

enter image description here

关于javascript - Discord.js - 如何改变按钮的样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68764440/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com