-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathModeration.Audit.cs
325 lines (303 loc) · 14.7 KB
/
Moderation.Audit.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using CompatApiClient.Utils;
using CompatBot.Commands.Attributes;
using CompatBot.EventHandlers;
using CompatBot.Utils;
using DSharpPlus;
using DSharpPlus.CommandsNext;
using DSharpPlus.CommandsNext.Attributes;
using DSharpPlus.Entities;
namespace CompatBot.Commands;
internal sealed partial class Moderation
{
[Group("audit"), RequiresBotModRole]
[Description("Commands to audit server things")]
public sealed class Audit: BaseCommandModuleCustom
{
public static readonly SemaphoreSlim CheckLock = new(1, 1);
[Command("spoofing"), Aliases("impersonation"), RequireDirectMessage]
[Description("Checks every user on the server for name spoofing")]
public Task Spoofing(CommandContext ctx)
{
SpoofingCheck(ctx);
return Task.CompletedTask;
}
[Command("members"), Aliases("users"), RequireDirectMessage]
[Description("Dumps server member information, including usernames, nicknames, and roles")]
public async Task Members(CommandContext ctx)
{
if (!await CheckLock.WaitAsync(0).ConfigureAwait(false))
{
await ctx.Channel.SendMessageAsync("Another check is already in progress").ConfigureAwait(false);
return;
}
try
{
await ctx.ReactWithAsync(Config.Reactions.PleaseWait).ConfigureAwait(false);
var members = GetMembers(ctx.Client);
await using var compressedResult = Config.MemoryStreamManager.GetStream();
await using var memoryStream = Config.MemoryStreamManager.GetStream();
await using var writer = new StreamWriter(memoryStream, new UTF8Encoding(false), 4096, true);
foreach (var member in members)
await writer.WriteLineAsync($"{member.Username}\t{member.Nickname}\t{member.JoinedAt:O}\t{string.Join(',', member.Roles.Select(r => r.Name))}").ConfigureAwait(false);
await writer.FlushAsync().ConfigureAwait(false);
memoryStream.Seek(0, SeekOrigin.Begin);
if (memoryStream.Length <= ctx.GetAttachmentSizeLimit())
{
await ctx.Channel.SendMessageAsync(new DiscordMessageBuilder().AddFile("names.txt", memoryStream)).ConfigureAwait(false);
return;
}
await using var gzip = new GZipStream(compressedResult, CompressionLevel.Optimal, true);
await memoryStream.CopyToAsync(gzip).ConfigureAwait(false);
await gzip.FlushAsync().ConfigureAwait(false);
compressedResult.Seek(0, SeekOrigin.Begin);
if (compressedResult.Length <= ctx.GetAttachmentSizeLimit())
await ctx.Channel.SendMessageAsync(new DiscordMessageBuilder().AddFile("names.txt.gz", compressedResult)).ConfigureAwait(false);
else
await ctx.Channel.SendMessageAsync($"Dump is too large: {compressedResult.Length} bytes").ConfigureAwait(false);
}
catch (Exception e)
{
Config.Log.Warn(e, "Failed to dump guild members");
await ctx.ReactWithAsync(Config.Reactions.Failure, "Failed to dump guild members").ConfigureAwait(false);
}
finally
{
CheckLock.Release();
await ctx.RemoveReactionAsync(Config.Reactions.PleaseWait).ConfigureAwait(false);
}
}
[Command("raid")]
[Description("Kick known raiders")]
public async Task Raid(CommandContext ctx)
{
if (!await CheckLock.WaitAsync(0).ConfigureAwait(false))
{
await ctx.Channel.SendMessageAsync("Another check is already in progress").ConfigureAwait(false);
return;
}
try
{
await ctx.ReactWithAsync(Config.Reactions.PleaseWait).ConfigureAwait(false);
var result = new StringBuilder("List of users:").AppendLine();
var headerLength = result.Length;
var members = GetMembers(ctx.Client);
foreach (var member in members)
try
{
var displayName = member.DisplayName;
if (!UsernameRaidMonitor.NeedsKick(displayName))
continue;
try
{
await member.RemoveAsync("Anti Raid").ConfigureAwait(false);
result.AppendLine($"{member.Username} have been automatically kicked");
}
catch (Exception e)
{
Config.Log.Warn(e, $"Failed to kick member {member.GetUsernameWithNickname()}");
}
}
catch (Exception e)
{
Config.Log.Warn(e, $"Failed to audit username for {member.Id}");
}
if (result.Length == headerLength)
result.AppendLine("No naughty users 🎉");
await ctx.SendAutosplitMessageAsync(result, blockStart: "", blockEnd: "").ConfigureAwait(false);
}
catch (Exception e)
{
var msg = "Failed to check display names for raids for all guild members";
Config.Log.Warn(e, msg);
await ctx.ReactWithAsync(Config.Reactions.Failure, msg).ConfigureAwait(false);
}
finally
{
CheckLock.Release();
await ctx.RemoveReactionAsync(Config.Reactions.PleaseWait).ConfigureAwait(false);
}
}
[Command("zalgo"), Aliases("diacritics")]
[Description("Checks every member's display name for discord and rule #7 requirements")]
public async Task Zalgo(CommandContext ctx)
{
if (!await CheckLock.WaitAsync(0).ConfigureAwait(false))
{
await ctx.Channel.SendMessageAsync("Another check is already in progress").ConfigureAwait(false);
return;
}
try
{
await ctx.ReactWithAsync(Config.Reactions.PleaseWait).ConfigureAwait(false);
var result = new StringBuilder("List of users who do not meet Rule #7 requirements:").AppendLine();
var headerLength = result.Length;
var members = GetMembers(ctx.Client);
foreach (var member in members)
try
{
var displayName = member.DisplayName;
if (!UsernameZalgoMonitor.NeedsRename(displayName))
continue;
var nickname = UsernameZalgoMonitor.StripZalgo(displayName, member.Username, member.Id).Sanitize();
try
{
await member.ModifyAsync(m => m.Nickname = nickname).ConfigureAwait(false);
result.AppendLine($"{member.Mention} have been automatically renamed from {displayName} to {nickname} according Rule #7");
}
catch (Exception e)
{
Config.Log.Warn(e, $"Failed to rename member {member.GetUsernameWithNickname()}");
result.AppendLine($"{member.Mention} please change your nickname according to Rule #7 (suggestion: {nickname})");
}
}
catch (Exception e)
{
Config.Log.Warn(e, $"Failed to audit username for {member.Id}");
}
if (result.Length == headerLength)
result.AppendLine("No naughty users 🎉");
await ctx.SendAutosplitMessageAsync(result, blockStart: "", blockEnd: "").ConfigureAwait(false);
}
catch (Exception e)
{
var msg = "Failed to check display names for zalgo for all guild members";
Config.Log.Warn(e, msg);
await ctx.ReactWithAsync(Config.Reactions.Failure, msg).ConfigureAwait(false);
}
finally
{
CheckLock.Release();
await ctx.RemoveReactionAsync(Config.Reactions.PleaseWait).ConfigureAwait(false);
}
}
#if DEBUG
[Command("locales"), Aliases("locale", "languages", "language", "lang", "loc")]
public async Task UserLocales(CommandContext ctx)
{
#pragma warning disable VSTHRD103
if (!CheckLock.Wait(0))
#pragma warning restore VSTHRD103
{
await ctx.Channel.SendMessageAsync("Another check is already in progress").ConfigureAwait(false);
return;
}
try
{
await ctx.ReactWithAsync(Config.Reactions.PleaseWait).ConfigureAwait(false);
var members = GetMembers(ctx.Client);
var stats = new Dictionary<string, int>();
foreach (var m in members)
{
var loc = m.Locale ?? "Unknown";
if (stats.ContainsKey(loc))
stats[loc]++;
else
stats[loc] = 1;
}
var table = new AsciiTable(
new AsciiColumn("Locale"),
new AsciiColumn("Count", alignToRight: true),
new AsciiColumn("%", alignToRight: true)
);
var total = stats.Values.Sum();
foreach (var lang in stats.OrderByDescending(l => l.Value).ThenBy(l => l.Key))
table.Add(lang.Key, lang.Value.ToString(), $"{100.0 * lang.Value / total:0.00}%");
await ctx.SendAutosplitMessageAsync(new StringBuilder().AppendLine("Member locale stats:").Append(table)).ConfigureAwait(false);
}
catch (Exception e)
{
Config.Log.Warn(e, "Failed to get locale stats");
await ctx.ReactWithAsync(Config.Reactions.Failure, "Failed to get locale stats").ConfigureAwait(false);
}
finally
{
CheckLock.Release();
await ctx.RemoveReactionAsync(Config.Reactions.PleaseWait).ConfigureAwait(false);
}
}
#endif
private static List<DiscordMember> GetMembers(DiscordClient client)
{
//owner -> white name
//newbs -> veterans
return client.Guilds.Select(g => g.Value.GetAllMembersAsync().ConfigureAwait(false))
.SelectMany(l => l.GetAwaiter().GetResult())
.OrderByDescending(m => m.Hierarchy)
.ThenByDescending(m => m.JoinedAt)
.ToList();
}
private static async void SpoofingCheck(CommandContext ctx)
{
if (!CheckLock.Wait(0))
{
await ctx.Channel.SendMessageAsync("Another check is already in progress").ConfigureAwait(false);
return;
}
try
{
await ctx.ReactWithAsync(Config.Reactions.PleaseWait).ConfigureAwait(false);
var members = GetMembers(ctx.Client);
if (members.Count < 2)
return;
var result = new StringBuilder("List of potential impersonators → victims:").AppendLine();
var headerLength = result.Length;
var checkedMembers = new List<DiscordMember>(members.Count) {members[0]};
for (var i = 1; i < members.Count; i++)
{
var member = members[i];
var victims = UsernameSpoofMonitor.GetPotentialVictims(ctx.Client, member, true, true, checkedMembers);
if (victims.Any())
result.Append(member.GetMentionWithNickname()).Append(" → ").AppendLine(string.Join(", ", victims.Select(m => m.GetMentionWithNickname())));
checkedMembers.Add(member);
}
await using var compressedStream = Config.MemoryStreamManager.GetStream();
await using var uncompressedStream = Config.MemoryStreamManager.GetStream();
await using (var writer = new StreamWriter(uncompressedStream, new UTF8Encoding(false), 4096, true))
{
await writer.WriteAsync(result.ToString()).ConfigureAwait(false);
await writer.FlushAsync().ConfigureAwait(false);
}
uncompressedStream.Seek(0, SeekOrigin.Begin);
if (result.Length <= headerLength)
{
await ctx.Channel.SendMessageAsync("No potential name spoofing was detected").ConfigureAwait(false);
return;
}
if (uncompressedStream.Length <= ctx.GetAttachmentSizeLimit())
{
await ctx.Channel.SendMessageAsync(new DiscordMessageBuilder().AddFile("spoofing_check_results.txt", uncompressedStream)).ConfigureAwait(false);
return;
}
await using (var gzip = new GZipStream(compressedStream, CompressionLevel.Optimal, true))
{
await uncompressedStream.CopyToAsync(gzip).ConfigureAwait(false);
gzip.Flush();
}
compressedStream.Seek(0, SeekOrigin.Begin);
if (compressedStream.Length <= ctx.GetAttachmentSizeLimit())
await ctx.Channel.SendMessageAsync(new DiscordMessageBuilder().AddFile("spoofing_check_results.txt.gz", compressedStream)).ConfigureAwait(false);
else
await ctx.Channel.SendMessageAsync($"Dump is too large: {compressedStream.Length} bytes").ConfigureAwait(false);
}
catch (Exception e)
{
Config.Log.Error(e);
//should be extra careful, as async void will run on a thread pull, and will terminate the whole application with an uncaught exception
try { await ctx.ReactWithAsync(Config.Reactions.Failure, "(X_X)").ConfigureAwait(false); } catch { }
}
finally
{
CheckLock.Release();
await ctx.RemoveReactionAsync(Config.Reactions.PleaseWait).ConfigureAwait(false);
}
}
}
}