Skip to content

Commit

Permalink
Automatically delete ban messages for compromised account bans (#251)
Browse files Browse the repository at this point in the history
* Automatically delete ban messages for compromised account bans

* Combine tasks for auto-warn messages & compromised account ban messages

* Fix mistakenly changed comparison when building for Release

* don't send a duplicate ban message for !ban

---------

Co-authored-by: Erisa A <erisa@erisa.uk>
  • Loading branch information
FloatingMilkshake and Erisa authored Dec 26, 2024
1 parent 8139986 commit 0b56658
Show file tree
Hide file tree
Showing 8 changed files with 103 additions and 47 deletions.
10 changes: 0 additions & 10 deletions Commands/Bans.cs
Original file line number Diff line number Diff line change
Expand Up @@ -123,11 +123,6 @@ public async Task BanCmd(CommandContext ctx,
return;
}
}
reason = reason.Replace("`", "\\`").Replace("*", "\\*");
if (banDuration == default)
await ctx.Channel.SendMessageAsync($"{Program.cfgjson.Emoji.Banned} {targetMember.Mention} has been banned: **{reason}**");
else
await ctx.Channel.SendMessageAsync($"{Program.cfgjson.Emoji.Banned} {targetMember.Mention} has been banned for **{TimeHelpers.TimeToPrettyFormat(banDuration, false)}**: **{reason}**");
}

/// I CANNOT find a way to do this as alias so I made it a separate copy of the command.
Expand Down Expand Up @@ -207,11 +202,6 @@ public async Task BankeepCmd(CommandContext ctx,
return;
}
}
reason = reason.Replace("`", "\\`").Replace("*", "\\*");
if (banDuration == default)
await ctx.Channel.SendMessageAsync($"{Program.cfgjson.Emoji.Banned} {targetMember.Mention} has been banned: **{reason}**");
else
await ctx.Channel.SendMessageAsync($"{Program.cfgjson.Emoji.Banned} {targetMember.Mention} has been banned for **{TimeHelpers.TimeToPrettyFormat(banDuration, false)}**: **{reason}**");
}

[Command("unban")]
Expand Down
4 changes: 2 additions & 2 deletions Commands/Debug.cs
Original file line number Diff line number Diff line change
Expand Up @@ -131,14 +131,14 @@ public async Task Refresh(CommandContext ctx)
var msg = await ctx.RespondAsync("Checking for pending scheduled tasks...");
bool bans = await Tasks.PunishmentTasks.CheckBansAsync();
bool mutes = await Tasks.PunishmentTasks.CheckMutesAsync();
bool warns = await Tasks.PunishmentTasks.CheckAutomaticWarningsAsync();
bool punishmentMessages = await Tasks.PunishmentTasks.CleanUpPunishmentMessagesAsync();
bool reminders = await Tasks.ReminderTasks.CheckRemindersAsync();
bool raidmode = await Tasks.RaidmodeTasks.CheckRaidmodeAsync(ctx.Guild.Id);
bool unlocks = await Tasks.LockdownTasks.CheckUnlocksAsync();
bool channelUpdateEvents = await Tasks.EventTasks.HandlePendingChannelUpdateEventsAsync();
bool channelDeleteEvents = await Tasks.EventTasks.HandlePendingChannelDeleteEventsAsync();

await msg.ModifyAsync($"Unban check result: `{bans}`\nUnmute check result: `{mutes}`\nAutomatic warning message check result: `{warns}`\nReminders check result: `{reminders}`\nRaidmode check result: `{raidmode}`\nUnlocks check result: `{unlocks}`\nPending Channel Update events check result: `{channelUpdateEvents}`\nPending Channel Delete events check result: `{channelDeleteEvents}`");
await msg.ModifyAsync($"Unban check result: `{bans}`\nUnmute check result: `{mutes}`\nPunishment message cleanup check result: `{punishmentMessages}`\nReminders check result: `{reminders}`\nRaidmode check result: `{raidmode}`\nUnlocks check result: `{unlocks}`\nPending Channel Update events check result: `{channelUpdateEvents}`\nPending Channel Delete events check result: `{channelDeleteEvents}`");
}

[Command("sh")]
Expand Down
5 changes: 0 additions & 5 deletions Commands/InteractionCommands/BanInteractions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -103,11 +103,6 @@ public async Task BanSlashCommand(InteractionContext ctx,
return;
}
}
reason = reason.Replace("`", "\\`").Replace("*", "\\*");
if (banDuration == default)
await ctx.Channel.SendMessageAsync($"{Program.cfgjson.Emoji.Banned} {user.Mention} has been banned: **{reason}**");
else
await ctx.Channel.SendMessageAsync($"{Program.cfgjson.Emoji.Banned} {user.Mention} has been banned for **{TimeHelpers.TimeToPrettyFormat(banDuration, false)}**: **{reason}**");

webhookOut.Content = $"{Program.cfgjson.Emoji.Success} User was successfully bonked.";
await ctx.EditResponseAsync(webhookOut);
Expand Down
57 changes: 43 additions & 14 deletions Helpers/BanHelpers.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,17 +18,16 @@ public static async Task<bool> BanFromServerAsync(ulong targetUserId, string rea
expireTime = null;
}

MemberPunishment newBan = new()
(DiscordMessage? dmMessage, DiscordMessage? chatMessage) output = new();

reason = reason.Replace("`", "\\`").Replace("*", "\\*");
if (channel is not null)
{
MemberId = targetUserId,
ModId = moderatorId,
ServerId = guild.Id,
ExpireTime = expireTime,
ActionTime = actionTime,
Reason = reason
};

await Program.db.HashSetAsync("bans", targetUserId, JsonConvert.SerializeObject(newBan));
if (banDuration == default)
output.chatMessage = await channel.SendMessageAsync($"{Program.cfgjson.Emoji.Banned} <@{targetUserId}> has been banned: **{reason}**");
else
output.chatMessage = await channel.SendMessageAsync($"{Program.cfgjson.Emoji.Banned} <@{targetUserId}> has been banned for **{TimeHelpers.TimeToPrettyFormat(banDuration, false)}**: **{reason}**");
}

try
{
Expand All @@ -38,24 +37,54 @@ public static async Task<bool> BanFromServerAsync(ulong targetUserId, string rea
if (appealable)
{
if (compromisedAccount)
await targetMember.SendMessageAsync($"{Program.cfgjson.Emoji.Banned} You have been banned from **{guild.Name}**!\nReason: **{reason}**\nYou can appeal the ban here: <{Program.cfgjson.AppealLink}>\nBefore appealing, please follow these steps to protect your account:\n1. Reset your Discord account password. Even if you use MFA, this will reset all session tokens.\n2. Review active sessions and authorised app connections.\n3. Ensure your PC is free of malware.\n4. [Enable MFA](https://support.discord.com/hc/en-us/articles/219576828-Setting-up-Multi-Factor-Authentication) if not already.");
output.dmMessage = await targetMember.SendMessageAsync($"{Program.cfgjson.Emoji.Banned} You have been banned from **{guild.Name}**!\nReason: **{reason}**\nYou can appeal the ban here: <{Program.cfgjson.AppealLink}>\nBefore appealing, please follow these steps to protect your account:\n1. Reset your Discord account password. Even if you use MFA, this will reset all session tokens.\n2. Review active sessions and authorised app connections.\n3. Ensure your PC is free of malware.\n4. [Enable MFA](https://support.discord.com/hc/en-us/articles/219576828-Setting-up-Multi-Factor-Authentication) if not already.");
else
await targetMember.SendMessageAsync($"{Program.cfgjson.Emoji.Banned} You have been banned from **{guild.Name}**!\nReason: **{reason}**\nYou can appeal the ban here: <{Program.cfgjson.AppealLink}>");
output.dmMessage = await targetMember.SendMessageAsync($"{Program.cfgjson.Emoji.Banned} You have been banned from **{guild.Name}**!\nReason: **{reason}**\nYou can appeal the ban here: <{Program.cfgjson.AppealLink}>");
}
else
{
await targetMember.SendMessageAsync($"{Program.cfgjson.Emoji.Banned} You have been permanently banned from **{guild.Name}**!\nReason: **{reason}**");
output.dmMessage = await targetMember.SendMessageAsync($"{Program.cfgjson.Emoji.Banned} You have been permanently banned from **{guild.Name}**!\nReason: **{reason}**");
}
}
else
{
await targetMember.SendMessageAsync($"{Program.cfgjson.Emoji.Banned} You have been banned from **{guild.Name}** for {TimeHelpers.TimeToPrettyFormat(banDuration, false)}!\nReason: **{reason}**\nBan expires: <t:{TimeHelpers.ToUnixTimestamp(expireTime)}:R>");
output.dmMessage = await targetMember.SendMessageAsync($"{Program.cfgjson.Emoji.Banned} You have been banned from **{guild.Name}** for {TimeHelpers.TimeToPrettyFormat(banDuration, false)}!\nReason: **{reason}**\nBan expires: <t:{TimeHelpers.ToUnixTimestamp(expireTime)}:R>");
}
}
catch
{
// A DM failing to send isn't important.
}

MemberPunishment newBan = new()
{
MemberId = targetUserId,
ModId = moderatorId,
ServerId = guild.Id,
ExpireTime = expireTime,
ActionTime = actionTime,
Reason = reason
};

if (output.chatMessage is not null)
newBan.ContextMessageReference = new()
{
MessageId = output.chatMessage.Id,
ChannelId = output.chatMessage.ChannelId
};

if (output.dmMessage is not null)
newBan!.DmMessageReference = new()
{
MessageId = output.dmMessage.Id,
ChannelId = output.dmMessage.ChannelId
};

await Program.db.HashSetAsync("bans", targetUserId, JsonConvert.SerializeObject(newBan));

// If ban is for a compromised account, add to list so the context message can be more-easily deleted later
if (compromisedAccount)
Program.db.HashSet("compromisedAccountBans", targetUserId, JsonConvert.SerializeObject(newBan));

try
{
Expand Down
2 changes: 1 addition & 1 deletion Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -248,7 +248,7 @@ static async Task Main(string[] _)
[
Tasks.PunishmentTasks.CheckMutesAsync(),
Tasks.PunishmentTasks.CheckBansAsync(),
Tasks.PunishmentTasks.CheckAutomaticWarningsAsync(),
Tasks.PunishmentTasks.CleanUpPunishmentMessagesAsync(),
Tasks.ReminderTasks.CheckRemindersAsync(),
Tasks.RaidmodeTasks.CheckRaidmodeAsync(cfgjson.ServerID),
Tasks.LockdownTasks.CheckUnlocksAsync(),
Expand Down
3 changes: 3 additions & 0 deletions Structs.cs
Original file line number Diff line number Diff line change
Expand Up @@ -286,6 +286,9 @@ public class ConfigJson

[JsonProperty("autoWarnMsgAutoDeleteDays")]
public int AutoWarnMsgAutoDeleteDays { get; private set; }

[JsonProperty("compromisedAccountBanMsgAutoDeleteDays")]
public int CompromisedAccountBanMsgAutoDeleteDays { get; private set; }

[JsonProperty("logLevel")]
public Level LogLevel { get; private set; } = Level.Information;
Expand Down
68 changes: 53 additions & 15 deletions Tasks/PunishmentTasks.cs
Original file line number Diff line number Diff line change
Expand Up @@ -58,26 +58,30 @@ public static async Task<bool> CheckMutesAsync()
}
}

public static async Task<bool> CheckAutomaticWarningsAsync()
// Cleans up public messages for automatic warnings & bans for compromised accounts
public static async Task<bool> CleanUpPunishmentMessagesAsync()
{
if (Program.cfgjson.AutoWarnMsgAutoDeleteDays == 0)
if (Program.cfgjson.AutoWarnMsgAutoDeleteDays == 0 && Program.cfgjson.CompromisedAccountBanMsgAutoDeleteDays == 0)
return false;

Dictionary<string, UserWarning> warnList = Program.db.HashGetAll("automaticWarnings").ToDictionary(
x => x.Name.ToString(),
x => JsonConvert.DeserializeObject<UserWarning>(x.Value)
);

if (warnList is null | warnList.Keys.Count == 0)
return false;
else

// The success value will be changed later if any of the message deletes are successful.
bool success = false;

if (Program.cfgjson.AutoWarnMsgAutoDeleteDays > 0)
{
// The success value will be changed later if any of the message deletes are successful.
bool success = false;
Dictionary<string, UserWarning> warnList = Program.db.HashGetAll("automaticWarnings").ToDictionary(
x => x.Name.ToString(),
x => JsonConvert.DeserializeObject<UserWarning>(x.Value)
);

foreach (KeyValuePair<string, UserWarning> entry in warnList)
{
UserWarning warn = entry.Value;
#if DEBUG
if (DateTime.Now > warn.WarnTimestamp.AddSeconds(Program.cfgjson.AutoWarnMsgAutoDeleteDays))
#else
if (DateTime.Now > warn.WarnTimestamp.AddDays(Program.cfgjson.AutoWarnMsgAutoDeleteDays))
#endif
{
try
{
Expand All @@ -94,9 +98,43 @@ public static async Task<bool> CheckAutomaticWarningsAsync()
}
}
}
Program.discord.Logger.LogDebug(Program.CliptokEventID, "Checked automatic warnings at {time} with result: {result}", DateTime.Now, success);
return success;
}

if (Program.cfgjson.CompromisedAccountBanMsgAutoDeleteDays > 0)
{
Dictionary<string, MemberPunishment> banList = Program.db.HashGetAll("compromisedAccountBans").ToDictionary(
x => x.Name.ToString(),
x => JsonConvert.DeserializeObject<MemberPunishment>(x.Value)
);

foreach (KeyValuePair<string, MemberPunishment> entry in banList)
{
MemberPunishment ban = entry.Value;
#if DEBUG
if (DateTime.Now > ban.ActionTime.Value.AddSeconds(Program.cfgjson.CompromisedAccountBanMsgAutoDeleteDays))
#else
if (DateTime.Now > ban.ActionTime.Value.AddDays(Program.cfgjson.CompromisedAccountBanMsgAutoDeleteDays))
#endif
{
try
{
var contextMessage = await DiscordHelpers.GetMessageFromReferenceAsync(ban.ContextMessageReference);
await contextMessage.DeleteAsync();
Program.db.HashDelete("compromisedAccountBans", ban.MemberId);
success = true;
}
catch (NullReferenceException)
{
// it's fine. trust me. we'll live.
Program.db.HashDelete("compromisedAccountBans", ban.MemberId);
continue;
}
}
}
}

Program.discord.Logger.LogDebug(Program.CliptokEventID, "Checked for auto-warn and compromised account ban messages at {time} with result: {result}", DateTime.Now, success);
return success;
}
}

Expand Down
1 change: 1 addition & 0 deletions config.json
Original file line number Diff line number Diff line change
Expand Up @@ -322,6 +322,7 @@
"tqsMutedRole": 752821045408563230,
"tqsMuteDurationHours": 2,
"autoWarnMsgAutoDeleteDays": 3,
"compromisedAccountBanMsgAutoDeleteDays": 3,
"logLevel": "Debug",
"lokiURL": "http://100.79.19.82:3100",
"lokiServiceName": "cliptok",
Expand Down

0 comments on commit 0b56658

Please sign in to comment.