-
Notifications
You must be signed in to change notification settings - Fork 1
/
Program.cs
875 lines (816 loc) · 35.6 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
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
using System;
using System.Text;
using System.IO;
using System.Linq;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Discord.Net;
using Discord;
using Discord.WebSocket;
using System.Diagnostics;
using FreneticUtilities.FreneticDataSyntax;
using FreneticUtilities.FreneticToolkit;
using FreneticUtilities.FreneticExtensions;
namespace FreneticDiscordBot
{
public class FreneticDiscordBot
{
// TODO: Clean and/or rewrite? This static-abusing mess is very lazy.
public Random random = new();
public const string CONFIG_FOLDER = "./config/";
public const string TOKEN_FILE = CONFIG_FOLDER + "token.txt";
public const string CONFIG_FILE = CONFIG_FOLDER + "config.fds";
public static readonly string TOKEN = File.ReadAllText(TOKEN_FILE);
public const string POSITIVE_PREFIX = "+> ";
public const string NEGATIVE_PREFIX = "-> ";
public const string TODO_PREFIX = NEGATIVE_PREFIX + "// TODO: ";
public static string[] Quotes = File.ReadAllText("./quotes.txt").Replace("\r\n", "\n").Replace("\r", "\n").Replace("\n\n", ((char)0x01).ToString()).Split((char)0x01);
public FDSSection ConfigFile = new();
public LockObject ConfigLock = new();
public DiscordSocketClient client;
public RoleBouncer Role_Bouncer;
public GuildEveryoneRole Guild_Everyone_Role;
public InfoPostManager Info_Post_Manager;
public CancellationTokenSource CancelTok = new();
public void Respond(SocketMessage message)
{
string[] mesdat = message.Content.Split(' ');
StringBuilder resBuild = new(message.Content.Length);
List<string> cmds = [];
for (int i = 0; i < mesdat.Length; i++)
{
if (mesdat[i].Contains('<') && mesdat[i].Contains('>'))
{
continue;
}
resBuild.Append(mesdat[i]).Append(' ');
if (mesdat[i].Length > 0)
{
cmds.Add(mesdat[i]);
}
}
if (cmds.Count == 0)
{
Console.WriteLine("Empty input, ignoring: " + message.Author.Username);
return;
}
string fullMsg = resBuild.ToString();
Console.WriteLine("Found input from: (" + message.Author.Username + "), in channel: " + message.Channel.Name + ": " + fullMsg);
string lowCmd = cmds[0].ToLowerInvariant();
cmds.RemoveAt(0);
if (CommonCmds.TryGetValue(lowCmd, out Action<string[], SocketMessage> acto))
{
acto.Invoke([.. cmds], message);
}
else
{
message.Channel.SendMessageAsync(NEGATIVE_PREFIX + "Unknown command. Consider the __**help**__ command?").Wait();
}
}
public Dictionary<string, Action<string[], SocketMessage>> CommonCmds = new(1024);
public class QuoteSeen
{
public int QID;
public DateTime Time;
}
public List<QuoteSeen> QuotesSeen = [];
public bool QuoteWasSeen(int qid)
{
for (int i = 0; i < QuotesSeen.Count; i++)
{
if (QuotesSeen[i].QID == qid)
{
return true;
}
}
return false;
}
void CMD_ShowQuote(string[] cmds, SocketMessage message)
{
for (int i = QuotesSeen.Count - 1; i >= 0; i--)
{
if (DateTime.UtcNow.Subtract(QuotesSeen[i].Time).TotalMinutes >= 5)
{
QuotesSeen.RemoveAt(i);
}
}
int qid = -1;
if (cmds.Length == 0)
{
for (int i = 0; i < 15; i++)
{
qid = random.Next(Quotes.Length);
if (!QuoteWasSeen(qid))
{
break;
}
}
}
else if (int.TryParse(cmds[0], out qid))
{
qid--;
if (qid < 0)
{
qid = 0;
}
if (qid >= Quotes.Length)
{
qid = Quotes.Length - 1;
}
}
else
{
List<int> spots = [];
string input_opt = string.Join(" ", cmds);
for (int i = 0; i < Quotes.Length; i++)
{
if (Quotes[i].ToLowerFast().Contains(input_opt.ToLowerFast()))
{
spots.Add(i);
}
}
if (spots.Count == 0)
{
message.Channel.SendMessageAsync(NEGATIVE_PREFIX + "Unable to find that quote! Sorry :(").Wait();
return;
}
for (int s = 0; s < 15; s++)
{
int temp = random.Next(spots.Count);
qid = spots[temp];
if (!QuoteWasSeen(qid))
{
break;
}
}
}
if (qid >= 0 && qid < Quotes.Length)
{
QuotesSeen.Add(new QuoteSeen() { QID = qid, Time = DateTime.UtcNow });
string quoteRes = POSITIVE_PREFIX + "Quote **" + (qid + 1) + "**:\n```xml\n" + Quotes[qid] + "\n```\n";
message.Channel.SendMessageAsync(quoteRes).Wait();
}
}
public static string CmdsHelp =
"`help`, `quote`, `hello`, `frenetic`, `whois`, "
+ "...";
public static string CmdsAdminHelp =
"`restart`, `listeninto`, `redirectnotice`, "
+ "...";
void CMD_Help(string[] cmds, SocketMessage message)
{
if (IsBotCommander(message.Author))
{
message.Channel.SendMessageAsync(POSITIVE_PREFIX + "Available Commands:\n" + CmdsHelp
+ "\nAvailable admin commands: " + CmdsAdminHelp).Wait();
}
else
{
message.Channel.SendMessageAsync(POSITIVE_PREFIX + "Available Commands:\n" + CmdsHelp).Wait();
}
}
void CMD_Hello(string[] cmds, SocketMessage message)
{
message.Channel.SendMessageAsync(POSITIVE_PREFIX + "Hi! I'm a bot! Find my source code at https://github.com/FreneticLLC/FreneticDiscordBot").Wait();
}
void CMD_SelfInfo(string[] cmds, SocketMessage message)
{
SocketUser user = message.Author;
foreach (SocketUser tuser in message.MentionedUsers)
{
if (tuser.Id != client.CurrentUser.Id)
{
user = tuser;
break;
}
}
if (cmds.Length > 0 && ulong.TryParse(cmds[0], out ulong userId))
{
user = client.GetUser(userId) ?? user;
}
EmbedBuilder bed = new();
EmbedAuthorBuilder auth = new()
{
Name = user.Username + "#" + user.Discriminator,
IconUrl = user.GetAvatarUrl(),
Url = user.GetAvatarUrl()
};
bed.Author = auth;
bed.Color = new Color(0xC8, 0x74, 0x4B);
bed.Title = "Who is " + auth.Name + "?";
bed.Description = auth.Name + " is a Discord " + (user.IsBot ? "bot" : (user.IsWebhook ? "webhook" : "user")) + "!";
bed.AddField((efb) => efb.WithName("Discord ID").WithValue(user.Id));
bed.AddField((efb) => efb.WithName("Discord Join Date").WithValue(FormatDT(user.CreatedAt)));
bed.AddField((efb) => efb.WithName("Current Status").WithValue(user.Status));
bed.AddField((efb) => efb.WithName("Current Activity").WithValue(user.Activities.IsEmpty() ? "Nothing." : (user.Activities.First().Type + ": " + user.Activities.First().Name)));
if (user is SocketGuildUser iguser)
{
if (iguser.JoinedAt.HasValue)
{
bed.AddField(efb => efb.WithName("Joined Here Date").WithValue(FormatDT(iguser.JoinedAt.Value)));
}
if (iguser.Nickname != null)
{
bed.AddField(efb => efb.WithName("Current Nickname").WithValue(iguser.Nickname));
}
string[] roles = iguser.Roles.Where((r) => !r.IsEveryone).Select((r) => r.Name).ToArray();
bed.AddField((efb) => efb.WithName("Current Roles").WithValue(roles.Length > 0 ? string.Join(", ", roles) : "None currently."));
}
bed.Footer = new EmbedFooterBuilder().WithIconUrl(client.CurrentUser.GetAvatarUrl()).WithText("Info provided by FreneticDiscordBot, which is Copyright (C) Frenetic LLC");
message.Channel.SendMessageAsync(POSITIVE_PREFIX, embed: bed.Build()).Wait();
}
public static bool IsBotCommander(SocketUser usr)
{
return (usr as SocketGuildUser).Roles.Where((role) => role.Name.ToLowerFast() == "botcommander").FirstOrDefault() != null;
}
void CMD_Restart(string[] cmds, SocketMessage message)
{
// NOTE: This implies a one-guild bot. A multi-guild bot probably shouldn't have this "BotCommander" role-based verification.
// But under current scale, a true-admin confirmation isn't worth the bother.
if (!IsBotCommander(message.Author))
{
message.Channel.SendMessageAsync(NEGATIVE_PREFIX + "Nope! That's not for you!").Wait();
return;
}
if (!File.Exists("./start.sh"))
{
message.Channel.SendMessageAsync(NEGATIVE_PREFIX + "Nope! That's not valid for my current configuration!").Wait();
}
message.Channel.SendMessageAsync(POSITIVE_PREFIX + "Yes, boss. Restarting now...").Wait();
Process.Start("sh", "./start.sh " + message.Channel.Id);
Task.Factory.StartNew(() =>
{
Console.WriteLine("Shutdown start...");
for (int i = 0; i < 15; i++)
{
Console.WriteLine("T Minus " + (15 - i));
Task.Delay(1000).Wait();
}
Console.WriteLine("Shutdown!");
Environment.Exit(0);
});
client.StopAsync().Wait();
}
static string Pad2(int num)
{
return num < 10 ? "0" + num : num.ToString();
}
static string AddPlus(double d)
{
return d < 0 ? d.ToString() : "+" + d;
}
static string FormatDT(DateTimeOffset dtoff)
{
return dtoff.Year + "/" + Pad2(dtoff.Month) + "/" + Pad2(dtoff.Day)
+ " " + Pad2(dtoff.Hour) + ":" + Pad2(dtoff.Minute) + ":" + Pad2(dtoff.Second)
+ " UTC" + AddPlus(dtoff.Offset.TotalHours);
}
void CMD_WhatIsFrenetic(string[] cmds, SocketMessage message)
{
EmbedBuilder bed = new();
EmbedAuthorBuilder auth = new()
{
Name = "Frenetic LLC",
IconUrl = client.CurrentUser.GetAvatarUrl(),
Url = "https://freneticllc.com"
};
bed.Author = auth;
bed.Color = new Color(0xC8, 0x74, 0x4B);
bed.Title = "What is Frenetic LLC?";
bed.Description = "Frenetic LLC is a California registered limited liability company.";
bed.AddField((efb) => efb.WithName("What does Frenetic LLC do?").WithValue("In short: We make games!"));
bed.AddField((efb) => efb.WithName("Who is Frenetic LLC?").WithValue("We are an international team! Check out the #meet-the-team channel on the Frenetic LLC official Discord!"));
bed.Footer = new EmbedFooterBuilder().WithIconUrl(auth.IconUrl).WithText("Copyright (C) Frenetic LLC");
message.Channel.SendMessageAsync(POSITIVE_PREFIX, embed: bed.Build()).Wait();
}
void CMD_ListenInto(string[] cmds, SocketMessage message)
{
if (!IsBotCommander(message.Author))
{
message.Channel.SendMessageAsync(NEGATIVE_PREFIX + "Nope! That's not for you!").Wait();
return;
}
ulong serverId = (message.Channel as IGuildChannel).Guild.Id;
KnownServer ks = ServersConfig.GetOrAdd(serverId, (id) => new KnownServer());
if (cmds.Length == 0)
{
message.Channel.SendMessageAsync(NEGATIVE_PREFIX + "Nope! Consult documentation!").Wait();
return;
}
String goal = cmds[0].ToLowerInvariant();
IEnumerable<ITextChannel> channels = (message.Channel as IGuildChannel)
.Guild.GetTextChannelsAsync().Result.Where((tc) => tc.Name.ToLowerInvariant().Replace("#", "").Equals(goal));
if (!channels.Any())
{
message.Channel.SendMessageAsync(POSITIVE_PREFIX + "Disabling sending.").Wait();
IEnumerable<ITextChannel> channels2 = (message.Channel as IGuildChannel).Guild.GetTextChannelsAsync().Result;
StringBuilder sbRes = new();
foreach (ITextChannel itc in channels2)
{
sbRes.Append('`').Append(itc.Name).Append("`, ");
}
message.Channel.SendMessageAsync(POSITIVE_PREFIX + "Given: `" + goal + "`, Available: " + sbRes.ToString()).Wait();
goal = null;
}
else
{
message.Channel.SendMessageAsync(POSITIVE_PREFIX + "Listening into: " + goal).Wait();
}
lock (ConfigLock)
{
ks.AllChannelsTo = goal;
ConfigFile.Set("servers." + serverId + ".all_channels_to", goal);
}
SaveChannelConfig();
}
void CMD_RedirectNotice(string[] cmds, SocketMessage message)
{
if (!IsBotCommander(message.Author))
{
message.Channel.SendMessageAsync(NEGATIVE_PREFIX + "Nope! That's not for you!").Wait();
return;
}
ulong serverId = (message.Channel as IGuildChannel).Guild.Id;
ulong channelId = message.Channel.Id;
KnownServer ks = ServersConfig.GetOrAdd(serverId, (id) => new KnownServer());
if (cmds.Length == 0)
{
message.Channel.SendMessageAsync(NEGATIVE_PREFIX + "Nope! Consult documentation!").Wait();
return;
}
String goal = cmds[0].ToLowerInvariant();
IEnumerable<ITextChannel> channels = (message.Channel as IGuildChannel)
.Guild.GetTextChannelsAsync().Result.Where((tc) => tc.Name.ToLowerInvariant().Replace("#", "").Equals(goal));
if (!channels.Any())
{
message.Channel.SendMessageAsync(POSITIVE_PREFIX + "Disabling redirect notice.").Wait();
IEnumerable<ITextChannel> channels2 = (message.Channel as IGuildChannel).Guild.GetTextChannelsAsync().Result;
StringBuilder sbRes = new();
foreach (ITextChannel itc in channels2)
{
sbRes.Append('`').Append(itc.Name).Append("`, ");
}
message.Channel.SendMessageAsync(POSITIVE_PREFIX + "Given: `" + goal + "`, Available: " + sbRes.ToString()).Wait();
goal = null;
}
else
{
message.Channel.SendMessageAsync(POSITIVE_PREFIX + "Notifying redirect to: " + goal).Wait();
}
lock (ConfigLock)
{
if (goal == null)
{
ks.ChannelRedirectNotices.Remove(channelId);
}
else
{
ulong dest = channels.First().Id;
ks.ChannelRedirectNotices[channelId] = new ChannelRedirectNotice() { RedirectToChannel = dest };
ConfigFile.Set("servers." + serverId + ".channel_redirect_notices." + channelId, dest);
}
}
SaveChannelConfig();
}
public void SaveChannelConfig()
{
lock (reSaveLock)
{
ConfigFile.SaveToFile(CONFIG_FILE);
}
}
public static LockObject reSaveLock = new();
void DefaultCommands()
{
// Various
CommonCmds["quotes"] = CMD_ShowQuote;
CommonCmds["quote"] = CMD_ShowQuote;
CommonCmds["q"] = CMD_ShowQuote;
CommonCmds["help"] = CMD_Help;
CommonCmds["halp"] = CMD_Help;
CommonCmds["helps"] = CMD_Help;
CommonCmds["halps"] = CMD_Help;
CommonCmds["hel"] = CMD_Help;
CommonCmds["hal"] = CMD_Help;
CommonCmds["h"] = CMD_Help;
CommonCmds["hello"] = CMD_Hello;
CommonCmds["hi"] = CMD_Hello;
CommonCmds["hey"] = CMD_Hello;
CommonCmds["source"] = CMD_Hello;
CommonCmds["src"] = CMD_Hello;
CommonCmds["github"] = CMD_Hello;
CommonCmds["git"] = CMD_Hello;
CommonCmds["hub"] = CMD_Hello;
CommonCmds["who"] = CMD_WhatIsFrenetic;
CommonCmds["what"] = CMD_WhatIsFrenetic;
CommonCmds["where"] = CMD_WhatIsFrenetic;
CommonCmds["why"] = CMD_WhatIsFrenetic;
CommonCmds["frenetic"] = CMD_WhatIsFrenetic;
CommonCmds["llc"] = CMD_WhatIsFrenetic;
CommonCmds["freneticllc"] = CMD_WhatIsFrenetic;
CommonCmds["website"] = CMD_WhatIsFrenetic;
CommonCmds["team"] = CMD_WhatIsFrenetic;
CommonCmds["company"] = CMD_WhatIsFrenetic;
CommonCmds["business"] = CMD_WhatIsFrenetic;
CommonCmds["restart"] = CMD_Restart;
CommonCmds["selfinfo"] = CMD_SelfInfo;
CommonCmds["whoami"] = CMD_SelfInfo;
CommonCmds["whois"] = CMD_SelfInfo;
CommonCmds["userinfo"] = CMD_SelfInfo;
CommonCmds["userprofile"] = CMD_SelfInfo;
CommonCmds["profile"] = CMD_SelfInfo;
CommonCmds["prof"] = CMD_SelfInfo;
// Admin
CommonCmds["listeninto"] = CMD_ListenInto;
CommonCmds["redirectnotice"] = CMD_RedirectNotice;
}
public ConcurrentDictionary<ulong, KnownServer> ServersConfig = new();
public bool ConnectedOnce = false;
public bool ConnectedCurrently = false;
public static FreneticDiscordBot CurrentBot = null;
static void Main(string[] args)
{
CurrentBot = new FreneticDiscordBot(args);
while (true)
{
string read = Console.ReadLine();
string[] dats = read.Split([' '], 2);
string cmd = dats[0].ToLowerInvariant();
if (cmd == "quit" || cmd == "stop" || cmd == "exit")
{
CurrentBot.CancelTok.Cancel();
CurrentBot.client.StopAsync().Wait();
Environment.Exit(0);
}
else if (cmd == "reset")
{
CurrentBot.ForceRestartBot();
}
else if (cmd == "infopost" || cmd == "infopostcheck" || cmd == "check")
{
CurrentBot.Info_Post_Manager?.RunCheck();
}
}
}
public FreneticDiscordBot(string[] args)
{
Console.WriteLine("Preparing...");
DefaultCommands();
if (File.Exists(CONFIG_FILE))
{
ConfigFile = FDSUtility.ReadFile(CONFIG_FILE);
FDSSection serversListSection = ConfigFile.GetSection("servers");
foreach (string serverIdKey in serversListSection.GetRootKeys())
{
ulong serverId = ulong.Parse(serverIdKey);
KnownServer serverObj = new();
ServersConfig[serverId] = serverObj;
FDSSection serverSection = serversListSection.GetSection(serverIdKey);
if (serverSection.HasKey("all_channels_to"))
{
string serverAllChannelsTo = serverSection.GetString("all_channels_to");
serverObj.AllChannelsTo = serverAllChannelsTo;
}
if (serverSection.HasKey("channel_redirect_notices"))
{
FDSSection channelRedirectListSection = serverSection.GetSection("channel_redirect_notices");
foreach (string channelRedirectIdKey in channelRedirectListSection.GetRootKeys())
{
ulong channelSource = ulong.Parse(channelRedirectIdKey);
ulong channelTarget = channelRedirectListSection.GetUlong(channelRedirectIdKey).Value;
serverObj.ChannelRedirectNotices[channelSource] = new ChannelRedirectNotice() { RedirectToChannel = channelTarget };
}
}
}
}
Console.WriteLine("Loading Discord...");
DiscordSocketConfig config = new()
{
MessageCacheSize = 256,
AlwaysDownloadUsers = true,
};
config.GatewayIntents |= GatewayIntents.MessageContent | GatewayIntents.GuildMembers;
client = new DiscordSocketClient(config);
FDSSection bouncerSection = ConfigFile.GetSection("bouncer");
if (bouncerSection is not null)
{
Role_Bouncer = new();
Role_Bouncer.Init(bouncerSection, client);
}
FDSSection guildEveryoneSection = ConfigFile.GetSection("guild_everyone_role");
if (guildEveryoneSection is not null)
{
Guild_Everyone_Role = new();
Guild_Everyone_Role.Init(guildEveryoneSection, client);
}
FDSSection infoPostSection = ConfigFile.GetSection("info_post_manager");
if (infoPostSection is not null)
{
Info_Post_Manager = new();
Info_Post_Manager.Init(infoPostSection, client, this);
}
client.Ready += () =>
{
if (StopAllLogic)
{
return Task.CompletedTask;
}
Console.WriteLine($"Bot is in guilds:\n{client.Guilds.Select(g => $"{g.Id}: {g.Name}").JoinString("\n")}");
ConnectedCurrently = true;
client.SetGameAsync("https://freneticllc.com").Wait();
if (ConnectedOnce)
{
return Task.CompletedTask;
}
Console.WriteLine("Args: " + args.Length);
if (args.Length > 0 && ulong.TryParse(args[0], out ulong a1))
{
ISocketMessageChannel chan = client.GetChannel(a1) as ISocketMessageChannel;
Console.WriteLine("Restarted as per request in channel: " + chan.Name);
chan.SendMessageAsync(POSITIVE_PREFIX + "Connected and ready!").Wait();
}
ConnectedOnce = true;
return Task.CompletedTask;
};
client.MessageReceived += (message) =>
{
if (StopAllLogic)
{
return Task.CompletedTask;
}
if (message.Author.Id == client.CurrentUser.Id)
{
return Task.CompletedTask;
}
LoopsSilent = 0;
if (message.Author.IsBot || message.Author.IsWebhook)
{
return Task.CompletedTask;
}
if (message.Channel.Name.StartsWith('@') || message.Channel is not SocketGuildChannel sgc)
{
Console.WriteLine("Refused message from (" + message.Author.Username + "): (Invalid Channel: " + message.Channel.Name + "): " + message.Content);
return Task.CompletedTask;
}
bool mentionedMe = message.MentionedUsers.Any((su) => su.Id == client.CurrentUser.Id);
Console.WriteLine("Parsing message from (" + message.Author.Username + "), in channel: " + message.Channel.Name + ": " + message.Content);
if (ServersConfig.TryGetValue(sgc.Guild.Id, out KnownServer serverSettings))
{
if (serverSettings.ChannelRedirectNotices.TryGetValue(message.Channel.Id, out ChannelRedirectNotice notice))
{
if (!notice.UserLastNotices.TryGetValue(message.Author.Id, out DateTimeOffset dto)
|| DateTimeOffset.UtcNow.Subtract(dto).TotalMinutes > 10.0)
{
notice.UserLastNotices[message.Author.Id] = DateTimeOffset.UtcNow;
Console.WriteLine("Telling user to post in redirect target instead of here.");
message.Channel.SendMessageAsync(NEGATIVE_PREFIX + "Please post in <#" + notice.RedirectToChannel + "> not here.").Wait();
}
}
}
if (mentionedMe)
{
try
{
Respond(message);
}
catch (Exception ex)
{
if (ex is ThreadAbortException)
{
throw;
}
Console.WriteLine("Error handling command: " + ex.ToString());
}
}
else
{
String mesLow = message.Content.ToLowerInvariant();
if (mesLow.StartsWith("yay"))
{
message.Channel.SendMessageAsync(POSITIVE_PREFIX + "YAY!!!").Wait();
}
}
return Task.CompletedTask;
};
client.MessageDeleted += (m, c) =>
{
if (StopAllLogic)
{
return Task.CompletedTask;
}
Console.WriteLine("A message was deleted!");
if (c.GetOrDownloadAsync().Result is not IGuildChannel channel)
{
Console.WriteLine("But it was in a weird channel?");
return Task.CompletedTask;
}
if (!ServersConfig.TryGetValue(channel.Guild.Id, out KnownServer ks))
{
Console.WriteLine("But it wasn't in a known guild.");
return Task.CompletedTask;
}
if (ks.AllChannelsTo == null)
{
Console.WriteLine("But it wasn't in a listening zone.");
return Task.CompletedTask;
}
IEnumerable<ITextChannel> channels = channel.Guild.GetTextChannelsAsync().Result.Where((tc) => tc.Name.ToLowerInvariant().Replace("#", "").Equals(ks.AllChannelsTo));
if (!channels.Any())
{
Console.WriteLine("Failed to match a channel: " + ks.AllChannelsTo);
return Task.CompletedTask;
}
ITextChannel outputter = channels.First();
IMessage mValue;
if (!m.HasValue)
{
Console.WriteLine("But I don't see its data... Outputting a blankness note.");
outputter.SendMessageAsync(POSITIVE_PREFIX + "Message in `" + channel.Name + "` with id `" + c.Id + "` deleted. Specific content not known (likely an old message).").Wait();
return Task.CompletedTask;
}
else
{
mValue = m.Value;
}
if (mValue.Author.Id == client.CurrentUser.Id)
{
Console.WriteLine("Wait, I did that!");
return Task.CompletedTask;
}
if (mValue.Author.IsBot || mValue.Author.IsWebhook)
{
Console.WriteLine("But it was bot-posted!");
return Task.CompletedTask;
}
outputter.SendMessageAsync(POSITIVE_PREFIX + "Message deleted (`" + mValue.Channel.Name + "`)... message from: `"
+ mValue.Author.Username + "#" + mValue.Author.Discriminator
+ "`: ```\n" + mValue.Content.Replace('`', '\'') + "\n```").Wait();
Console.WriteLine("Outputted!");
return Task.CompletedTask;
};
client.MessageUpdated += (m, mNew, c) =>
{
if (StopAllLogic)
{
return Task.CompletedTask;
}
Console.WriteLine("A message was edited!");
if (c is not IGuildChannel channel)
{
Console.WriteLine("But it was in a weird channel?");
return Task.CompletedTask;
}
if (!ServersConfig.TryGetValue(channel.Guild.Id, out KnownServer ks))
{
Console.WriteLine("But it wasn't in a known guild.");
return Task.CompletedTask;
}
if (ks.AllChannelsTo == null)
{
Console.WriteLine("But it wasn't in a listening zone.");
return Task.CompletedTask;
}
IEnumerable<ITextChannel> channels = channel.Guild.GetTextChannelsAsync().Result.Where((tc) => tc.Name.ToLowerInvariant().Replace("#", "").Equals(ks.AllChannelsTo));
if (!channels.Any())
{
Console.WriteLine("Failed to match a channel: " + ks.AllChannelsTo);
return Task.CompletedTask;
}
ITextChannel outputter = channels.First();
if (mNew.Author.Id == client.CurrentUser.Id)
{
Console.WriteLine("Wait, I did that!");
return Task.CompletedTask;
}
if (mNew.Author.IsBot || mNew.Author.IsWebhook)
{
Console.WriteLine("But it was bot-posted!");
return Task.CompletedTask;
}
IMessage mValue;
if (!m.HasValue)
{
outputter.SendMessageAsync(POSITIVE_PREFIX + "Message edited(`" + mNew.Channel.Name + "`)... message from: `"
+ mNew.Author.Username + "#" + mNew.Author.Discriminator
+ "`:\n(Original message unknown)\nBecame:\n```"
+ mNew.Content.Replace('`', '\'') + "\n```");
Console.WriteLine("But I don't see its data... outputting what I can!");
return Task.CompletedTask;
}
else
{
mValue = m.Value;
}
if (mNew.Content == mValue.Content)
{
Console.WriteLine("But it was not an edit (reaction or similar instead)!");
return Task.CompletedTask;
}
outputter.SendMessageAsync(POSITIVE_PREFIX + "Message edited(`" + mValue.Channel.Name + "`)... message from: `"
+ mValue.Author.Username + "#" + mValue.Author.Discriminator
+ "`: ```\n" + mValue.Content.Replace('`', '\'') + "\n```\nBecame:\n```"
+ mNew.Content.Replace('`', '\'') + "\n```");
return Task.CompletedTask;
};
Console.WriteLine("Prepping monitor...");
Task.Factory.StartNew(() =>
{
while (true)
{
Task.Delay(MonitorLoopTime).Wait();
if (StopAllLogic)
{
return;
}
try
{
IdleTick?.Invoke();
MonitorLoop();
}
catch (Exception ex)
{
if (ex is ThreadAbortException)
{
throw;
}
Console.WriteLine("Connection monitor loop had exception: " + ex.ToString());
}
}
});
Console.WriteLine("Logging in to Discord...");
client.LoginAsync(TokenType.Bot, TOKEN).Wait();
Console.WriteLine("Connecting to Discord...");
client.StartAsync().Wait();
Console.WriteLine("Running Discord!");
}
public TimeSpan MonitorLoopTime = new(hours: 0, minutes: 1, seconds: 0);
public bool MonitorWasFailedAlready = false;
public bool StopAllLogic = false;
public void ForceRestartBot()
{
CancelTok.Cancel();
lock (MonitorLock)
{
StopAllLogic = true;
}
Task.Factory.StartNew(() =>
{
client.StopAsync().Wait();
});
CurrentBot = new FreneticDiscordBot([]);
}
public LockObject MonitorLock = new();
public long LoopsSilent = 0;
public long LoopsTotal = 0;
public Action IdleTick;
public void MonitorLoop()
{
bool isConnected;
lock (MonitorLock)
{
LoopsSilent++;
LoopsTotal++;
isConnected = ConnectedCurrently && client.ConnectionState == ConnectionState.Connected;
}
if (!isConnected)
{
Console.WriteLine("Monitor detected disconnected state!");
}
if (LoopsSilent > 60)
{
Console.WriteLine("Monitor detected over an hour of silence, and is assuming a disconnected state!");
isConnected = false;
}
if (LoopsTotal > 60 * 12)
{
Console.WriteLine("Monitor detected that the bot has been running for over 12 hours, and will restart soon!");
isConnected = false;
}
if (isConnected)
{
MonitorWasFailedAlready = false;
}
else
{
if (MonitorWasFailedAlready)
{
Console.WriteLine("Monitor is enforcing a restart!");
ForceRestartBot();
}
MonitorWasFailedAlready = true;
}
}
public class ChannelRedirectNotice
{
public ulong RedirectToChannel;
public ConcurrentDictionary<ulong, DateTimeOffset> UserLastNotices = new();
}
public class KnownServer
{
public string AllChannelsTo = null;
public Dictionary<ulong, ChannelRedirectNotice> ChannelRedirectNotices = [];
}
}
}