.inrole will now list users in alphabetical order

This commit is contained in:
Toastie 2025-03-09 17:16:52 +13:00
parent ec0057ad19
commit 37986ed0b2
Signed by: toastie_t0ast
GPG key ID: 0861BE54AD481DC7
2 changed files with 182 additions and 178 deletions
src/EllieBot

View file

@ -61,7 +61,7 @@
<PackageReference Include="Serilog.Sinks.Seq" Version="9.0.0" /> <PackageReference Include="Serilog.Sinks.Seq" Version="9.0.0" />
<PackageReference Include="SixLabors.Fonts" Version="2.1.0" /> <PackageReference Include="SixLabors.Fonts" Version="2.1.0" />
<PackageReference Include="SixLabors.ImageSharp" Version="3.1.6" /> <PackageReference Include="SixLabors.ImageSharp" Version="3.1.7" />
<PackageReference Include="SixLabors.ImageSharp.Drawing" Version="2.1.5" /> <PackageReference Include="SixLabors.ImageSharp.Drawing" Version="2.1.5" />
<PackageReference Include="SixLabors.Shapes" Version="1.0.0-beta0009" /> <PackageReference Include="SixLabors.Shapes" Version="1.0.0-beta0009" />
<PackageReference Include="StackExchange.Redis" Version="2.8.24" /> <PackageReference Include="StackExchange.Redis" Version="2.8.24" />

View file

@ -85,10 +85,10 @@ public partial class Utility : EllieModule
message = await repSvc.ReplaceAsync(message, repCtx); message = await repSvc.ReplaceAsync(message, repCtx);
await Response() await Response()
.Text(message) .Text(message)
.Channel(channel) .Channel(channel)
.UserBasedMentions() .UserBasedMentions()
.SendAsync(); .SendAsync();
} }
[Cmd] [Cmd]
@ -123,27 +123,27 @@ public partial class Utility : EllieModule
} }
await Response() await Response()
.Sanitize() .Sanitize()
.Paginated() .Paginated()
.Items(userNames) .Items(userNames)
.PageSize(20) .PageSize(20)
.Page((names, _) => .Page((names, _) =>
{ {
if (names.Count == 0) if (names.Count == 0)
{ {
return CreateEmbed() return CreateEmbed()
.WithErrorColor() .WithErrorColor()
.WithDescription(GetText(strs.nobody_playing_game)); .WithDescription(GetText(strs.nobody_playing_game));
} }
var eb = CreateEmbed() var eb = CreateEmbed()
.WithOkColor(); .WithOkColor();
var users = names.Join('\n'); var users = names.Join('\n');
return eb.WithDescription(users); return eb.WithDescription(users);
}) })
.SendAsync(); .SendAsync();
} }
[Cmd] [Cmd]
@ -161,9 +161,11 @@ public partial class Utility : EllieModule
CacheMode.CacheOnly CacheMode.CacheOnly
); );
users = role is null users = (role is null
? users ? users
: users.Where(u => u.RoleIds.Contains(role.Id)).ToList(); : users.Where(u => u.RoleIds.Contains(role.Id)))
.OrderBy(x => x.DisplayName)
.ToList();
var roleUsers = new List<string>(users.Count); var roleUsers = new List<string>(users.Count);
@ -173,23 +175,23 @@ public partial class Utility : EllieModule
} }
await Response() await Response()
.Paginated() .Paginated()
.Items(roleUsers) .Items(roleUsers)
.PageSize(20) .PageSize(20)
.CurrentPage(page) .CurrentPage(page)
.Page((pageUsers, _) => .Page((pageUsers, _) =>
{ {
if (pageUsers.Count == 0) if (pageUsers.Count == 0)
return CreateEmbed().WithOkColor().WithDescription(GetText(strs.no_user_on_this_page)); return CreateEmbed().WithOkColor().WithDescription(GetText(strs.no_user_on_this_page));
var roleName = Format.Bold(role?.Name ?? "No Role"); var roleName = Format.Bold(role?.Name ?? "No Role");
return CreateEmbed() return CreateEmbed()
.WithOkColor() .WithOkColor()
.WithTitle(GetText(strs.inrole_list(role?.GetIconUrl() + roleName, roleUsers.Count))) .WithTitle(GetText(strs.inrole_list(role?.GetIconUrl() + roleName, roleUsers.Count)))
.WithDescription(string.Join("\n", pageUsers)); .WithDescription(string.Join("\n", pageUsers));
}) })
.SendAsync(); .SendAsync();
} }
[Cmd] [Cmd]
@ -211,14 +213,14 @@ public partial class Utility : EllieModule
{ {
var builder = new StringBuilder(); var builder = new StringBuilder();
foreach (var p in perms.GetType() foreach (var p in perms.GetType()
.GetProperties() .GetProperties()
.Where(static p => .Where(static p =>
{ {
var method = p.GetGetMethod(); var method = p.GetGetMethod();
if (method is null) if (method is null)
return false; return false;
return !method.GetParameters().Any(); return !method.GetParameters().Any();
})) }))
builder.AppendLine($"{p.Name} : {p.GetValue(perms, null)}"); builder.AppendLine($"{p.Name} : {p.GetValue(perms, null)}");
await Response().Confirm(builder.ToString()).SendAsync(); await Response().Confirm(builder.ToString()).SendAsync();
} }
@ -229,20 +231,20 @@ public partial class Utility : EllieModule
{ {
var usr = target ?? ctx.User; var usr = target ?? ctx.User;
await Response() await Response()
.Confirm(strs.userid("🆔", .Confirm(strs.userid("🆔",
Format.Bold(usr.ToString()), Format.Bold(usr.ToString()),
Format.Code(usr.Id.ToString()))) Format.Code(usr.Id.ToString())))
.SendAsync(); .SendAsync();
} }
[Cmd] [Cmd]
[RequireContext(ContextType.Guild)] [RequireContext(ContextType.Guild)]
public async Task RoleId([Leftover] IRole role) public async Task RoleId([Leftover] IRole role)
=> await Response() => await Response()
.Confirm(strs.roleid("🆔", .Confirm(strs.roleid("🆔",
Format.Bold(role.ToString()), Format.Bold(role.ToString()),
Format.Code(role.Id.ToString()))) Format.Code(role.Id.ToString())))
.SendAsync(); .SendAsync();
[Cmd] [Cmd]
public async Task ChannelId() public async Task ChannelId()
@ -267,36 +269,36 @@ public partial class Utility : EllieModule
if (target is not null) if (target is not null)
{ {
var roles = target.GetRoles() var roles = target.GetRoles()
.Except(new[] { guild.EveryoneRole }) .Except(new[] { guild.EveryoneRole })
.OrderBy(r => -r.Position) .OrderBy(r => -r.Position)
.Skip((page - 1) * rolesPerPage) .Skip((page - 1) * rolesPerPage)
.Take(rolesPerPage) .Take(rolesPerPage)
.ToArray(); .ToArray();
if (!roles.Any()) if (!roles.Any())
await Response().Error(strs.no_roles_on_page).SendAsync(); await Response().Error(strs.no_roles_on_page).SendAsync();
else else
{ {
await Response() await Response()
.Confirm(GetText(strs.roles_page(page, Format.Bold(target.ToString()))), .Confirm(GetText(strs.roles_page(page, Format.Bold(target.ToString()))),
"\n• " + string.Join("\n• ", (IEnumerable<IRole>)roles)) "\n• " + string.Join("\n• ", (IEnumerable<IRole>)roles))
.SendAsync(); .SendAsync();
} }
} }
else else
{ {
var roles = guild.Roles.Except(new[] { guild.EveryoneRole }) var roles = guild.Roles.Except(new[] { guild.EveryoneRole })
.OrderBy(r => -r.Position) .OrderBy(r => -r.Position)
.Skip((page - 1) * rolesPerPage) .Skip((page - 1) * rolesPerPage)
.Take(rolesPerPage) .Take(rolesPerPage)
.ToArray(); .ToArray();
if (!roles.Any()) if (!roles.Any())
await Response().Error(strs.no_roles_on_page).SendAsync(); await Response().Error(strs.no_roles_on_page).SendAsync();
else else
{ {
await Response() await Response()
.Confirm(GetText(strs.roles_all_page(page)), .Confirm(GetText(strs.roles_all_page(page)),
"\n• " + string.Join("\n• ", (IEnumerable<IRole>)roles).SanitizeMentions(true)) "\n• " + string.Join("\n• ", (IEnumerable<IRole>)roles).SanitizeMentions(true))
.SendAsync(); .SendAsync();
} }
} }
} }
@ -328,33 +330,33 @@ public partial class Utility : EllieModule
ownerIds = "-"; ownerIds = "-";
var eb = CreateEmbed() var eb = CreateEmbed()
.WithOkColor() .WithOkColor()
.WithAuthor($"EllieBot v{StatsService.BotVersion}", .WithAuthor($"EllieBot v{StatsService.BotVersion}",
"https://cdn.elliebot.net/Ellie.png", "https://cdn.elliebot.net/Ellie.png",
"https://docs.elliebot.net") "https://docs.elliebot.net")
.AddField(GetText(strs.author), _stats.Author, true) .AddField(GetText(strs.author), _stats.Author, true)
.AddField(GetText(strs.botid), _client.CurrentUser.Id.ToString(), true) .AddField(GetText(strs.botid), _client.CurrentUser.Id.ToString(), true)
.AddField(GetText(strs.shard), .AddField(GetText(strs.shard),
$"#{_client.ShardId} / {_creds.TotalShards}", $"#{_client.ShardId} / {_creds.TotalShards}",
true) true)
.AddField(GetText(strs.commands_ran), _stats.CommandsRan.ToString(), true) .AddField(GetText(strs.commands_ran), _stats.CommandsRan.ToString(), true)
.AddField(GetText(strs.messages), .AddField(GetText(strs.messages),
$"{_stats.MessageCounter} ({_stats.MessagesPerSecond:F2}/sec)", $"{_stats.MessageCounter} ({_stats.MessagesPerSecond:F2}/sec)",
true) true)
.AddField(GetText(strs.memory), .AddField(GetText(strs.memory),
FormattableString.Invariant($"{_stats.GetPrivateMemoryMegabytes():F2} MB"), FormattableString.Invariant($"{_stats.GetPrivateMemoryMegabytes():F2} MB"),
true) true)
.AddField(GetText(strs.owner_ids), ownerIds, true) .AddField(GetText(strs.owner_ids), ownerIds, true)
.AddField(GetText(strs.uptime), _stats.GetUptimeString("\n"), true) .AddField(GetText(strs.uptime), _stats.GetUptimeString("\n"), true)
.AddField(GetText(strs.presence), .AddField(GetText(strs.presence),
GetText(strs.presence_txt(_coord.GetGuildCount(), GetText(strs.presence_txt(_coord.GetGuildCount(),
_stats.TextChannels, _stats.TextChannels,
_stats.VoiceChannels)), _stats.VoiceChannels)),
true); true);
await Response() await Response()
.Embed(eb) .Embed(eb)
.SendAsync(); .SendAsync();
} }
[Cmd] [Cmd]
@ -503,9 +505,9 @@ public partial class Utility : EllieModule
} }
format = attach.Filename format = attach.Filename
.Split('.') .Split('.')
.Last() .Last()
.ToLowerInvariant(); .ToLowerInvariant();
if (string.IsNullOrWhiteSpace(format) || (format != "png" && format != "apng")) if (string.IsNullOrWhiteSpace(format) || (format != "png" && format != "apng"))
{ {
@ -572,30 +574,30 @@ public partial class Utility : EllieModule
return; return;
var allGuilds = _client.Guilds var allGuilds = _client.Guilds
.OrderBy(g => g.Name) .OrderBy(g => g.Name)
.ToList(); .ToList();
await Response() await Response()
.Paginated() .Paginated()
.Items(allGuilds) .Items(allGuilds)
.PageSize(9) .PageSize(9)
.Page((guilds, _) => .Page((guilds, _) =>
{ {
if (!guilds.Any()) if (!guilds.Any())
{ {
return CreateEmbed() return CreateEmbed()
.WithDescription(GetText(strs.listservers_none)) .WithDescription(GetText(strs.listservers_none))
.WithErrorColor(); .WithErrorColor();
} }
var embed = CreateEmbed() var embed = CreateEmbed()
.WithOkColor(); .WithOkColor();
foreach (var guild in guilds) foreach (var guild in guilds)
embed.AddField(guild.Name, GetText(strs.listservers(guild.Id, guild.MemberCount, guild.OwnerId))); embed.AddField(guild.Name, GetText(strs.listservers(guild.Id, guild.MemberCount, guild.OwnerId)));
return embed; return embed;
}) })
.SendAsync(); .SendAsync();
} }
[Cmd] [Cmd]
@ -632,7 +634,7 @@ public partial class Utility : EllieModule
{ {
Content = msg.Content, Content = msg.Content,
Embeds = msg.Embeds Embeds = msg.Embeds
.Map(x => new SmartEmbedArrayElementText(x)) .Map(x => new SmartEmbedArrayElementText(x))
}.ToJson(_showEmbedSerializerOptions); }.ToJson(_showEmbedSerializerOptions);
await Response().Confirm(Format.Code(json, "json").Replace("](", "]\\(")).SendAsync(); await Response().Confirm(Format.Code(json, "json").Replace("](", "]\\(")).SendAsync();
@ -648,34 +650,34 @@ public partial class Utility : EllieModule
var title = $"Chatlog-{ctx.Guild.Name}/#{ctx.Channel.Name}-{DateTime.Now}.txt"; var title = $"Chatlog-{ctx.Guild.Name}/#{ctx.Channel.Name}-{DateTime.Now}.txt";
var grouping = msgs.GroupBy(x => $"{x.CreatedAt.Date:dd.MM.yyyy}") var grouping = msgs.GroupBy(x => $"{x.CreatedAt.Date:dd.MM.yyyy}")
.Select(g => new .Select(g => new
{ {
date = g.Key, date = g.Key,
messages = g.OrderBy(x => x.CreatedAt) messages = g.OrderBy(x => x.CreatedAt)
.Select(s => .Select(s =>
{ {
var msg = $"【{s.Timestamp:HH:mm:ss}】{s.Author}:"; var msg = $"【{s.Timestamp:HH:mm:ss}】{s.Author}:";
if (string.IsNullOrWhiteSpace(s.ToString())) if (string.IsNullOrWhiteSpace(s.ToString()))
{ {
if (s.Attachments.Any()) if (s.Attachments.Any())
{ {
msg += "FILES_UPLOADED: " msg += "FILES_UPLOADED: "
+ string.Join("\n", s.Attachments.Select(x => x.Url)); + string.Join("\n", s.Attachments.Select(x => x.Url));
} }
else if (s.Embeds.Any()) else if (s.Embeds.Any())
{ {
msg += "EMBEDS: " msg += "EMBEDS: "
+ string.Join("\n--------\n", + string.Join("\n--------\n",
s.Embeds.Select(x s.Embeds.Select(x
=> $"Description: {x.Description}")); => $"Description: {x.Description}"));
} }
} }
else else
msg += s.ToString(); msg += s.ToString();
return msg; return msg;
}) })
}); });
await using var stream = await JsonConvert.SerializeObject(grouping, Formatting.Indented).ToStream(); await using var stream = await JsonConvert.SerializeObject(grouping, Formatting.Indented).ToStream();
await ctx.User.SendFileAsync(stream, title, title); await ctx.User.SendFileAsync(stream, title, title);
} }
@ -690,8 +692,8 @@ public partial class Utility : EllieModule
msg.DeleteAfter(0); msg.DeleteAfter(0);
await Response() await Response()
.Confirm($"{Format.Bold(ctx.User.ToString())} 🏓 {(int)sw.Elapsed.TotalMilliseconds}ms") .Confirm($"{Format.Bold(ctx.User.ToString())} 🏓 {(int)sw.Elapsed.TotalMilliseconds}ms")
.SendAsync(); .SendAsync();
} }
[Cmd] [Cmd]
@ -715,8 +717,8 @@ public partial class Utility : EllieModule
if (succ) if (succ)
{ {
await Response() await Response()
.Confirm(strs.afk_set) .Confirm(strs.afk_set)
.SendAsync(); .SendAsync();
} }
} }
@ -737,22 +739,22 @@ public partial class Utility : EllieModule
var script = CSharpScript.Create(scriptText, var script = CSharpScript.Create(scriptText,
ScriptOptions.Default ScriptOptions.Default
.WithReferences(this.GetType().Assembly) .WithReferences(this.GetType().Assembly)
.WithImports( .WithImports(
"System", "System",
"System.Collections.Generic", "System.Collections.Generic",
"System.IO", "System.IO",
"System.Linq", "System.Linq",
"System.Net.Http", "System.Net.Http",
"System.Threading", "System.Threading",
"System.Threading.Tasks", "System.Threading.Tasks",
"EllieBot", "EllieBot",
"EllieBot.Extensions", "EllieBot.Extensions",
"Microsoft.Extensions.DependencyInjection", "Microsoft.Extensions.DependencyInjection",
"EllieBot.Common", "EllieBot.Common",
"EllieBot.Modules", "EllieBot.Modules",
"System.Text", "System.Text",
"System.Text.Json"), "System.Text.Json"),
globalsType: typeof(EvalGlobals)); globalsType: typeof(EvalGlobals));
try try
@ -771,9 +773,9 @@ public partial class Utility : EllieModule
if (!string.IsNullOrWhiteSpace(output)) if (!string.IsNullOrWhiteSpace(output))
{ {
var eb = CreateEmbed() var eb = CreateEmbed()
.WithOkColor() .WithOkColor()
.AddField("Code", scriptText) .AddField("Code", scriptText)
.AddField("Output", output.TrimTo(512)!); .AddField("Output", output.TrimTo(512)!);
_ = Response().Embed(eb).SendAsync(); _ = Response().Embed(eb).SendAsync();
} }
@ -790,19 +792,21 @@ public partial class Utility : EllieModule
if (ctx.Message.ReferencedMessage is not { } msg) if (ctx.Message.ReferencedMessage is not { } msg)
{ {
var msgs = await ctx.Channel.GetMessagesAsync(ctx.Message, Direction.Before, 3).FlattenAsync(); var msgs = await ctx.Channel.GetMessagesAsync(ctx.Message, Direction.Before, 3).FlattenAsync();
msg = msgs.FirstOrDefault(x => !string.IsNullOrWhiteSpace(x.Content) || (x.Attachments.FirstOrDefault()?.Width is not null)) as IUserMessage; msg = msgs.FirstOrDefault(x
=> !string.IsNullOrWhiteSpace(x.Content) ||
(x.Attachments.FirstOrDefault()?.Width is not null)) as IUserMessage;
if (msg is null) if (msg is null)
return; return;
} }
var eb = CreateEmbed() var eb = CreateEmbed()
.WithOkColor() .WithOkColor()
.WithDescription(msg.Content) .WithDescription(msg.Content)
.WithAuthor(msg.Author) .WithAuthor(msg.Author)
.WithTimestamp(msg.Timestamp) .WithTimestamp(msg.Timestamp)
.WithImageUrl(msg.Attachments.FirstOrDefault()?.Url) .WithImageUrl(msg.Attachments.FirstOrDefault()?.Url)
.WithFooter(GetText(strs.sniped_by(ctx.User.ToString())), ctx.User.GetDisplayAvatarUrl()); .WithFooter(GetText(strs.sniped_by(ctx.User.ToString())), ctx.User.GetDisplayAvatarUrl());
ctx.Message.DeleteAfter(1); ctx.Message.DeleteAfter(1);
await Response().Embed(eb).SendAsync(); await Response().Embed(eb).SendAsync();