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

2024-04-06

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

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")还透露,风格已成功从初级转变为危险。

但在我的 Discord 客户端中,样式/颜色没有改变,最重要的是我收到一个错误,说交互失败。

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

那么我做错了什么?


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

要摆脱“此交互失败”错误,您需要respond https://discord.com/developers/docs/interactions/receiving-and-responding#responding-to-an-interaction到互动。一种响应方法是使用MessageComponentInteraction.update() https://discord.js.org/#/docs/main/stable/class/MessageComponentInteraction?scrollTo=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)
                ]
            });

        }
    }
});

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

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

        }
    }
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Discord.js - 如何更改按钮的样式 的相关文章

随机推荐