using DSharpPlus;
using DSharpPlus.Entities;
using DSharpPlus.Exceptions;
namespace X10D.DSharpPlus;
///
/// Extension methods for .
///
public static class DiscordUserExtensions
{
///
/// Returns the current as a member of the specified guild.
///
/// The user to transform.
/// The guild whose member list to search.
///
/// A whose is equal to , or
/// if this user is not in the specified .
///
///
/// is .
/// -or-
/// is .
///
public static async Task GetAsMemberOfAsync(this DiscordUser user, DiscordGuild guild)
{
#if NET6_0_OR_GREATER
ArgumentNullException.ThrowIfNull(user);
ArgumentNullException.ThrowIfNull(guild);
#else
if (user is null)
{
throw new ArgumentNullException(nameof(user));
}
if (guild is null)
{
throw new ArgumentNullException(nameof(guild));
}
#endif
if (user is DiscordMember member && member.Guild == guild)
{
return member;
}
if (guild.Members.TryGetValue(user.Id, out member!))
{
return member;
}
try
{
return await guild.GetMemberAsync(user.Id);
}
catch (NotFoundException)
{
return null;
}
}
///
/// Returns the user's username with the discriminator, in the format username#discriminator.
///
/// The user whose username and discriminator to retrieve.
/// A string in the format username#discriminator
/// is .
public static string GetUsernameWithDiscriminator(this DiscordUser user)
{
#if NET6_0_OR_GREATER
ArgumentNullException.ThrowIfNull(user);
#else
if (user is null)
{
throw new ArgumentNullException(nameof(user));
}
#endif
return $"{user.Username}#{user.Discriminator}";
}
///
/// Returns a value indicating whether the current user is in the specified guild.
///
/// The user to check.
/// The guild whose member list to search.
///
/// if is a member of ; otherwise,
/// .
///
public static async Task IsInGuildAsync(this DiscordUser user, DiscordGuild guild)
{
#if NET6_0_OR_GREATER
ArgumentNullException.ThrowIfNull(user);
ArgumentNullException.ThrowIfNull(guild);
#else
if (user is null)
{
throw new ArgumentNullException(nameof(user));
}
if (guild is null)
{
throw new ArgumentNullException(nameof(guild));
}
#endif
if (guild.Members.TryGetValue(user.Id, out _))
{
return true;
}
try
{
DiscordMember? member = await guild.GetMemberAsync(user.Id);
return member is not null;
}
catch (NotFoundException)
{
return false;
}
}
///
/// Normalizes a so that the internal client is assured to be a specified value.
///
/// The to normalize.
/// The target client.
///
/// A whose public values will match , but whose internal client is
/// .
///
///
/// is
/// -or-
/// is
///
public static async Task NormalizeClientAsync(this DiscordUser user, DiscordClient client)
{
#if NET6_0_OR_GREATER
ArgumentNullException.ThrowIfNull(user);
ArgumentNullException.ThrowIfNull(client);
#else
if (user is null)
{
throw new ArgumentNullException(nameof(user));
}
if (client is null)
{
throw new ArgumentNullException(nameof(client));
}
#endif
return await client.GetGuildAsync(user.Id);
}
}