44 lines
No EOL
1.5 KiB
C#
44 lines
No EOL
1.5 KiB
C#
using Remora.Discord.API.Abstractions.Objects;
|
|
using Remora.Rest.Core;
|
|
using Remora.Results;
|
|
|
|
namespace Catalogger.Backend.Extensions;
|
|
|
|
public static class DiscordExtensions
|
|
{
|
|
public static string Tag(this IPartialUser user)
|
|
{
|
|
var discriminator = user.Discriminator.OrDefault();
|
|
return discriminator == 0 ? user.Username.Value : $"{user.Username.Value}#{discriminator:0000}";
|
|
}
|
|
|
|
public static string AvatarUrl(this IUser user, int size = 256)
|
|
{
|
|
if (user.Avatar != null)
|
|
{
|
|
var ext = user.Avatar.HasGif ? ".gif" : ".webp";
|
|
return $"https://cdn.discordapp.com/avatars/{user.ID}/{user.Avatar.Value}{ext}?size={size}";
|
|
}
|
|
|
|
var avatarIndex = user.Discriminator == 0 ? (int)((user.ID.Value >> 22) % 6) : user.Discriminator % 5;
|
|
return $"https://cdn.discordapp.com/embed/avatars/{avatarIndex}.png?size={size}";
|
|
}
|
|
|
|
public static ulong ToUlong(this Snowflake snowflake) => snowflake.Value;
|
|
|
|
public static ulong ToUlong(this Optional<Snowflake> snowflake)
|
|
{
|
|
if (!snowflake.IsDefined()) throw new Exception("ToUlong called on an undefined Snowflake");
|
|
return snowflake.Value.Value;
|
|
}
|
|
|
|
public static T GetOrThrow<T>(this Result<T> result)
|
|
{
|
|
if (result.Error != null) throw new DiscordRestException(result.Error.Message);
|
|
return result.Entity;
|
|
}
|
|
|
|
public static async Task<T> GetOrThrow<T>(this Task<Result<T>> result) => (await result).GetOrThrow();
|
|
|
|
public class DiscordRestException(string message) : Exception(message);
|
|
} |