chore: format with csharpier

This commit is contained in:
sam 2024-10-09 17:35:11 +02:00
parent 2f516dcb73
commit 4f54077c68
59 changed files with 2000 additions and 942 deletions

View file

@ -30,7 +30,8 @@ public class ChannelCommands(
ChannelCache channelCache,
IFeedbackService feedbackService,
ContextInjectionService contextInjection,
InMemoryDataService<Snowflake, ChannelCommandData> dataService) : CommandGroup
InMemoryDataService<Snowflake, ChannelCommandData> dataService
) : CommandGroup
{
private readonly ILogger _logger = logger.ForContext<ChannelCommands>();
@ -40,22 +41,30 @@ public class ChannelCommands(
public async Task<IResult> ConfigureChannelsAsync()
{
var (userId, guildId) = contextInjection.GetUserAndGuild();
if (!guildCache.TryGet(guildId, out var guild)) throw new CataloggerError("Guild not in cache");
if (!guildCache.TryGet(guildId, out var guild))
throw new CataloggerError("Guild not in cache");
var guildChannels = channelCache.GuildChannels(guildId).ToList();
var guildConfig = await db.GetGuildAsync(guildId);
var (embeds, components) = BuildRootMenu(guildChannels, guild, guildConfig);
var msg = await feedbackService.SendContextualAsync(embeds: embeds,
options: new FeedbackMessageOptions(MessageComponents: components)).GetOrThrow();
var msg = await feedbackService
.SendContextualAsync(
embeds: embeds,
options: new FeedbackMessageOptions(MessageComponents: components)
)
.GetOrThrow();
dataService.TryAddData(msg.ID, new ChannelCommandData(userId, CurrentPage: null));
return Result.Success;
}
public static (List<IEmbed>, List<IMessageComponent>) BuildRootMenu(List<IChannel> guildChannels, IGuild guild,
DbGuild guildConfig)
public static (List<IEmbed>, List<IMessageComponent>) BuildRootMenu(
List<IChannel> guildChannels,
IGuild guild,
DbGuild guildConfig
)
{
List<IEmbed> embeds =
[
@ -65,158 +74,369 @@ public class ChannelCommands(
Colour: DiscordUtils.Purple,
Fields: new[]
{
new EmbedField("Server changes", PrettyChannelString(guildConfig.Channels.GuildUpdate), true),
new EmbedField("Emoji changes", PrettyChannelString(guildConfig.Channels.GuildEmojisUpdate), true),
new EmbedField("New roles", PrettyChannelString(guildConfig.Channels.GuildRoleCreate), true),
new EmbedField("Edited roles", PrettyChannelString(guildConfig.Channels.GuildRoleUpdate), true),
new EmbedField("Deleted roles", PrettyChannelString(guildConfig.Channels.GuildRoleDelete), true),
new EmbedField("New channels", PrettyChannelString(guildConfig.Channels.ChannelCreate), true),
new EmbedField("Edited channels", PrettyChannelString(guildConfig.Channels.ChannelUpdate), true),
new EmbedField("Deleted channels", PrettyChannelString(guildConfig.Channels.ChannelDelete), true),
new EmbedField("Members joining", PrettyChannelString(guildConfig.Channels.GuildMemberAdd), true),
new EmbedField("Members leaving", PrettyChannelString(guildConfig.Channels.GuildMemberRemove),
true),
new EmbedField("Member role changes", PrettyChannelString(guildConfig.Channels.GuildMemberUpdate),
true),
new EmbedField("Key role changes", PrettyChannelString(guildConfig.Channels.GuildKeyRoleUpdate),
true),
new EmbedField("Member name changes",
new EmbedField(
"Server changes",
PrettyChannelString(guildConfig.Channels.GuildUpdate),
true
),
new EmbedField(
"Emoji changes",
PrettyChannelString(guildConfig.Channels.GuildEmojisUpdate),
true
),
new EmbedField(
"New roles",
PrettyChannelString(guildConfig.Channels.GuildRoleCreate),
true
),
new EmbedField(
"Edited roles",
PrettyChannelString(guildConfig.Channels.GuildRoleUpdate),
true
),
new EmbedField(
"Deleted roles",
PrettyChannelString(guildConfig.Channels.GuildRoleDelete),
true
),
new EmbedField(
"New channels",
PrettyChannelString(guildConfig.Channels.ChannelCreate),
true
),
new EmbedField(
"Edited channels",
PrettyChannelString(guildConfig.Channels.ChannelUpdate),
true
),
new EmbedField(
"Deleted channels",
PrettyChannelString(guildConfig.Channels.ChannelDelete),
true
),
new EmbedField(
"Members joining",
PrettyChannelString(guildConfig.Channels.GuildMemberAdd),
true
),
new EmbedField(
"Members leaving",
PrettyChannelString(guildConfig.Channels.GuildMemberRemove),
true
),
new EmbedField(
"Member role changes",
PrettyChannelString(guildConfig.Channels.GuildMemberUpdate),
true
),
new EmbedField(
"Key role changes",
PrettyChannelString(guildConfig.Channels.GuildKeyRoleUpdate),
true
),
new EmbedField(
"Member name changes",
PrettyChannelString(guildConfig.Channels.GuildMemberNickUpdate),
true),
new EmbedField("Member avatar changes",
PrettyChannelString(guildConfig.Channels.GuildMemberAvatarUpdate), true),
new EmbedField("Kicks", PrettyChannelString(guildConfig.Channels.GuildMemberKick), true),
new EmbedField("Bans", PrettyChannelString(guildConfig.Channels.GuildBanAdd), true),
new EmbedField("Unbans", PrettyChannelString(guildConfig.Channels.GuildBanRemove), true),
new EmbedField("New invites", PrettyChannelString(guildConfig.Channels.InviteCreate), true),
new EmbedField("Deleted invites", PrettyChannelString(guildConfig.Channels.InviteDelete), true),
new EmbedField("Edited messages", PrettyChannelString(guildConfig.Channels.MessageUpdate), true),
new EmbedField("Deleted messages", PrettyChannelString(guildConfig.Channels.MessageDelete), true),
new EmbedField("Bulk deleted messages", PrettyChannelString(guildConfig.Channels.MessageDeleteBulk),
true),
})
true
),
new EmbedField(
"Member avatar changes",
PrettyChannelString(guildConfig.Channels.GuildMemberAvatarUpdate),
true
),
new EmbedField(
"Kicks",
PrettyChannelString(guildConfig.Channels.GuildMemberKick),
true
),
new EmbedField(
"Bans",
PrettyChannelString(guildConfig.Channels.GuildBanAdd),
true
),
new EmbedField(
"Unbans",
PrettyChannelString(guildConfig.Channels.GuildBanRemove),
true
),
new EmbedField(
"New invites",
PrettyChannelString(guildConfig.Channels.InviteCreate),
true
),
new EmbedField(
"Deleted invites",
PrettyChannelString(guildConfig.Channels.InviteDelete),
true
),
new EmbedField(
"Edited messages",
PrettyChannelString(guildConfig.Channels.MessageUpdate),
true
),
new EmbedField(
"Deleted messages",
PrettyChannelString(guildConfig.Channels.MessageDelete),
true
),
new EmbedField(
"Bulk deleted messages",
PrettyChannelString(guildConfig.Channels.MessageDeleteBulk),
true
),
}
),
];
List<IMessageComponent> components =
[
new ActionRowComponent([
new ButtonComponent(ButtonComponentStyle.Primary, Label: "Server changes",
CustomID: CustomIDHelpers.CreateButtonIDWithState("config-channels",
nameof(LogChannelType.GuildUpdate))),
new ButtonComponent(ButtonComponentStyle.Primary, Label: "Emoji changes",
CustomID: CustomIDHelpers.CreateButtonIDWithState("config-channels",
nameof(LogChannelType.GuildEmojisUpdate))),
new ButtonComponent(ButtonComponentStyle.Primary, Label: "New roles",
CustomID: CustomIDHelpers.CreateButtonIDWithState("config-channels",
nameof(LogChannelType.GuildRoleCreate))),
new ButtonComponent(ButtonComponentStyle.Primary, Label: "Edited roles",
CustomID: CustomIDHelpers.CreateButtonIDWithState("config-channels",
nameof(LogChannelType.GuildRoleUpdate))),
new ButtonComponent(ButtonComponentStyle.Primary, Label: "Deleted roles",
CustomID: CustomIDHelpers.CreateButtonIDWithState("config-channels",
nameof(LogChannelType.GuildRoleDelete))),
]),
new ActionRowComponent([
new ButtonComponent(ButtonComponentStyle.Primary, Label: "New channels",
CustomID: CustomIDHelpers.CreateButtonIDWithState("config-channels",
nameof(LogChannelType.ChannelCreate))),
new ButtonComponent(ButtonComponentStyle.Primary, Label: "Edited channels",
CustomID: CustomIDHelpers.CreateButtonIDWithState("config-channels",
nameof(LogChannelType.ChannelUpdate))),
new ButtonComponent(ButtonComponentStyle.Primary, Label: "Deleted channels",
CustomID: CustomIDHelpers.CreateButtonIDWithState("config-channels",
nameof(LogChannelType.ChannelDelete))),
new ButtonComponent(ButtonComponentStyle.Primary, Label: "Members joining",
CustomID: CustomIDHelpers.CreateButtonIDWithState("config-channels",
nameof(LogChannelType.GuildMemberAdd))),
new ButtonComponent(ButtonComponentStyle.Primary, Label: "Members leaving",
CustomID: CustomIDHelpers.CreateButtonIDWithState("config-channels",
nameof(LogChannelType.GuildMemberRemove))),
]),
new ActionRowComponent([
new ButtonComponent(ButtonComponentStyle.Primary, Label: "Member role changes",
CustomID: CustomIDHelpers.CreateButtonIDWithState("config-channels",
nameof(LogChannelType.GuildMemberUpdate))),
new ButtonComponent(ButtonComponentStyle.Primary, Label: "Key role changes",
CustomID: CustomIDHelpers.CreateButtonIDWithState("config-channels",
nameof(LogChannelType.GuildKeyRoleUpdate))),
new ButtonComponent(ButtonComponentStyle.Primary, Label: "Member name changes",
CustomID: CustomIDHelpers.CreateButtonIDWithState("config-channels",
nameof(LogChannelType.GuildMemberNickUpdate))),
new ButtonComponent(ButtonComponentStyle.Primary, Label: "Members avatar changes",
CustomID: CustomIDHelpers.CreateButtonIDWithState("config-channels",
nameof(LogChannelType.GuildMemberAvatarUpdate))),
new ButtonComponent(ButtonComponentStyle.Primary, Label: "Kicks",
CustomID: CustomIDHelpers.CreateButtonIDWithState("config-channels",
nameof(LogChannelType.GuildMemberKick))),
]),
new ActionRowComponent([
new ButtonComponent(ButtonComponentStyle.Primary, Label: "Bans",
CustomID: CustomIDHelpers.CreateButtonIDWithState("config-channels",
nameof(LogChannelType.GuildBanAdd))),
new ButtonComponent(ButtonComponentStyle.Primary, Label: "Unbans",
CustomID: CustomIDHelpers.CreateButtonIDWithState("config-channels",
nameof(LogChannelType.GuildBanRemove))),
new ButtonComponent(ButtonComponentStyle.Primary, Label: "New invites",
CustomID: CustomIDHelpers.CreateButtonIDWithState("config-channels",
nameof(LogChannelType.InviteCreate))),
new ButtonComponent(ButtonComponentStyle.Primary, Label: "Deleted invites",
CustomID: CustomIDHelpers.CreateButtonIDWithState("config-channels",
nameof(LogChannelType.InviteDelete))),
new ButtonComponent(ButtonComponentStyle.Primary, Label: "Edited messages",
CustomID: CustomIDHelpers.CreateButtonIDWithState("config-channels",
nameof(LogChannelType.MessageUpdate))),
]),
new ActionRowComponent([
new ButtonComponent(ButtonComponentStyle.Primary, Label: "Deleted messages",
CustomID: CustomIDHelpers.CreateButtonIDWithState("config-channels",
nameof(LogChannelType.MessageDelete))),
new ButtonComponent(ButtonComponentStyle.Primary, Label: "Bulk deleted messages",
CustomID: CustomIDHelpers.CreateButtonIDWithState("config-channels",
nameof(LogChannelType.MessageDeleteBulk))),
new ButtonComponent(ButtonComponentStyle.Secondary, Label: "Close",
CustomID: CustomIDHelpers.CreateButtonIDWithState("config-channels", "close")),
]),
new ActionRowComponent(
[
new ButtonComponent(
ButtonComponentStyle.Primary,
Label: "Server changes",
CustomID: CustomIDHelpers.CreateButtonIDWithState(
"config-channels",
nameof(LogChannelType.GuildUpdate)
)
),
new ButtonComponent(
ButtonComponentStyle.Primary,
Label: "Emoji changes",
CustomID: CustomIDHelpers.CreateButtonIDWithState(
"config-channels",
nameof(LogChannelType.GuildEmojisUpdate)
)
),
new ButtonComponent(
ButtonComponentStyle.Primary,
Label: "New roles",
CustomID: CustomIDHelpers.CreateButtonIDWithState(
"config-channels",
nameof(LogChannelType.GuildRoleCreate)
)
),
new ButtonComponent(
ButtonComponentStyle.Primary,
Label: "Edited roles",
CustomID: CustomIDHelpers.CreateButtonIDWithState(
"config-channels",
nameof(LogChannelType.GuildRoleUpdate)
)
),
new ButtonComponent(
ButtonComponentStyle.Primary,
Label: "Deleted roles",
CustomID: CustomIDHelpers.CreateButtonIDWithState(
"config-channels",
nameof(LogChannelType.GuildRoleDelete)
)
),
]
),
new ActionRowComponent(
[
new ButtonComponent(
ButtonComponentStyle.Primary,
Label: "New channels",
CustomID: CustomIDHelpers.CreateButtonIDWithState(
"config-channels",
nameof(LogChannelType.ChannelCreate)
)
),
new ButtonComponent(
ButtonComponentStyle.Primary,
Label: "Edited channels",
CustomID: CustomIDHelpers.CreateButtonIDWithState(
"config-channels",
nameof(LogChannelType.ChannelUpdate)
)
),
new ButtonComponent(
ButtonComponentStyle.Primary,
Label: "Deleted channels",
CustomID: CustomIDHelpers.CreateButtonIDWithState(
"config-channels",
nameof(LogChannelType.ChannelDelete)
)
),
new ButtonComponent(
ButtonComponentStyle.Primary,
Label: "Members joining",
CustomID: CustomIDHelpers.CreateButtonIDWithState(
"config-channels",
nameof(LogChannelType.GuildMemberAdd)
)
),
new ButtonComponent(
ButtonComponentStyle.Primary,
Label: "Members leaving",
CustomID: CustomIDHelpers.CreateButtonIDWithState(
"config-channels",
nameof(LogChannelType.GuildMemberRemove)
)
),
]
),
new ActionRowComponent(
[
new ButtonComponent(
ButtonComponentStyle.Primary,
Label: "Member role changes",
CustomID: CustomIDHelpers.CreateButtonIDWithState(
"config-channels",
nameof(LogChannelType.GuildMemberUpdate)
)
),
new ButtonComponent(
ButtonComponentStyle.Primary,
Label: "Key role changes",
CustomID: CustomIDHelpers.CreateButtonIDWithState(
"config-channels",
nameof(LogChannelType.GuildKeyRoleUpdate)
)
),
new ButtonComponent(
ButtonComponentStyle.Primary,
Label: "Member name changes",
CustomID: CustomIDHelpers.CreateButtonIDWithState(
"config-channels",
nameof(LogChannelType.GuildMemberNickUpdate)
)
),
new ButtonComponent(
ButtonComponentStyle.Primary,
Label: "Members avatar changes",
CustomID: CustomIDHelpers.CreateButtonIDWithState(
"config-channels",
nameof(LogChannelType.GuildMemberAvatarUpdate)
)
),
new ButtonComponent(
ButtonComponentStyle.Primary,
Label: "Kicks",
CustomID: CustomIDHelpers.CreateButtonIDWithState(
"config-channels",
nameof(LogChannelType.GuildMemberKick)
)
),
]
),
new ActionRowComponent(
[
new ButtonComponent(
ButtonComponentStyle.Primary,
Label: "Bans",
CustomID: CustomIDHelpers.CreateButtonIDWithState(
"config-channels",
nameof(LogChannelType.GuildBanAdd)
)
),
new ButtonComponent(
ButtonComponentStyle.Primary,
Label: "Unbans",
CustomID: CustomIDHelpers.CreateButtonIDWithState(
"config-channels",
nameof(LogChannelType.GuildBanRemove)
)
),
new ButtonComponent(
ButtonComponentStyle.Primary,
Label: "New invites",
CustomID: CustomIDHelpers.CreateButtonIDWithState(
"config-channels",
nameof(LogChannelType.InviteCreate)
)
),
new ButtonComponent(
ButtonComponentStyle.Primary,
Label: "Deleted invites",
CustomID: CustomIDHelpers.CreateButtonIDWithState(
"config-channels",
nameof(LogChannelType.InviteDelete)
)
),
new ButtonComponent(
ButtonComponentStyle.Primary,
Label: "Edited messages",
CustomID: CustomIDHelpers.CreateButtonIDWithState(
"config-channels",
nameof(LogChannelType.MessageUpdate)
)
),
]
),
new ActionRowComponent(
[
new ButtonComponent(
ButtonComponentStyle.Primary,
Label: "Deleted messages",
CustomID: CustomIDHelpers.CreateButtonIDWithState(
"config-channels",
nameof(LogChannelType.MessageDelete)
)
),
new ButtonComponent(
ButtonComponentStyle.Primary,
Label: "Bulk deleted messages",
CustomID: CustomIDHelpers.CreateButtonIDWithState(
"config-channels",
nameof(LogChannelType.MessageDeleteBulk)
)
),
new ButtonComponent(
ButtonComponentStyle.Secondary,
Label: "Close",
CustomID: CustomIDHelpers.CreateButtonIDWithState(
"config-channels",
"close"
)
),
]
),
];
return (embeds, components);
string PrettyChannelString(ulong id)
{
if (id == 0) return "Not set";
if (guildChannels.All(c => c.ID != id)) return $"unknown channel {id}";
if (id == 0)
return "Not set";
if (guildChannels.All(c => c.ID != id))
return $"unknown channel {id}";
return $"<#{id}>";
}
}
public static string PrettyLogTypeName(LogChannelType type) => type switch
{
LogChannelType.GuildUpdate => "Server changes",
LogChannelType.GuildEmojisUpdate => "Emoji changes",
LogChannelType.GuildRoleCreate => "New roles",
LogChannelType.GuildRoleUpdate => "Edited roles",
LogChannelType.GuildRoleDelete => "Deleted roles",
LogChannelType.ChannelCreate => "New channels",
LogChannelType.ChannelUpdate => "Edited channels",
LogChannelType.ChannelDelete => "Deleted channels",
LogChannelType.GuildMemberAdd => "Members joining",
LogChannelType.GuildMemberUpdate => "Members leaving",
LogChannelType.GuildKeyRoleUpdate => "Key role changes",
LogChannelType.GuildMemberNickUpdate => "Member name changes",
LogChannelType.GuildMemberAvatarUpdate => "Member avatar changes",
LogChannelType.GuildMemberRemove => "Members leaving",
LogChannelType.GuildMemberKick => "Kicks",
LogChannelType.GuildBanAdd => "Bans",
LogChannelType.GuildBanRemove => "Unbans",
LogChannelType.InviteCreate => "New invites",
LogChannelType.InviteDelete => "Deleted invites",
LogChannelType.MessageUpdate => "Edited messages",
LogChannelType.MessageDelete => "Deleted messages",
LogChannelType.MessageDeleteBulk => "Bulk deleted messages",
_ => throw new ArgumentOutOfRangeException(nameof(type), type, "Invalid LogChannelType value")
};
}
public static string PrettyLogTypeName(LogChannelType type) =>
type switch
{
LogChannelType.GuildUpdate => "Server changes",
LogChannelType.GuildEmojisUpdate => "Emoji changes",
LogChannelType.GuildRoleCreate => "New roles",
LogChannelType.GuildRoleUpdate => "Edited roles",
LogChannelType.GuildRoleDelete => "Deleted roles",
LogChannelType.ChannelCreate => "New channels",
LogChannelType.ChannelUpdate => "Edited channels",
LogChannelType.ChannelDelete => "Deleted channels",
LogChannelType.GuildMemberAdd => "Members joining",
LogChannelType.GuildMemberUpdate => "Members leaving",
LogChannelType.GuildKeyRoleUpdate => "Key role changes",
LogChannelType.GuildMemberNickUpdate => "Member name changes",
LogChannelType.GuildMemberAvatarUpdate => "Member avatar changes",
LogChannelType.GuildMemberRemove => "Members leaving",
LogChannelType.GuildMemberKick => "Kicks",
LogChannelType.GuildBanAdd => "Bans",
LogChannelType.GuildBanRemove => "Unbans",
LogChannelType.InviteCreate => "New invites",
LogChannelType.InviteDelete => "Deleted invites",
LogChannelType.MessageUpdate => "Edited messages",
LogChannelType.MessageDelete => "Deleted messages",
LogChannelType.MessageDeleteBulk => "Bulk deleted messages",
_ => throw new ArgumentOutOfRangeException(
nameof(type),
type,
"Invalid LogChannelType value"
),
};
}

View file

@ -27,7 +27,8 @@ public class ChannelCommandsComponents(
ContextInjectionService contextInjection,
IFeedbackService feedbackService,
IDiscordRestInteractionAPI interactionApi,
InMemoryDataService<Snowflake, ChannelCommandData> dataService) : InteractionGroup
InMemoryDataService<Snowflake, ChannelCommandData> dataService
) : InteractionGroup
{
private readonly ILogger _logger = logger.ForContext<ChannelCommandsComponents>();
@ -35,11 +36,16 @@ public class ChannelCommandsComponents(
[SuppressInteractionResponse(true)]
public async Task<Result> OnButtonPressedAsync(string state)
{
if (contextInjection.Context is not IInteractionCommandContext ctx) throw new CataloggerError("No context");
if (!ctx.TryGetUserID(out var userId)) throw new CataloggerError("No user ID in context");
if (!ctx.Interaction.Message.TryGet(out var msg)) throw new CataloggerError("No message ID in context");
if (!ctx.TryGetGuildID(out var guildId)) throw new CataloggerError("No guild ID in context");
if (!guildCache.TryGet(guildId, out var guild)) throw new CataloggerError("Guild not in cache");
if (contextInjection.Context is not IInteractionCommandContext ctx)
throw new CataloggerError("No context");
if (!ctx.TryGetUserID(out var userId))
throw new CataloggerError("No user ID in context");
if (!ctx.Interaction.Message.TryGet(out var msg))
throw new CataloggerError("No message ID in context");
if (!ctx.TryGetGuildID(out var guildId))
throw new CataloggerError("No guild ID in context");
if (!guildCache.TryGet(guildId, out var guild))
throw new CataloggerError("Guild not in cache");
var guildChannels = channelCache.GuildChannels(guildId).ToList();
var guildConfig = await db.GetGuildAsync(guildId);
@ -47,20 +53,27 @@ public class ChannelCommandsComponents(
await using var lease = result.GetOrThrow();
if (lease.Data.UserId != userId)
{
return (Result)await feedbackService.SendContextualAsync("This is not your configuration menu.",
options: new FeedbackMessageOptions(MessageFlags: MessageFlags.Ephemeral));
return (Result)
await feedbackService.SendContextualAsync(
"This is not your configuration menu.",
options: new FeedbackMessageOptions(MessageFlags: MessageFlags.Ephemeral)
);
}
switch (state)
{
case "close":
return await interactionApi.UpdateMessageAsync(ctx.Interaction,
new InteractionMessageCallbackData(Components: Array.Empty<IMessageComponent>()));
return await interactionApi.UpdateMessageAsync(
ctx.Interaction,
new InteractionMessageCallbackData(Components: Array.Empty<IMessageComponent>())
);
case "reset":
if (lease.Data.CurrentPage == null)
throw new CataloggerError("CurrentPage was null in reset button callback");
if (!Enum.TryParse<LogChannelType>(lease.Data.CurrentPage, out var channelType))
throw new CataloggerError($"Invalid config-channels CurrentPage: '{lease.Data.CurrentPage}'");
throw new CataloggerError(
$"Invalid config-channels CurrentPage: '{lease.Data.CurrentPage}'"
);
// TODO: figure out some way to make this less verbose?
switch (channelType)
@ -140,8 +153,10 @@ public class ChannelCommandsComponents(
goto case "return";
case "return":
var (e, c) = ChannelCommands.BuildRootMenu(guildChannels, guild, guildConfig);
await interactionApi.UpdateMessageAsync(ctx.Interaction,
new InteractionMessageCallbackData(Embeds: e, Components: c));
await interactionApi.UpdateMessageAsync(
ctx.Interaction,
new InteractionMessageCallbackData(Embeds: e, Components: c)
);
lease.Data = new ChannelCommandData(userId, CurrentPage: null);
return Result.Success;
}
@ -151,9 +166,12 @@ public class ChannelCommandsComponents(
var channelId = WebhookExecutorService.GetDefaultLogChannel(guildConfig, logChannelType);
string? channelMention;
if (channelId is 0) channelMention = null;
else if (guildChannels.All(c => c.ID != channelId)) channelMention = $"unknown channel {channelId}";
else channelMention = $"<#{channelId}>";
if (channelId is 0)
channelMention = null;
else if (guildChannels.All(c => c.ID != channelId))
channelMention = $"unknown channel {channelId}";
else
channelMention = $"<#{channelId}>";
List<IEmbed> embeds =
[
@ -161,43 +179,69 @@ public class ChannelCommandsComponents(
Title: ChannelCommands.PrettyLogTypeName(logChannelType),
Description: channelMention == null
? "This event is not currently logged.\nTo start logging it somewhere, select a channel below."
: $"This event is currently set to log to {channelMention}." +
"\nTo change where it is logged, select a channel below." +
"\nTo disable logging this event entirely, select \"Stop logging\" below.",
Colour: DiscordUtils.Purple)
: $"This event is currently set to log to {channelMention}."
+ "\nTo change where it is logged, select a channel below."
+ "\nTo disable logging this event entirely, select \"Stop logging\" below.",
Colour: DiscordUtils.Purple
),
];
List<IMessageComponent> components =
[
new ActionRowComponent(new[]
{
new ChannelSelectComponent(CustomID: CustomIDHelpers.CreateSelectMenuID("config-channels"),
ChannelTypes: new[] { ChannelType.GuildText })
}),
new ActionRowComponent(new[]
{
new ButtonComponent(ButtonComponentStyle.Danger, Label: "Stop logging",
CustomID: CustomIDHelpers.CreateButtonIDWithState("config-channels", "reset"),
IsDisabled: channelMention == null),
new ButtonComponent(ButtonComponentStyle.Secondary, Label: "Return to menu",
CustomID: CustomIDHelpers.CreateButtonIDWithState("config-channels", "return"))
})
new ActionRowComponent(
new[]
{
new ChannelSelectComponent(
CustomID: CustomIDHelpers.CreateSelectMenuID("config-channels"),
ChannelTypes: new[] { ChannelType.GuildText }
),
}
),
new ActionRowComponent(
new[]
{
new ButtonComponent(
ButtonComponentStyle.Danger,
Label: "Stop logging",
CustomID: CustomIDHelpers.CreateButtonIDWithState(
"config-channels",
"reset"
),
IsDisabled: channelMention == null
),
new ButtonComponent(
ButtonComponentStyle.Secondary,
Label: "Return to menu",
CustomID: CustomIDHelpers.CreateButtonIDWithState(
"config-channels",
"return"
)
),
}
),
];
lease.Data = new ChannelCommandData(userId, CurrentPage: state);
return await interactionApi.UpdateMessageAsync(ctx.Interaction,
new InteractionMessageCallbackData(Embeds: embeds, Components: components));
return await interactionApi.UpdateMessageAsync(
ctx.Interaction,
new InteractionMessageCallbackData(Embeds: embeds, Components: components)
);
}
[SelectMenu("config-channels")]
[SuppressInteractionResponse(true)]
public async Task<Result> OnMenuSelectionAsync(IReadOnlyList<IPartialChannel> channels)
{
if (contextInjection.Context is not IInteractionCommandContext ctx) throw new CataloggerError("No context");
if (!ctx.TryGetUserID(out var userId)) throw new CataloggerError("No user ID in context");
if (!ctx.Interaction.Message.TryGet(out var msg)) throw new CataloggerError("No message ID in context");
if (!ctx.TryGetGuildID(out var guildId)) throw new CataloggerError("No guild ID in context");
if (!guildCache.TryGet(guildId, out var guild)) throw new CataloggerError("Guild not in cache");
if (contextInjection.Context is not IInteractionCommandContext ctx)
throw new CataloggerError("No context");
if (!ctx.TryGetUserID(out var userId))
throw new CataloggerError("No user ID in context");
if (!ctx.Interaction.Message.TryGet(out var msg))
throw new CataloggerError("No message ID in context");
if (!ctx.TryGetGuildID(out var guildId))
throw new CataloggerError("No guild ID in context");
if (!guildCache.TryGet(guildId, out var guild))
throw new CataloggerError("Guild not in cache");
var guildConfig = await db.GetGuildAsync(guildId);
var channelId = channels[0].ID.ToUlong();
@ -205,12 +249,17 @@ public class ChannelCommandsComponents(
await using var lease = result.GetOrThrow();
if (lease.Data.UserId != userId)
{
return (Result)await feedbackService.SendContextualAsync("This is not your configuration menu.",
options: new FeedbackMessageOptions(MessageFlags: MessageFlags.Ephemeral));
return (Result)
await feedbackService.SendContextualAsync(
"This is not your configuration menu.",
options: new FeedbackMessageOptions(MessageFlags: MessageFlags.Ephemeral)
);
}
if (!Enum.TryParse<LogChannelType>(lease.Data.CurrentPage, out var channelType))
throw new CataloggerError($"Invalid config-channels CurrentPage '{lease.Data.CurrentPage}'");
throw new CataloggerError(
$"Invalid config-channels CurrentPage '{lease.Data.CurrentPage}'"
);
switch (channelType)
{
@ -291,32 +340,53 @@ public class ChannelCommandsComponents(
[
new Embed(
Title: ChannelCommands.PrettyLogTypeName(channelType),
Description: $"This event is currently set to log to <#{channelId}>." +
"\nTo change where it is logged, select a channel below." +
"\nTo disable logging this event entirely, select \"Stop logging\" below.",
Colour: DiscordUtils.Purple)
Description: $"This event is currently set to log to <#{channelId}>."
+ "\nTo change where it is logged, select a channel below."
+ "\nTo disable logging this event entirely, select \"Stop logging\" below.",
Colour: DiscordUtils.Purple
),
];
List<IMessageComponent> components =
[
new ActionRowComponent(new[]
{
new ChannelSelectComponent(CustomID: CustomIDHelpers.CreateSelectMenuID("config-channels"),
ChannelTypes: new[] { ChannelType.GuildText })
}),
new ActionRowComponent(new[]
{
new ButtonComponent(ButtonComponentStyle.Danger, Label: "Stop logging",
CustomID: CustomIDHelpers.CreateButtonIDWithState("config-channels", "reset")),
new ButtonComponent(ButtonComponentStyle.Secondary, Label: "Return to menu",
CustomID: CustomIDHelpers.CreateButtonIDWithState("config-channels", "return"))
})
new ActionRowComponent(
new[]
{
new ChannelSelectComponent(
CustomID: CustomIDHelpers.CreateSelectMenuID("config-channels"),
ChannelTypes: new[] { ChannelType.GuildText }
),
}
),
new ActionRowComponent(
new[]
{
new ButtonComponent(
ButtonComponentStyle.Danger,
Label: "Stop logging",
CustomID: CustomIDHelpers.CreateButtonIDWithState(
"config-channels",
"reset"
)
),
new ButtonComponent(
ButtonComponentStyle.Secondary,
Label: "Return to menu",
CustomID: CustomIDHelpers.CreateButtonIDWithState(
"config-channels",
"return"
)
),
}
),
];
lease.Data = lease.Data with { UserId = userId };
return await interactionApi.UpdateMessageAsync(ctx.Interaction,
new InteractionMessageCallbackData(Embeds: embeds, Components: components));
return await interactionApi.UpdateMessageAsync(
ctx.Interaction,
new InteractionMessageCallbackData(Embeds: embeds, Components: components)
);
}
}
public record ChannelCommandData(Snowflake UserId, string? CurrentPage);
public record ChannelCommandData(Snowflake UserId, string? CurrentPage);

View file

@ -22,41 +22,52 @@ public class KeyRoleCommands(
ContextInjectionService contextInjection,
IFeedbackService feedbackService,
GuildCache guildCache,
RoleCache roleCache) : CommandGroup
RoleCache roleCache
) : CommandGroup
{
[Command("list")]
[Description("List this server's key roles.")]
public async Task<IResult> ListKeyRolesAsync()
{
var (_, guildId) = contextInjection.GetUserAndGuild();
if (!guildCache.TryGet(guildId, out var guild)) throw new CataloggerError("Guild not in cache");
if (!guildCache.TryGet(guildId, out var guild))
throw new CataloggerError("Guild not in cache");
var guildRoles = roleCache.GuildRoles(guildId).ToList();
var guildConfig = await db.GetGuildAsync(guildId);
if (guildConfig.KeyRoles.Count == 0)
return await feedbackService.SendContextualAsync(
"There are no key roles to list. Add some with `/key-roles add`.");
"There are no key roles to list. Add some with `/key-roles add`."
);
var description = string.Join("\n", guildConfig.KeyRoles.Select(id =>
{
var role = guildRoles.FirstOrDefault(r => r.ID.Value == id);
return role != null ? $"- {role.Name} <@&{role.ID}>" : $"- unknown role {id}";
}));
var description = string.Join(
"\n",
guildConfig.KeyRoles.Select(id =>
{
var role = guildRoles.FirstOrDefault(r => r.ID.Value == id);
return role != null ? $"- {role.Name} <@&{role.ID}>" : $"- unknown role {id}";
})
);
return await feedbackService.SendContextualEmbedAsync(new Embed(
Title: $"Key roles for {guild.Name}",
Description: description,
Colour: DiscordUtils.Purple));
return await feedbackService.SendContextualEmbedAsync(
new Embed(
Title: $"Key roles for {guild.Name}",
Description: description,
Colour: DiscordUtils.Purple
)
);
}
[Command("add")]
[Description("Add a new key role.")]
public async Task<IResult> AddKeyRoleAsync(
[Description("The role to add.")] [DiscordTypeHint(TypeHint.Role)] Snowflake roleId)
[Description("The role to add.")] [DiscordTypeHint(TypeHint.Role)] Snowflake roleId
)
{
var (_, guildId) = contextInjection.GetUserAndGuild();
var role = roleCache.GuildRoles(guildId).FirstOrDefault(r => r.ID == roleId);
if (role == null) throw new CataloggerError("Role is not cached");
if (role == null)
throw new CataloggerError("Role is not cached");
var guildConfig = await db.GetGuildAsync(guildId);
if (guildConfig.KeyRoles.Any(id => role.ID == id))
@ -66,27 +77,34 @@ public class KeyRoleCommands(
db.Update(guildConfig);
await db.SaveChangesAsync();
return await feedbackService.SendContextualAsync($"Added {role.Name} to this server's key roles!");
return await feedbackService.SendContextualAsync(
$"Added {role.Name} to this server's key roles!"
);
}
[Command("remove")]
[Description("Remove a key role.")]
public async Task<IResult> RemoveKeyRoleAsync(
[Description("The role to remove.")] [DiscordTypeHint(TypeHint.Role)]
Snowflake roleId)
[Description("The role to remove.")] [DiscordTypeHint(TypeHint.Role)] Snowflake roleId
)
{
var (_, guildId) = contextInjection.GetUserAndGuild();
var role = roleCache.GuildRoles(guildId).FirstOrDefault(r => r.ID == roleId);
if (role == null) throw new CataloggerError("Role is not cached");
if (role == null)
throw new CataloggerError("Role is not cached");
var guildConfig = await db.GetGuildAsync(guildId);
if (guildConfig.KeyRoles.All(id => role.ID != id))
return await feedbackService.SendContextualAsync($"{role.Name} is already not a key role.");
return await feedbackService.SendContextualAsync(
$"{role.Name} is already not a key role."
);
guildConfig.KeyRoles.Remove(role.ID.Value);
db.Update(guildConfig);
await db.SaveChangesAsync();
return await feedbackService.SendContextualAsync($"Removed {role.Name} from this server's key roles!");
return await feedbackService.SendContextualAsync(
$"Removed {role.Name} from this server's key roles!"
);
}
}
}

View file

@ -32,7 +32,8 @@ public class MetaCommands(
ContextInjectionService contextInjection,
GuildCache guildCache,
ChannelCache channelCache,
IDiscordRestChannelAPI channelApi) : CommandGroup
IDiscordRestChannelAPI channelApi
) : CommandGroup
{
private readonly ILogger _logger = logger.ForContext<MetaCommands>();
private readonly HttpClient _client = new();
@ -41,12 +42,14 @@ public class MetaCommands(
[Description("Ping pong! See the bot's latency")]
public async Task<IResult> PingAsync()
{
var shardId = contextInjection.Context?.TryGetGuildID(out var guildId) == true
? client.ShardIdFor(guildId.Value)
: 0;
var shardId =
contextInjection.Context?.TryGetGuildID(out var guildId) == true
? client.ShardIdFor(guildId.Value)
: 0;
var averageLatency = client.Shards.Values.Select(x => x.Latency.TotalMilliseconds).Sum() /
client.Shards.Count;
var averageLatency =
client.Shards.Values.Select(x => x.Latency.TotalMilliseconds).Sum()
/ client.Shards.Count;
var t1 = clock.GetCurrentInstant();
var msg = await feedbackService.SendContextualAsync("...").GetOrThrow();
@ -57,42 +60,54 @@ public class MetaCommands(
var embed = new EmbedBuilder()
.WithColour(DiscordUtils.Purple)
.WithFooter($"{RuntimeInformation.FrameworkDescription} on {RuntimeInformation.RuntimeIdentifier}")
.WithFooter(
$"{RuntimeInformation.FrameworkDescription} on {RuntimeInformation.RuntimeIdentifier}"
)
.WithCurrentTimestamp();
embed.AddField("Ping",
$"Gateway: {client.Shards[shardId].Latency.TotalMilliseconds:N0}ms (average: {averageLatency:N0}ms)\n" +
$"API: {elapsed.TotalMilliseconds:N0}ms",
inline: true);
embed.AddField(
"Ping",
$"Gateway: {client.Shards[shardId].Latency.TotalMilliseconds:N0}ms (average: {averageLatency:N0}ms)\n"
+ $"API: {elapsed.TotalMilliseconds:N0}ms",
inline: true
);
embed.AddField("Memory usage", memoryUsage.Bytes().Humanize(), inline: true);
var messageRate = await MessagesRate();
embed.AddField("Messages received",
embed.AddField(
"Messages received",
messageRate != null
? $"{messageRate / 5:F1}/m\n({CataloggerMetrics.MessagesReceived.Value:N0} since last restart)"
: $"{CataloggerMetrics.MessagesReceived.Value:N0} since last restart",
true);
true
);
embed.AddField("Shard", $"{shardId + 1} of {client.Shards.Count}", true);
embed.AddField("Uptime",
$"{(CataloggerMetrics.Startup - clock.GetCurrentInstant()).Prettify(TimeUnit.Second)}\n" +
$"since <t:{CataloggerMetrics.Startup.ToUnixTimeSeconds()}:F>",
true);
embed.AddField(
"Uptime",
$"{(CataloggerMetrics.Startup - clock.GetCurrentInstant()).Prettify(TimeUnit.Second)}\n"
+ $"since <t:{CataloggerMetrics.Startup.ToUnixTimeSeconds()}:F>",
true
);
embed.AddField("Numbers",
$"{CataloggerMetrics.MessagesStored.Value:N0} messages " +
$"from {guildCache.Size:N0} servers\nCached {channelCache.Size:N0} channels",
false);
embed.AddField(
"Numbers",
$"{CataloggerMetrics.MessagesStored.Value:N0} messages "
+ $"from {guildCache.Size:N0} servers\nCached {channelCache.Size:N0} channels",
false
);
IEmbed[] embeds = [embed.Build().GetOrThrow()];
return (Result)await channelApi.EditMessageAsync(msg.ChannelID, msg.ID, content: "", embeds: embeds);
return (Result)
await channelApi.EditMessageAsync(msg.ChannelID, msg.ID, content: "", embeds: embeds);
}
// TODO: add more checks around response format, configurable prometheus endpoint
private async Task<double?> MessagesRate()
{
if (!config.Logging.EnableMetrics) return null;
if (!config.Logging.EnableMetrics)
return null;
try
{
@ -118,4 +133,4 @@ public class MetaCommands(
private record PrometheusResult(object[] value);
// ReSharper restore InconsistentNaming, ClassNeverInstantiated.Local
}
}