分配或删除角色后如何在Discord上编辑嵌入式消息

时间:2020-09-06 15:14:18

标签: discord.js

我正在使用Discord机器人,并且有一个嵌入的图形显示了具有该角色的人员的姓名,我希望每次分配或删除该角色时,使该消息编辑一条消息。帮助将不胜感激?

1 个答案:

答案 0 :(得分:0)

您可以使用Client#guildMemberUpdate。每当GuildMember更新时都会触发该事件。 (这包括:添加角色,删除角色,更改昵称等)。

这是一个简单的例子:

client.on("guildMemberUpdate", (oldGuildMember, newGuildMember) => {
    if (oldGuildMember.guild.id == "GuildID") { // Checking if the event was fired within the required Guild.
        if (!oldGuildMember.roles.cache.equals(newGuildMember.roles.cache)) { // Checking if the roles were changed.
            const Channel = client.channels.cache.get("ChannelIUD"); // Getting the channel your MessageEmbed is in.
            const Role = oldGuildMember.guild.roles.cache.get("RoleID"); // Getting the Role by ID.
            if (!Role || !Channel) return console.error("Invalid role or channel.");

            Channel.messages.fetch("MessageID").then(message => { // Getting the MessageEmbed as a Message by ID
                const Embed = new Discord.MessageEmbed(); // Updating the MessageEmbed.
                Embed.addField(`Members of ${Role.name}`, Role.members.size > 0 ? `${Role.members.map(member => member.user.tag).join("; \n")};` : "This role has no members.");
                Embed.setColor("RED");
                message.edit(Embed).catch(error => console.error("Couldn't edit the message."));
            }).catch(error => console.error("Couldn't fetch the message."));
        };
    };
});