Skip to content

Commit 0b56658

Browse files
Automatically delete ban messages for compromised account bans (#251)
* 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 <[email protected]>
1 parent 8139986 commit 0b56658

File tree

8 files changed

+103
-47
lines changed

8 files changed

+103
-47
lines changed

Commands/Bans.cs

-10
Original file line numberDiff line numberDiff line change
@@ -123,11 +123,6 @@ public async Task BanCmd(CommandContext ctx,
123123
return;
124124
}
125125
}
126-
reason = reason.Replace("`", "\\`").Replace("*", "\\*");
127-
if (banDuration == default)
128-
await ctx.Channel.SendMessageAsync($"{Program.cfgjson.Emoji.Banned} {targetMember.Mention} has been banned: **{reason}**");
129-
else
130-
await ctx.Channel.SendMessageAsync($"{Program.cfgjson.Emoji.Banned} {targetMember.Mention} has been banned for **{TimeHelpers.TimeToPrettyFormat(banDuration, false)}**: **{reason}**");
131126
}
132127

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

217207
[Command("unban")]

Commands/Debug.cs

+2-2
Original file line numberDiff line numberDiff line change
@@ -131,14 +131,14 @@ public async Task Refresh(CommandContext ctx)
131131
var msg = await ctx.RespondAsync("Checking for pending scheduled tasks...");
132132
bool bans = await Tasks.PunishmentTasks.CheckBansAsync();
133133
bool mutes = await Tasks.PunishmentTasks.CheckMutesAsync();
134-
bool warns = await Tasks.PunishmentTasks.CheckAutomaticWarningsAsync();
134+
bool punishmentMessages = await Tasks.PunishmentTasks.CleanUpPunishmentMessagesAsync();
135135
bool reminders = await Tasks.ReminderTasks.CheckRemindersAsync();
136136
bool raidmode = await Tasks.RaidmodeTasks.CheckRaidmodeAsync(ctx.Guild.Id);
137137
bool unlocks = await Tasks.LockdownTasks.CheckUnlocksAsync();
138138
bool channelUpdateEvents = await Tasks.EventTasks.HandlePendingChannelUpdateEventsAsync();
139139
bool channelDeleteEvents = await Tasks.EventTasks.HandlePendingChannelDeleteEventsAsync();
140140

141-
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}`");
141+
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}`");
142142
}
143143

144144
[Command("sh")]

Commands/InteractionCommands/BanInteractions.cs

-5
Original file line numberDiff line numberDiff line change
@@ -103,11 +103,6 @@ public async Task BanSlashCommand(InteractionContext ctx,
103103
return;
104104
}
105105
}
106-
reason = reason.Replace("`", "\\`").Replace("*", "\\*");
107-
if (banDuration == default)
108-
await ctx.Channel.SendMessageAsync($"{Program.cfgjson.Emoji.Banned} {user.Mention} has been banned: **{reason}**");
109-
else
110-
await ctx.Channel.SendMessageAsync($"{Program.cfgjson.Emoji.Banned} {user.Mention} has been banned for **{TimeHelpers.TimeToPrettyFormat(banDuration, false)}**: **{reason}**");
111106

112107
webhookOut.Content = $"{Program.cfgjson.Emoji.Success} User was successfully bonked.";
113108
await ctx.EditResponseAsync(webhookOut);

Helpers/BanHelpers.cs

+43-14
Original file line numberDiff line numberDiff line change
@@ -18,17 +18,16 @@ public static async Task<bool> BanFromServerAsync(ulong targetUserId, string rea
1818
expireTime = null;
1919
}
2020

21-
MemberPunishment newBan = new()
21+
(DiscordMessage? dmMessage, DiscordMessage? chatMessage) output = new();
22+
23+
reason = reason.Replace("`", "\\`").Replace("*", "\\*");
24+
if (channel is not null)
2225
{
23-
MemberId = targetUserId,
24-
ModId = moderatorId,
25-
ServerId = guild.Id,
26-
ExpireTime = expireTime,
27-
ActionTime = actionTime,
28-
Reason = reason
29-
};
30-
31-
await Program.db.HashSetAsync("bans", targetUserId, JsonConvert.SerializeObject(newBan));
26+
if (banDuration == default)
27+
output.chatMessage = await channel.SendMessageAsync($"{Program.cfgjson.Emoji.Banned} <@{targetUserId}> has been banned: **{reason}**");
28+
else
29+
output.chatMessage = await channel.SendMessageAsync($"{Program.cfgjson.Emoji.Banned} <@{targetUserId}> has been banned for **{TimeHelpers.TimeToPrettyFormat(banDuration, false)}**: **{reason}**");
30+
}
3231

3332
try
3433
{
@@ -38,24 +37,54 @@ public static async Task<bool> BanFromServerAsync(ulong targetUserId, string rea
3837
if (appealable)
3938
{
4039
if (compromisedAccount)
41-
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.");
40+
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.");
4241
else
43-
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}>");
42+
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}>");
4443
}
4544
else
4645
{
47-
await targetMember.SendMessageAsync($"{Program.cfgjson.Emoji.Banned} You have been permanently banned from **{guild.Name}**!\nReason: **{reason}**");
46+
output.dmMessage = await targetMember.SendMessageAsync($"{Program.cfgjson.Emoji.Banned} You have been permanently banned from **{guild.Name}**!\nReason: **{reason}**");
4847
}
4948
}
5049
else
5150
{
52-
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>");
51+
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>");
5352
}
5453
}
5554
catch
5655
{
5756
// A DM failing to send isn't important.
5857
}
58+
59+
MemberPunishment newBan = new()
60+
{
61+
MemberId = targetUserId,
62+
ModId = moderatorId,
63+
ServerId = guild.Id,
64+
ExpireTime = expireTime,
65+
ActionTime = actionTime,
66+
Reason = reason
67+
};
68+
69+
if (output.chatMessage is not null)
70+
newBan.ContextMessageReference = new()
71+
{
72+
MessageId = output.chatMessage.Id,
73+
ChannelId = output.chatMessage.ChannelId
74+
};
75+
76+
if (output.dmMessage is not null)
77+
newBan!.DmMessageReference = new()
78+
{
79+
MessageId = output.dmMessage.Id,
80+
ChannelId = output.dmMessage.ChannelId
81+
};
82+
83+
await Program.db.HashSetAsync("bans", targetUserId, JsonConvert.SerializeObject(newBan));
84+
85+
// If ban is for a compromised account, add to list so the context message can be more-easily deleted later
86+
if (compromisedAccount)
87+
Program.db.HashSet("compromisedAccountBans", targetUserId, JsonConvert.SerializeObject(newBan));
5988

6089
try
6190
{

Program.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -248,7 +248,7 @@ static async Task Main(string[] _)
248248
[
249249
Tasks.PunishmentTasks.CheckMutesAsync(),
250250
Tasks.PunishmentTasks.CheckBansAsync(),
251-
Tasks.PunishmentTasks.CheckAutomaticWarningsAsync(),
251+
Tasks.PunishmentTasks.CleanUpPunishmentMessagesAsync(),
252252
Tasks.ReminderTasks.CheckRemindersAsync(),
253253
Tasks.RaidmodeTasks.CheckRaidmodeAsync(cfgjson.ServerID),
254254
Tasks.LockdownTasks.CheckUnlocksAsync(),

Structs.cs

+3
Original file line numberDiff line numberDiff line change
@@ -286,6 +286,9 @@ public class ConfigJson
286286

287287
[JsonProperty("autoWarnMsgAutoDeleteDays")]
288288
public int AutoWarnMsgAutoDeleteDays { get; private set; }
289+
290+
[JsonProperty("compromisedAccountBanMsgAutoDeleteDays")]
291+
public int CompromisedAccountBanMsgAutoDeleteDays { get; private set; }
289292

290293
[JsonProperty("logLevel")]
291294
public Level LogLevel { get; private set; } = Level.Information;

Tasks/PunishmentTasks.cs

+53-15
Original file line numberDiff line numberDiff line change
@@ -58,26 +58,30 @@ public static async Task<bool> CheckMutesAsync()
5858
}
5959
}
6060

61-
public static async Task<bool> CheckAutomaticWarningsAsync()
61+
// Cleans up public messages for automatic warnings & bans for compromised accounts
62+
public static async Task<bool> CleanUpPunishmentMessagesAsync()
6263
{
63-
if (Program.cfgjson.AutoWarnMsgAutoDeleteDays == 0)
64+
if (Program.cfgjson.AutoWarnMsgAutoDeleteDays == 0 && Program.cfgjson.CompromisedAccountBanMsgAutoDeleteDays == 0)
6465
return false;
65-
66-
Dictionary<string, UserWarning> warnList = Program.db.HashGetAll("automaticWarnings").ToDictionary(
67-
x => x.Name.ToString(),
68-
x => JsonConvert.DeserializeObject<UserWarning>(x.Value)
69-
);
70-
71-
if (warnList is null | warnList.Keys.Count == 0)
72-
return false;
73-
else
66+
67+
// The success value will be changed later if any of the message deletes are successful.
68+
bool success = false;
69+
70+
if (Program.cfgjson.AutoWarnMsgAutoDeleteDays > 0)
7471
{
75-
// The success value will be changed later if any of the message deletes are successful.
76-
bool success = false;
72+
Dictionary<string, UserWarning> warnList = Program.db.HashGetAll("automaticWarnings").ToDictionary(
73+
x => x.Name.ToString(),
74+
x => JsonConvert.DeserializeObject<UserWarning>(x.Value)
75+
);
76+
7777
foreach (KeyValuePair<string, UserWarning> entry in warnList)
7878
{
7979
UserWarning warn = entry.Value;
80+
#if DEBUG
81+
if (DateTime.Now > warn.WarnTimestamp.AddSeconds(Program.cfgjson.AutoWarnMsgAutoDeleteDays))
82+
#else
8083
if (DateTime.Now > warn.WarnTimestamp.AddDays(Program.cfgjson.AutoWarnMsgAutoDeleteDays))
84+
#endif
8185
{
8286
try
8387
{
@@ -94,9 +98,43 @@ public static async Task<bool> CheckAutomaticWarningsAsync()
9498
}
9599
}
96100
}
97-
Program.discord.Logger.LogDebug(Program.CliptokEventID, "Checked automatic warnings at {time} with result: {result}", DateTime.Now, success);
98-
return success;
99101
}
102+
103+
if (Program.cfgjson.CompromisedAccountBanMsgAutoDeleteDays > 0)
104+
{
105+
Dictionary<string, MemberPunishment> banList = Program.db.HashGetAll("compromisedAccountBans").ToDictionary(
106+
x => x.Name.ToString(),
107+
x => JsonConvert.DeserializeObject<MemberPunishment>(x.Value)
108+
);
109+
110+
foreach (KeyValuePair<string, MemberPunishment> entry in banList)
111+
{
112+
MemberPunishment ban = entry.Value;
113+
#if DEBUG
114+
if (DateTime.Now > ban.ActionTime.Value.AddSeconds(Program.cfgjson.CompromisedAccountBanMsgAutoDeleteDays))
115+
#else
116+
if (DateTime.Now > ban.ActionTime.Value.AddDays(Program.cfgjson.CompromisedAccountBanMsgAutoDeleteDays))
117+
#endif
118+
{
119+
try
120+
{
121+
var contextMessage = await DiscordHelpers.GetMessageFromReferenceAsync(ban.ContextMessageReference);
122+
await contextMessage.DeleteAsync();
123+
Program.db.HashDelete("compromisedAccountBans", ban.MemberId);
124+
success = true;
125+
}
126+
catch (NullReferenceException)
127+
{
128+
// it's fine. trust me. we'll live.
129+
Program.db.HashDelete("compromisedAccountBans", ban.MemberId);
130+
continue;
131+
}
132+
}
133+
}
134+
}
135+
136+
Program.discord.Logger.LogDebug(Program.CliptokEventID, "Checked for auto-warn and compromised account ban messages at {time} with result: {result}", DateTime.Now, success);
137+
return success;
100138
}
101139
}
102140

config.json

+1
Original file line numberDiff line numberDiff line change
@@ -322,6 +322,7 @@
322322
"tqsMutedRole": 752821045408563230,
323323
"tqsMuteDurationHours": 2,
324324
"autoWarnMsgAutoDeleteDays": 3,
325+
"compromisedAccountBanMsgAutoDeleteDays": 3,
325326
"logLevel": "Debug",
326327
"lokiURL": "http://100.79.19.82:3100",
327328
"lokiServiceName": "cliptok",

0 commit comments

Comments
 (0)