CXazertyuuu
CXazertyuuu
DIAdiscord.js - Imagine a bot
Created by CXazertyuuu on 6/18/2024 in #djs-questions
Transform a APIInteractionDataResolvedGuildMember into a GuildMember
Hello there, I am beginning with discord.js and typescript. To ensure type safety, i want to make sure that the object returned by a interaction.options.getMember() is a GuildMember and not a APIInteractionDataResolvedGuildMember in order to later perform various operations. So i've began to write a function to fetch the GuildMember if needed but APIInteractionDataResolvedGuildMember does not have a user property so i can't have the id for fetching... How should i deal with it ? Or can i safely assume that in the context of slash commands in guild i will always have a GuildMember object ? Here the function that i wrote :
export async function getMemberSafely(member : GuildMember | APIInteractionDataResolvedGuildMember| null , guild : Guild) : Promise<GuildMember | null> {
if (!member) return null;
if (member instanceof GuildMember) return member;

try {
const fetchedMember : GuildMember = await guild.members.fetch((member as APIInteractionDataResolvedGuildMember)?.user?.id); // Here is the problem
return fetchedMember;
} catch (error) {
console.error("Erreur lors de la récupération d'un membre : ",error);
return null;

}
}
export async function getMemberSafely(member : GuildMember | APIInteractionDataResolvedGuildMember| null , guild : Guild) : Promise<GuildMember | null> {
if (!member) return null;
if (member instanceof GuildMember) return member;

try {
const fetchedMember : GuildMember = await guild.members.fetch((member as APIInteractionDataResolvedGuildMember)?.user?.id); // Here is the problem
return fetchedMember;
} catch (error) {
console.error("Erreur lors de la récupération d'un membre : ",error);
return null;

}
}
Thanks !
10 replies