Skip to content

Commit

Permalink
Run code cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
Erisa committed Aug 11, 2024
1 parent 6d8db2a commit 1b64fa5
Show file tree
Hide file tree
Showing 15 changed files with 82 additions and 76 deletions.
32 changes: 16 additions & 16 deletions Commands/Debug.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
internal class Debug : BaseCommandModule
{
public static Dictionary<ulong, PendingUserOverride> OverridesPendingAddition = new();

[Group("debug")]
[Aliases("troubleshoot", "unbug", "bugn't", "helpsomethinghasgoneverywrong")]
[Description("Commands and things for fixing the bot in the unlikely event that it breaks a bit.")]
Expand Down Expand Up @@ -222,7 +222,7 @@ public async Task CheckPendingChannelEvents(CommandContext ctx)
{
var pendingUpdateEvents = Tasks.EventTasks.PendingChannelUpdateEvents;
var pendingDeleteEvents = Tasks.EventTasks.PendingChannelDeleteEvents;

if (pendingUpdateEvents.Count == 0 && pendingDeleteEvents.Count == 0)
{
await ctx.RespondAsync("There are no pending channel events left to handle!");
Expand All @@ -249,7 +249,7 @@ public async Task CheckPendingChannelEvents(CommandContext ctx)
}
list += "```\n";
}

await ctx.RespondAsync(await StringHelpers.CodeOrHasteBinAsync(list));
}

Expand Down Expand Up @@ -313,7 +313,7 @@ public async Task Import(CommandContext ctx,
{
// Import overrides
var (success, failedOverwrite) = await ImportOverridesFromChannelAsync(channel);

if (success)
await ctx.RespondAsync($"{Program.cfgjson.Emoji.Success} Overrides for {channel.Mention} imported successfully!");
else
Expand All @@ -327,7 +327,7 @@ await ctx.RespondAsync(
public async Task ImportAll(CommandContext ctx)
{
var msg = await ctx.RespondAsync($"{Program.cfgjson.Emoji.Loading} Working...");

// Get all channels
var channels = await ctx.Guild.GetChannelsAsync();

Expand All @@ -340,7 +340,7 @@ public async Task ImportAll(CommandContext ctx)

if (!success) anyImportFailed = true;
}

if (anyImportFailed)
await msg.ModifyAsync($"{Program.cfgjson.Emoji.Error} Some overrides failed to import. Most likely this means I found overrides in the database but couldn't parse them. Check the database manually for details.");
else
Expand All @@ -362,13 +362,13 @@ public async Task Add(CommandContext ctx,

var confirmButton = new DiscordButtonComponent(DiscordButtonStyle.Success, "debug-overrides-add-confirm-callback", "Yes");
var cancelButton = new DiscordButtonComponent(DiscordButtonStyle.Danger, "debug-overrides-add-cancel-callback", "No");

var confirmationMessage = await ctx.RespondAsync(new DiscordMessageBuilder().WithContent(
$"{Program.cfgjson.Emoji.ShieldHelp} Just to confirm, you want to add the following override for {user.Mention} to {channel.Mention}?\n" +
$"**Allowed:** {parsedAllowedPerms}\n" +
$"**Denied:** {parsedDeniedPerms}\n")
.AddComponents([confirmButton, cancelButton]));

OverridesPendingAddition.Add(confirmationMessage.Id, new PendingUserOverride
{
ChannelId = channel.Id,
Expand Down Expand Up @@ -419,7 +419,7 @@ public async Task Apply(CommandContext ctx,
[Description("The user whose overrides to apply.")] DiscordUser user)
{
var msg = await ctx.RespondAsync($"{Program.cfgjson.Emoji.Loading} Working on it...");

// Try fetching member to determine whether they are in the server. If they are not, we can't apply overrides for them.
DiscordMember member;
try
Expand All @@ -431,7 +431,7 @@ public async Task Apply(CommandContext ctx,
await ctx.RespondAsync($"{Program.cfgjson.Emoji.Error} That user isn't in the server! I can't apply overrides for them.");
return;
}

var userOverwrites = await Program.db.HashGetAsync("overrides", member.Id.ToString());
if (string.IsNullOrWhiteSpace(userOverwrites))
{
Expand Down Expand Up @@ -469,13 +469,13 @@ public async Task Apply(CommandContext ctx,
await ctx.RespondAsync($"{Program.cfgjson.Emoji.Error} I don't have permission to add overrides in {channel.Mention}! Continuing...");
numAppliedOverrides--;
}

}

await msg.ModifyAsync(x => x.Content = $"{Program.cfgjson.Emoji.Success} Successfully applied {numAppliedOverrides}/{dictionary.Count} overrides for {user.Mention}!");
}
}

[Command("dumpchanneloverrides")]
[Description("Dump all of a channel's overrides. This pulls from Discord, not the database.")]
[IsBotOwner]
Expand All @@ -489,7 +489,7 @@ public async Task DumpChannelOverrides(CommandContext ctx,
{
output += $"{JsonConvert.SerializeObject(overwrite)}\n";
}

await ctx.RespondAsync(await StringHelpers.CodeOrHasteBinAsync(output, "json"));
}

Expand Down Expand Up @@ -542,7 +542,7 @@ public async Task DumpRawMessage(CommandContext ctx, [Description("The message w
if (Constants.RegexConstants.discord_link_rx.IsMatch(msgLinkOrId))
{
// Assume the user provided a message link. Extract channel and message IDs to get message content.

// Pattern to extract channel and message IDs from URL
var idPattern = new Regex(@"(?:.*\/)([0-9]+)\/([0-9]+)$");

Expand All @@ -560,7 +560,7 @@ public async Task DumpRawMessage(CommandContext ctx, [Description("The message w
await ctx.RespondAsync($"{Program.cfgjson.Emoji.Error} I couldn't fetch the channel from your message link! Please try again.");
return;
}

// Get message ID
var targetMessage = Convert.ToUInt64(idPattern.Match(msgLinkOrId).Groups[2].ToString().Replace("/", ""));

Expand Down Expand Up @@ -613,7 +613,7 @@ public async Task DumpRawMessage(CommandContext ctx, [Description("The message w
{
// Imports overrides from the specified channel to the database. See 'debug overrides import' and 'debug overrides importall'
// Return (true, 0) on success, (false, <ID of failed overwrite>) on failure

// Import all overrides for channel to db
foreach (var overwrite in channel.PermissionOverwrites)
{
Expand Down
2 changes: 1 addition & 1 deletion Commands/InteractionCommands/DebugInteractions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ public async Task ScamCheck(InteractionContext ctx, [Option("input", "Domain or
}

responseToSend += await StringHelpers.CodeOrHasteBinAsync(responseText, "json");

await ctx.RespondAsync(responseToSend);
}
else
Expand Down
2 changes: 1 addition & 1 deletion Commands/InteractionCommands/MuteInteractions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ public async Task TqsMuteSlashCommand(
{
// blah
}

if (await Program.db.HashExistsAsync("mutes", targetUser.Id) || (targetMember is not null && (targetMember.Roles.Contains(mutedRole) || targetMember.Roles.Contains(tqsMutedRole))))
{
await ctx.EditResponseAsync(new DiscordWebhookBuilder().WithContent($"{Program.cfgjson.Emoji.Error} {ctx.User.Mention}, that user is already muted."));
Expand Down
2 changes: 1 addition & 1 deletion Commands/InteractionCommands/WarningInteractions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ public async Task TransferWarningsSlashCommand(InteractionContext ctx,
await ctx.FollowUpAsync(new DiscordFollowupMessageBuilder().WithContent($"{Program.cfgjson.Emoji.Error} The source and target users cannot be the same!"));
return;
}

var sourceWarnings = await Program.db.HashGetAllAsync(sourceUser.Id.ToString());
var targetWarnings = await Program.db.HashGetAllAsync(targetUser.Id.ToString());

Expand Down
2 changes: 1 addition & 1 deletion Commands/Mutes.cs
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ public async Task TqsMuteCmd(
{
// blah
}

if (await Program.db.HashExistsAsync("mutes", targetUser.Id) || (targetMember != default && (targetMember.Roles.Contains(mutedRole) || targetMember.Roles.Contains(tqsMutedRole))))
{
await ctx.RespondAsync($"{Program.cfgjson.Emoji.Error} {ctx.User.Mention}, that user is already muted.");
Expand Down
4 changes: 2 additions & 2 deletions Commands/Warnings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,7 @@ public async Task WarnDetailsCmd(
await ctx.RespondAsync($"{Program.cfgjson.Emoji.Error} I couldn't find a warning for that user with that ID! Please check again.");
else if (warning.Type == WarningType.Note)
{
await ctx.RespondAsync($"{Program.cfgjson.Emoji.Error} That's a note, not a warning! Try using `/note details` instead, or make sure you've got the right warning ID.");
await ctx.RespondAsync($"{Program.cfgjson.Emoji.Error} That's a note, not a warning! Try using `/note details` instead, or make sure you've got the right warning ID.");
}
else
await ctx.RespondAsync(null, await FancyWarnEmbedAsync(warning, true, userID: targetUser.Id));
Expand Down Expand Up @@ -299,7 +299,7 @@ public async Task MostWarningsDayCmd(CommandContext ctx)
foreach (var warning in warningsOutput)
{
if (warning.Value.Type != WarningType.Warning) continue;

var day = warning.Value.WarnTimestamp.ToString("yyyy-MM-dd");
if (!counts.ContainsKey(day))
{
Expand Down
2 changes: 1 addition & 1 deletion Events/ChannelEvents.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
{
public class ChannelEvents
{
public static async Task ChannelUpdated(DiscordClient _, ChannelUpdatedEventArgs e)
public static async Task ChannelUpdated(DiscordClient _, ChannelUpdatedEventArgs e)
{
// Add this event to the pending events list. These are handled in a task later, see Tasks/EventTasks/HandlePendingChannelUpdateEventsAsync
// using DateTime might seem weird, but it's something that is unique for each event
Expand Down
48 changes: 24 additions & 24 deletions Events/InteractionEvents.cs
Original file line number Diff line number Diff line change
Expand Up @@ -69,25 +69,25 @@ await LogChannelHelper.LogDeletedMessagesAsync(
else if (e.Id == "debug-overrides-add-confirm-callback")
{
await e.Interaction.CreateResponseAsync(DiscordInteractionResponseType.DeferredMessageUpdate);

var overridesPendingAddition = Commands.Debug.OverridesPendingAddition;
if (!overridesPendingAddition.ContainsKey(e.Message.Id))
{
await e.Channel.SendMessageAsync(new DiscordMessageBuilder().WithContent($"{cfgjson.Emoji.Error} {e.User.Mention}, this action has already been completed!").WithReply(e.Message.Id));

// Remove buttons from original message so this doesn't happen again
var originalMsgWithoutButtons = new DiscordMessageBuilder(e.Message);
originalMsgWithoutButtons.ClearComponents();
await e.Message.ModifyAsync(originalMsgWithoutButtons);

return;
}

// Get override data
var pendingOverride = overridesPendingAddition.GetValueOrDefault(e.Message.Id);
var mockOverwrite = pendingOverride.Overwrite;
var channelId = pendingOverride.ChannelId;

// This is really cursed, but it effectively converts our mock DiscordOverwrite into an actual one so that it can be added to the current list of overwrites.
// Since the mock overwrite serializes into the same format as a DiscordOverwrite, we can serialize it and then deserialize it back to DiscordOverwrite to convert it.
var newOverwrite = JsonConvert.DeserializeObject<DiscordOverwrite>(JsonConvert.SerializeObject(mockOverwrite));
Expand All @@ -97,33 +97,33 @@ await LogChannelHelper.LogDeletedMessagesAsync(
if (userOverwrites.IsNullOrEmpty)
{
// No overwrites for this user yet, create a list and add to it

var overwrites = new Dictionary<string, DiscordOverwrite> { { channelId.ToString(), newOverwrite } };
await db.HashSetAsync("overrides", mockOverwrite.Id, JsonConvert.SerializeObject(overwrites));
}
else
{
// Overwrites for user exist, add to them

var overwrites = JsonConvert.DeserializeObject<Dictionary<string, DiscordOverwrite>>(userOverwrites);
if (overwrites.ContainsKey(channelId.ToString()))
{
// Require extra confirmation for merging permissions!
var mergeConfirmResponse = new DiscordMessageBuilder()
.WithContent($"{cfgjson.Emoji.Warning} **Caution:** This user already has an override for <#{channelId}>! Do you want to merge the permissions? Here are their **current** permissions:\n**Allowed:** {overwrites[channelId.ToString()].Allowed}\n**Denied:** {overwrites[channelId.ToString()].Denied}")
.AddComponents(new DiscordButtonComponent(DiscordButtonStyle.Danger, "debug-overrides-add-merge-confirm-callback", "Merge"), new DiscordButtonComponent(DiscordButtonStyle.Primary, "debug-overrides-add-cancel-callback", "Cancel"));

await e.Message.ModifyAsync(mergeConfirmResponse);
return;
}
else
{
overwrites.Add(channelId.ToString(), newOverwrite);
overwrites.Add(channelId.ToString(), newOverwrite);
}
// Update db
await db.HashSetAsync("overrides", mockOverwrite.Id, JsonConvert.SerializeObject(overwrites));
}

// Remove from db so the override is not added again
overridesPendingAddition.Remove(e.Message.Id);

Expand All @@ -133,40 +133,40 @@ await LogChannelHelper.LogDeletedMessagesAsync(
else if (e.Id == "debug-overrides-add-cancel-callback")
{
await e.Interaction.CreateResponseAsync(DiscordInteractionResponseType.DeferredMessageUpdate);

var overridesPendingAddition = Commands.Debug.OverridesPendingAddition;
if (!overridesPendingAddition.ContainsKey(e.Message.Id))
{
await e.Channel.SendMessageAsync(new DiscordMessageBuilder().WithContent($"{cfgjson.Emoji.Error} {e.User.Mention}, this action has already been completed!").WithReply(e.Message.Id));

// Remove buttons from original message so this doesn't happen again
var originalMsgWithoutButtons = new DiscordMessageBuilder(e.Message);
originalMsgWithoutButtons.ClearComponents();
await e.Message.ModifyAsync(originalMsgWithoutButtons);

return;
}

await e.Message.ModifyAsync(new DiscordMessageBuilder().WithContent($"{Program.cfgjson.Emoji.Error} Cancelled! Nothing was changed."));
overridesPendingAddition.Remove(e.Message.Id);
}
else if (e.Id == "debug-overrides-add-merge-confirm-callback")
{
// User already has an overwrite for the requested channel!
// Merge the permissions of the current & new overrides.

await e.Interaction.CreateResponseAsync(DiscordInteractionResponseType.DeferredMessageUpdate);

var overridesPendingAddition = Commands.Debug.OverridesPendingAddition;
if (!overridesPendingAddition.ContainsKey(e.Message.Id))
{
await e.Channel.SendMessageAsync(new DiscordMessageBuilder().WithContent($"{cfgjson.Emoji.Error} {e.User.Mention}, this action has already been completed!").WithReply(e.Message.Id));

// Remove buttons from original message so this doesn't happen again
var originalMsgWithoutButtons = new DiscordMessageBuilder(e.Message);
originalMsgWithoutButtons.ClearComponents();
await e.Message.ModifyAsync(originalMsgWithoutButtons);

return;
}

Expand All @@ -175,11 +175,11 @@ await LogChannelHelper.LogDeletedMessagesAsync(
var mockOverwrite = pendingOverride.Overwrite;
var channelId = pendingOverride.ChannelId;
var newOverwrite = JsonConvert.DeserializeObject<DiscordOverwrite>(JsonConvert.SerializeObject(mockOverwrite));

// Existing override data
var userOverwrites = await db.HashGetAsync("overrides", mockOverwrite.Id);
var overwrites = JsonConvert.DeserializeObject<Dictionary<string, DiscordOverwrite>>(userOverwrites);

// Merge permissions
var existingOverwrite = overwrites[channelId.ToString()];
var newMockOverwrite = new MockUserOverwrite
Expand All @@ -188,15 +188,15 @@ await LogChannelHelper.LogDeletedMessagesAsync(
Allowed = newOverwrite.Allowed | existingOverwrite.Allowed,
Denied = newOverwrite.Denied | existingOverwrite.Denied
};

// Cursed conversion again
newOverwrite = JsonConvert.DeserializeObject<DiscordOverwrite>(JsonConvert.SerializeObject(newMockOverwrite));

overwrites[channelId.ToString()] = newOverwrite;

// Update db
await db.HashSetAsync("overrides", mockOverwrite.Id, JsonConvert.SerializeObject(overwrites));

// Respond
await e.Message.ModifyAsync(new DiscordMessageBuilder().WithContent($"{cfgjson.Emoji.Success} Override successfully added. <@{newOverwrite.Id}> already had an override in <#{pendingOverride.ChannelId}>, so here are their new permissions:\n**Allowed:** {newOverwrite.Allowed}\n**Denied:** {newOverwrite.Denied}"));
}
Expand Down
2 changes: 1 addition & 1 deletion Events/MemberEvents.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ public class MemberEvents
{
public static async Task GuildMemberAdded(DiscordClient client, GuildMemberAddedEventArgs e)
{
client.Logger.LogDebug("Got a member added event for {member}", e.Member.Id);
client.Logger.LogDebug("Got a member added event for {member}", e.Member.Id);

if (e.Guild.Id != cfgjson.ServerID)
return;
Expand Down
Loading

0 comments on commit 1b64fa5

Please sign in to comment.