【问题标题】:Remove 1 element from Embed object DiscordJS从嵌入对象 DiscordJS 中删除 1 个元素
【发布时间】:2021-10-16 07:12:36
【问题描述】:

我一直在尝试编写一个机器人,将 1 个嵌入从 1 个频道复制到另一个频道。

但在将其发布到另一个频道之前,我希望它从嵌入对象中删除 1 个元素。

我现在如何拥有它:

client.on("message", (message) => {
    if (message.channel.id == channel1) {
        const embed = message.embeds[0];
    
        var params = {
            embeds: [embed],
        };
    
        fetch("WEBHOOK URL", {
            //send channel 2
            method: "POST",
            headers: {
                "Content-type": "application/json",
            },
            body: JSON.stringify(params),
        }).then((res) => {});
    }
});

如您所见,我直接使用 message.embeds[0]。

所以我什至不知道是否可以从中删除 1 个元素,例如页脚文本。

如果有人知道这是否可以做到,请说出来。

感谢您的阅读。

编辑:

会不会是这样的:

const embed = message.embeds[0];

embed.footer.text = [];
// or
embed.footer[0].text

【问题讨论】:

    标签: javascript discord discord.js


    【解决方案1】:

    您可以使用delete 运算符从对象中删除属性。

    const embed = message.embeds[0];
    if (!embed) return;
    
    delete embed.footer;
    
    message.channel.send({
        content: "Footer removed!",
        embeds: [embed]
    });
    

    请注意,您不能只删除text 属性并保留图标。如果没有 text 属性,页脚将不会显示。

    这些也可以:

    // Remove only text from footer (footer won't be visible including icon)
    embed.footer.text = "";
    // Or
    embed.footer = {};
    // Or
    embed.footer = null;
    // Or ...
    

    【讨论】:

    • 1 个问题,如果我对多条消息执行此操作,并且 1 嵌入没有页脚怎么办?我可以检测到 if(embed.footer) 这样它就不会让我的机器人崩溃吗?
    • 是的,如果您正在访问footer 的属性,最好使用该检查,例如.text。如果您只是在做delete embed.footer,则无需进行此类检查,属性页脚始终存在(在嵌入对象上),如果没有实际页脚,则只是null。
    • 此外,如果您尝试删除不存在的对象属性,delete 运算符将返回 true 并继续进行而不会出错。如 MDN 文档中所述(在我的答案中链接)。
    猜你喜欢
    • 1970-01-01
    • 2022-08-17
    • 1970-01-01
    • 2014-05-05
    • 2020-05-11
    • 1970-01-01
    • 1970-01-01
    • 2021-09-28
    • 1970-01-01
    相关资源
    最近更新 更多