From 005fd7b8c64c947bb4aba2c4a659b83f3a843632 Mon Sep 17 00:00:00 2001 From: Kwoth Date: Thu, 15 Sep 2022 17:02:53 +0200 Subject: [PATCH] Possible fix for missing IGuildUser when using guild commands, closes #383 --- .../Common/TypeReaders/GuildUserTypeReader.cs | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 src/NadekoBot/Common/TypeReaders/GuildUserTypeReader.cs diff --git a/src/NadekoBot/Common/TypeReaders/GuildUserTypeReader.cs b/src/NadekoBot/Common/TypeReaders/GuildUserTypeReader.cs new file mode 100644 index 000000000..1991443e5 --- /dev/null +++ b/src/NadekoBot/Common/TypeReaders/GuildUserTypeReader.cs @@ -0,0 +1,33 @@ +namespace NadekoBot.Common.TypeReaders; + +public sealed class GuildUserTypeReader : NadekoTypeReader +{ + public override async ValueTask> ReadAsync(ICommandContext ctx, string input) + { + if (ctx.Guild is null) + return TypeReaderResult.FromError(CommandError.Unsuccessful, "Must be in a guild."); + + input = input.Trim(); + IGuildUser? user = null; + if (MentionUtils.TryParseUser(input, out var id)) + user = await ctx.Guild.GetUserAsync(id, CacheMode.AllowDownload); + + if (ulong.TryParse(input, out id)) + user = await ctx.Guild.GetUserAsync(id, CacheMode.AllowDownload); + + if (user is null) + { + var users = await ctx.Guild.GetUsersAsync(CacheMode.CacheOnly); + user = users.FirstOrDefault(x => x.Username == input) + ?? users.FirstOrDefault(x => + string.Equals(x.ToString(), input, StringComparison.InvariantCultureIgnoreCase)) + ?? users.FirstOrDefault(x => + string.Equals(x.Username, input, StringComparison.InvariantCultureIgnoreCase)); + } + + if (user is null) + return TypeReaderResult.FromError(CommandError.ObjectNotFound, "User not found."); + + return TypeReaderResult.FromSuccess(user); + } +} \ No newline at end of file