forked from Erisa/Cliptok
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Program.cs
556 lines (465 loc) · 23.7 KB
/
Program.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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
using Cliptok.Modules;
using DSharpPlus;
using DSharpPlus.CommandsNext;
using DSharpPlus.CommandsNext.Exceptions;
using DSharpPlus.Entities;
using DSharpPlus.EventArgs;
using DSharpPlus.SlashCommands;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace Cliptok
{
class Program : BaseCommandModule
{
public static DiscordClient discord;
static CommandsNextExtension commands;
public static Random rnd = new();
public static ConfigJson cfgjson;
public static ConnectionMultiplexer redis;
public static IDatabase db;
internal static EventId CliptokEventID { get; } = new EventId(1000, "Cliptok");
public static string[] avatars;
public static string[] badUsernames;
public static List<ulong> autoBannedUsersCache = new();
public static DiscordChannel logChannel;
public static DiscordChannel userLogChannel;
public static DiscordChannel badMsgLog;
public static Random rand = new Random();
public static async Task<bool> CheckAndDehoistMemberAsync(DiscordMember targetMember)
{
if (
!(
targetMember.DisplayName[0] != ModCmds.dehoistCharacter
&& (
cfgjson.AutoDehoistCharacters.Contains(targetMember.DisplayName[0])
|| (targetMember.Nickname != null && targetMember.Nickname[0] != targetMember.Username[0] && cfgjson.SecondaryAutoDehoistCharacters.Contains(targetMember.Nickname[0]))
)
))
{
return false;
}
try
{
await targetMember.ModifyAsync(a =>
{
a.Nickname = ModCmds.DehoistName(targetMember.DisplayName);
});
return true;
}
catch
{
return false;
}
}
static void Main(string[] args)
{
MainAsync(args).ConfigureAwait(false).GetAwaiter().GetResult();
}
static async Task MainAsync(string[] _)
{
string token;
var json = "";
string configFile = "config.json";
#if DEBUG
configFile = "config.dev.json";
#endif
using (var fs = File.OpenRead(configFile))
using (var sr = new StreamReader(fs, new UTF8Encoding(false)))
json = await sr.ReadToEndAsync();
cfgjson = JsonConvert.DeserializeObject<ConfigJson>(json);
var keys = cfgjson.WordListList.Keys;
foreach (string key in keys)
{
var listOutput = File.ReadAllLines($"Lists/{key}");
cfgjson.WordListList[key].Words = listOutput;
}
if (File.Exists("Lists/usernames.txt"))
badUsernames = File.ReadAllLines("Lists/usernames.txt");
else
badUsernames = new string[0];
avatars = File.ReadAllLines("Lists/avatars.txt");
if (Environment.GetEnvironmentVariable("CLIPTOK_TOKEN") != null)
token = Environment.GetEnvironmentVariable("CLIPTOK_TOKEN");
else
token = cfgjson.Core.Token;
if (Environment.GetEnvironmentVariable("REDIS_URL") != null)
redis = ConnectionMultiplexer.Connect(Environment.GetEnvironmentVariable("REDIS_URL"));
else
{
string redisHost;
if (Environment.GetEnvironmentVariable("REDIS_DOCKER_OVERRIDE") != null)
redisHost = "redis";
else
redisHost = cfgjson.Redis.Host;
redis = ConnectionMultiplexer.Connect($"{redisHost}:{cfgjson.Redis.Port}");
}
db = redis.GetDatabase();
// Migration away from a broken attempt at a key in the past.
db.KeyDelete("messages");
discord = new DiscordClient(new DiscordConfiguration
{
Token = token,
TokenType = TokenType.Bot,
MinimumLogLevel = LogLevel.Information,
Intents = DiscordIntents.All
});
var slash = discord.UseSlashCommands();
slash.SlashCommandErrored += async (s, e) =>
{
if (e.Exception is SlashExecutionChecksFailedException slex)
{
foreach (var check in slex.FailedChecks)
if (check is SlashRequireHomeserverPermAttribute att)
{
var level = Warnings.GetPermLevel(e.Context.Member);
var levelText = level.ToString();
if (level == ServerPermLevel.nothing && rand.Next(1, 100) == 69)
levelText = $"naught but a thing, my dear human. Congratulations, you win {Program.rand.Next(1, 10)} bonus points.";
await e.Context.CreateResponseAsync(
InteractionResponseType.ChannelMessageWithSource,
new DiscordInteractionResponseBuilder().WithContent(
$"{cfgjson.Emoji.NoPermissions} Invalid permission level to use command **{e.Context.CommandName}**!\n" +
$"Required: `{att.TargetLvl}`\n" +
$"You have: `{Warnings.GetPermLevel(e.Context.Member)}`")
.AsEphemeral(true)
);
}
}
};
Task ClientError(DiscordClient client, ClientErrorEventArgs e)
{
client.Logger.LogError(CliptokEventID, e.Exception, "Client threw an exception");
return Task.CompletedTask;
}
slash.RegisterCommands<SlashCommands>(cfgjson.ServerID);
async Task OnReaction(DiscordClient client, MessageReactionAddEventArgs e)
{
Task.Run(async () =>
{
if (e.Emoji.Id != cfgjson.HeartosoftId || e.Channel.IsPrivate || e.Guild.Id != cfgjson.ServerID)
return;
bool handled = false;
DiscordMessage targetMessage = await e.Channel.GetMessageAsync(e.Message.Id);
DiscordEmoji noHeartosoft = await e.Guild.GetEmojiAsync(cfgjson.NoHeartosoftId);
if (targetMessage.Author.Id == e.User.Id)
{
await targetMessage.DeleteReactionAsync(e.Emoji, e.User);
handled = true;
}
foreach (string word in cfgjson.RestrictedHeartosoftPhrases)
{
if (targetMessage.Content.ToLower().Contains(word))
{
if (!handled)
await targetMessage.DeleteReactionAsync(e.Emoji, e.User);
await targetMessage.CreateReactionAsync(noHeartosoft);
return;
}
}
});
}
#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
async Task OnReady(DiscordClient client, ReadyEventArgs e)
{
Task.Run(async () =>
{
Console.WriteLine($"Logged in as {client.CurrentUser.Username}#{client.CurrentUser.Discriminator}");
logChannel = await discord.GetChannelAsync(cfgjson.LogChannel);
userLogChannel = await discord.GetChannelAsync(cfgjson.UserLogChannel);
badMsgLog = await discord.GetChannelAsync(cfgjson.InvestigationsChannelId);
Mutes.CheckMutesAsync();
ModCmds.CheckBansAsync();
ModCmds.CheckRemindersAsync();
string commitHash = "";
string commitMessage = "";
string commitTime = "";
if (File.Exists("CommitHash.txt"))
{
using var sr = new StreamReader("CommitHash.txt");
commitHash = sr.ReadToEnd();
}
if (Environment.GetEnvironmentVariable("RAILWAY_GIT_COMMIT_SHA") != null)
{
commitHash = Environment.GetEnvironmentVariable("RAILWAY_GIT_COMMIT_SHA");
commitHash = commitHash.Substring(0, Math.Min(commitHash.Length, 7));
}
if (string.IsNullOrWhiteSpace(commitHash))
{
commitHash = "dev";
}
if (File.Exists("CommitMessage.txt"))
{
using var sr = new StreamReader("CommitMessage.txt");
commitMessage = sr.ReadToEnd();
}
if (Environment.GetEnvironmentVariable("RAILWAY_GIT_COMMIT_MESSAGE") != null)
{
commitMessage = Environment.GetEnvironmentVariable("RAILWAY_GIT_COMMIT_MESSAGE");
}
if (string.IsNullOrWhiteSpace(commitMessage))
{
commitMessage = "N/A (Expected if bot is built for Windows)";
}
if (File.Exists("CommitTime.txt"))
{
using var sr = new StreamReader("CommitTime.txt");
commitTime = sr.ReadToEnd();
}
if (string.IsNullOrWhiteSpace(commitTime))
{
commitTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss zzz");
}
var cliptokChannel = await client.GetChannelAsync(cfgjson.HomeChannel);
cliptokChannel.SendMessageAsync($"{cfgjson.Emoji.Connected} {discord.CurrentUser.Username} connected successfully!\n\n" +
$"**Version**: `{commitHash}`\n" +
$"**Version timestamp**: `{commitTime}`\n**Framework**: `{RuntimeInformation.FrameworkDescription}`\n**Platform**: `{RuntimeInformation.OSDescription}`\n\n" +
$"Most recent commit message:\n" +
$"```\n" +
$"{commitMessage}\n" +
$"```");
});
}
async Task UsernameCheckAsync(DiscordMember member)
{
Task.Run(async () =>
{
foreach (var username in badUsernames)
{
// emergency failsafe, for newlines and other mistaken entries
if (username.Length < 4)
continue;
if (member.Username.ToLower().Contains(username.ToLower()))
{
if (autoBannedUsersCache.Contains(member.Id))
break;
IEnumerable<ulong> enumerable = autoBannedUsersCache.Append(member.Id);
var guild = await discord.GetGuildAsync(cfgjson.ServerID);
await Bans.BanFromServerAsync(member.Id, "Automatic ban for matching patterns of common bot accounts. Please appeal if you are a human.", discord.CurrentUser.Id, guild, 7, null, default, true);
var embed = new DiscordEmbedBuilder()
.WithTimestamp(DateTime.Now)
.WithFooter($"User ID: {member.Id}", null)
.WithAuthor($"{member.Username}#{member.Discriminator}", null, member.AvatarUrl)
.AddField("Infringing name", member.Username)
.AddField("Matching pattern", username)
.WithColor(new DiscordColor(0xf03916));
var investigations = await discord.GetChannelAsync(cfgjson.InvestigationsChannelId);
await investigations.SendMessageAsync($"{cfgjson.Emoji.Banned} {member.Mention} was banned for matching blocked username patterns.", embed);
break;
}
}
});
}
async Task GuildMemberAdded(DiscordClient client, GuildMemberAddEventArgs e)
{
Task.Run(async () =>
{
if (e.Guild.Id != cfgjson.ServerID)
return;
var builder = new DiscordEmbedBuilder()
.WithColor(new DiscordColor(0x3E9D28))
.WithTimestamp(DateTimeOffset.Now)
.WithThumbnail(e.Member.AvatarUrl)
.WithAuthor(
name: $"{e.Member.Username}#{e.Member.Discriminator} has joined",
iconUrl: e.Member.AvatarUrl
)
.AddField("User", e.Member.Mention, false)
.AddField("User ID", e.Member.Id.ToString(), false)
.AddField("Action", "Joined the server", false)
.WithFooter($"{client.CurrentUser.Username}JoinEvent");
userLogChannel.SendMessageAsync($"{cfgjson.Emoji.UserJoin} **Member joined the server!** - {e.Member.Id}", builder);
if (await db.HashExistsAsync("mutes", e.Member.Id))
{
// todo: store per-guild
DiscordRole mutedRole = e.Guild.GetRole(cfgjson.MutedRole);
await e.Member.GrantRoleAsync(mutedRole, "Reapplying mute: possible mute evasion.");
}
CheckAndDehoistMemberAsync(e.Member);
if (avatars.Contains(e.Member.AvatarHash))
{
var _ = Bans.BanSilently(e.Guild, e.Member.Id, "Secret sauce");
await badMsgLog.SendMessageAsync($"{cfgjson.Emoji.Banned} Raid-banned {e.Member.Mention} for matching avatar: {e.Member.AvatarUrl.Replace("1024", "128")}");
}
});
}
async Task GuildMemberRemoved(DiscordClient client, GuildMemberRemoveEventArgs e)
{
Task.Run(async () =>
{
if (e.Guild.Id != cfgjson.ServerID)
return;
string rolesStr = "None";
if (e.Member.Roles.Count() != 0)
{
rolesStr = "";
foreach (DiscordRole role in e.Member.Roles.OrderBy(x => x.Position).Reverse())
{
rolesStr += role.Mention + " ";
}
}
var builder = new DiscordEmbedBuilder()
.WithColor(new DiscordColor(0xBA4119))
.WithTimestamp(DateTimeOffset.Now)
.WithThumbnail(e.Member.AvatarUrl)
.WithAuthor(
name: $"{e.Member.Username}#{e.Member.Discriminator} has left",
iconUrl: e.Member.AvatarUrl
)
.AddField("User", e.Member.Mention, false)
.AddField("User ID", e.Member.Id.ToString(), false)
.AddField("Action", "Left the server", false)
.AddField("Roles", rolesStr)
.WithFooter($"{client.CurrentUser.Username}LeaveEvent");
userLogChannel.SendMessageAsync($"{cfgjson.Emoji.UserLeave} **Member left the server!** - {e.Member.Id}", builder);
});
}
async Task GuildMemberUpdated(DiscordClient client, GuildMemberUpdateEventArgs e)
{
Task.Run(async () =>
{
var muteRole = e.Guild.GetRole(cfgjson.MutedRole);
var userMute = await db.HashGetAsync("mutes", e.Member.Id);
if (e.Member.Roles.Contains(muteRole) && userMute.IsNull)
{
MemberPunishment newMute = new()
{
MemberId = e.Member.Id,
ModId = discord.CurrentUser.Id,
ServerId = e.Guild.Id,
ExpireTime = null
};
db.HashSetAsync("mutes", e.Member.Id, JsonConvert.SerializeObject(newMute));
}
if (!userMute.IsNull && !e.Member.Roles.Contains(muteRole))
db.HashDeleteAsync("mutes", e.Member.Id);
CheckAndDehoistMemberAsync(e.Member);
UsernameCheckAsync(e.Member);
}
);
}
async Task UserUpdated(DiscordClient client, UserUpdateEventArgs e)
{
Task.Run(async () =>
{
var guild = await client.GetGuildAsync(cfgjson.ServerID);
var member = await guild.GetMemberAsync(e.UserAfter.Id);
CheckAndDehoistMemberAsync(member);
UsernameCheckAsync(member);
});
}
async Task MessageCreated(DiscordClient client, MessageCreateEventArgs e)
{
MessageEvent.MessageHandlerAsync(client, e.Message, e.Channel);
}
async Task MessageUpdated(DiscordClient client, MessageUpdateEventArgs e)
{
MessageEvent.MessageHandlerAsync(client, e.Message, e.Channel, true);
}
async Task CommandsNextService_CommandErrored(CommandsNextExtension cnext, CommandErrorEventArgs e)
{
if (e.Exception is CommandNotFoundException && (e.Command == null || e.Command.QualifiedName != "help"))
return;
e.Context.Client.Logger.LogError(CliptokEventID, e.Exception, "Exception occurred during {0}'s invocation of '{1}'", e.Context.User.Username, e.Context.Command.QualifiedName);
var exs = new List<Exception>();
if (e.Exception is AggregateException ae)
exs.AddRange(ae.InnerExceptions);
else
exs.Add(e.Exception);
foreach (var ex in exs)
{
if (ex is CommandNotFoundException && (e.Command == null || e.Command.QualifiedName != "help"))
return;
if (ex is ChecksFailedException && (e.Command.Name != "help"))
return;
var embed = new DiscordEmbedBuilder
{
Color = new DiscordColor("#FF0000"),
Title = "An exception occurred when executing a command",
Description = $"{cfgjson.Emoji.BSOD} `{e.Exception.GetType()}` occurred when executing `{e.Command.QualifiedName}`.",
Timestamp = DateTime.UtcNow
};
embed.WithFooter(discord.CurrentUser.Username, discord.CurrentUser.AvatarUrl)
.AddField("Message", ex.Message);
if (e.Exception.GetType().ToString() == "System.ArgumentException")
embed.AddField("Note", "This usually means that you used the command incorrectly.\n" +
"Please double-check how to use this command.");
await e.Context.RespondAsync(embed: embed.Build()).ConfigureAwait(false);
}
}
Task Discord_ThreadCreated(DiscordClient client, ThreadCreateEventArgs e)
{
client.Logger.LogDebug(eventId: CliptokEventID, $"Thread created in {e.Guild.Name}. Thread Name: {e.Thread.Name}");
return Task.CompletedTask;
}
Task Discord_ThreadUpdated(DiscordClient client, ThreadUpdateEventArgs e)
{
client.Logger.LogDebug(eventId: CliptokEventID, $"Thread updated in {e.Guild.Name}. New Thread Name: {e.ThreadAfter.Name}");
return Task.CompletedTask;
}
Task Discord_ThreadDeleted(DiscordClient client, ThreadDeleteEventArgs e)
{
client.Logger.LogDebug(eventId: CliptokEventID, $"Thread deleted in {e.Guild.Name}. Thread Name: {e.Thread.Name ?? "Unknown"}");
return Task.CompletedTask;
}
Task Discord_ThreadListSynced(DiscordClient client, ThreadListSyncEventArgs e)
{
client.Logger.LogDebug(eventId: CliptokEventID, $"Threads synced in {e.Guild.Name}.");
return Task.CompletedTask;
}
Task Discord_ThreadMemberUpdated(DiscordClient client, ThreadMemberUpdateEventArgs e)
{
client.Logger.LogDebug(eventId: CliptokEventID, $"Thread member updated.");
Console.WriteLine($"Discord_ThreadMemberUpdated fired for thread {e.ThreadMember.ThreadId}. User ID {e.ThreadMember.Id}.");
return Task.CompletedTask;
}
Task Discord_ThreadMembersUpdated(DiscordClient client, ThreadMembersUpdateEventArgs e)
{
client.Logger.LogDebug(eventId: CliptokEventID, $"Thread members updated in {e.Guild.Name}.");
return Task.CompletedTask;
}
discord.Ready += OnReady;
discord.MessageCreated += MessageCreated;
discord.MessageUpdated += MessageUpdated;
discord.GuildMemberAdded += GuildMemberAdded;
discord.GuildMemberRemoved += GuildMemberRemoved;
discord.MessageReactionAdded += OnReaction;
discord.GuildMemberUpdated += GuildMemberUpdated;
discord.UserUpdated += UserUpdated;
discord.ClientErrored += ClientError;
discord.ThreadCreated += Discord_ThreadCreated;
discord.ThreadUpdated += Discord_ThreadUpdated;
discord.ThreadDeleted += Discord_ThreadDeleted;
discord.ThreadListSynced += Discord_ThreadListSynced;
discord.ThreadMemberUpdated += Discord_ThreadMemberUpdated;
discord.ThreadMembersUpdated += Discord_ThreadMembersUpdated;
commands = discord.UseCommandsNext(new CommandsNextConfiguration
{
StringPrefixes = cfgjson.Core.Prefixes
}); ;
commands.RegisterCommands<Warnings>();
commands.RegisterCommands<MuteCmds>();
commands.RegisterCommands<UserRoleCmds>();
commands.RegisterCommands<ModCmds>();
commands.RegisterCommands<Lockdown>();
commands.RegisterCommands<Bans>();
commands.CommandErrored += CommandsNextService_CommandErrored;
await discord.ConnectAsync();
while (true)
{
await Task.Delay(10000);
Mutes.CheckMutesAsync();
ModCmds.CheckBansAsync();
ModCmds.CheckRemindersAsync();
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
}
}
}
}